change-manager.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. import { trackChangesAnnotation } from '../realtime'
  2. import { clearChangeMarkers, buildChangeMarkers } from '../track-changes'
  3. import {
  4. setVerticalOverflow,
  5. updateSetsVerticalOverflow,
  6. editorVerticalTopPadding,
  7. } from '../vertical-overflow'
  8. import { EditorSelection, EditorState } from '@codemirror/state'
  9. import { EditorView, ViewUpdate } from '@codemirror/view'
  10. import { CurrentDoc } from '../../../../../../types/current-doc'
  11. import { fullHeightCoordsAtPos } from '../../utils/layer'
  12. import { debounce } from 'lodash'
  13. // With less than this number of entries, don't bother culling to avoid
  14. // little UI jumps when scrolling.
  15. const CULL_AFTER = Infinity // Note: was 100 but couldn't scroll to see items outside the viewport
  16. export const dispatchEditorEvent = (type: string, payload?: unknown) => {
  17. window.setTimeout(() => {
  18. window.dispatchEvent(
  19. new CustomEvent('editor:event', {
  20. detail: { type, payload },
  21. })
  22. )
  23. }, 0)
  24. }
  25. export type ChangeManager = {
  26. initialize: () => void
  27. handleUpdate: (update: ViewUpdate) => void
  28. destroy: () => void
  29. }
  30. export const createChangeManager = (
  31. view: EditorView,
  32. currentDoc: CurrentDoc
  33. ): ChangeManager => {
  34. /**
  35. * Calculate the screen coordinates of each entry (change or comment),
  36. * for use in the review panel.
  37. *
  38. * Returns a boolean indicating whether the visibility of any entry has changed
  39. */
  40. const recalculateScreenPositions = (entries?: Record<string, any>) => {
  41. const contentRect = view.contentDOM.getBoundingClientRect()
  42. const { doc } = view.state
  43. const items = Object.values(entries || {})
  44. const allVisible = items.length <= CULL_AFTER
  45. let visibilityChanged = false
  46. const docLength = doc.length
  47. const editorPaddingTop = editorVerticalTopPadding(view)
  48. for (const entry of items) {
  49. // TODO: clamp to max row and column, account for folding?
  50. const coords = fullHeightCoordsAtPos(
  51. view,
  52. Math.min(entry.offset, docLength) // avoid exception for comments at end of document when deleting text
  53. )
  54. if (coords) {
  55. const y = Math.round(coords.top - contentRect.top - editorPaddingTop)
  56. const height = Math.round(coords.bottom - coords.top)
  57. entry.screenPos = { y, height, editorPaddingTop }
  58. }
  59. if (allVisible) {
  60. if (!entry.visible) {
  61. visibilityChanged = true
  62. }
  63. entry.visible = true
  64. }
  65. }
  66. if (!allVisible) {
  67. const { from, to } = view.viewport
  68. for (const entry of items) {
  69. const previouslyVisible = entry.visible
  70. entry.visible = entry.offset >= from && entry.offset <= to
  71. if (previouslyVisible !== entry.visible) {
  72. visibilityChanged = true
  73. }
  74. }
  75. }
  76. return visibilityChanged
  77. }
  78. /**
  79. * Add a comment (thread) to the ShareJS doc when it's created
  80. */
  81. const addComment = (offset: number, length: number, threadId: string) => {
  82. currentDoc.submitOp({
  83. c: view.state.doc.sliceString(offset, offset + length),
  84. p: offset,
  85. t: threadId,
  86. })
  87. }
  88. /**
  89. * Remove a comment (thread) from the range tracker when it's deleted
  90. */
  91. const removeComment = (commentId: string) => {
  92. currentDoc.ranges.removeCommentId(commentId)
  93. }
  94. /**
  95. * Remove tracked changes from the range tracker when they're accepted
  96. */
  97. const acceptChanges = (changeIds: string[]) => {
  98. currentDoc.ranges.removeChangeIds(changeIds)
  99. }
  100. /**
  101. * Remove tracked changes from the range tracker when they're rejected,
  102. * and restore the original content
  103. */
  104. const rejectChanges = (changeIds: string[]) => {
  105. const changes: any[] = currentDoc.ranges.getChanges(changeIds)
  106. if (changes.length === 0) {
  107. return {}
  108. }
  109. // When doing bulk rejections, adjacent changes might interact with each other.
  110. // Consider an insertion with an adjacent deletion (which is a common use-case, replacing words):
  111. //
  112. // "foo bar baz" -> "foo quux baz"
  113. //
  114. // The change above will be modeled with two ops, with the insertion going first:
  115. //
  116. // foo quux baz
  117. // |--| -> insertion of "quux", op 1, at position 4
  118. // | -> deletion of "bar", op 2, pushed forward by "quux" to position 8
  119. //
  120. // When rejecting these changes at once, if the insertion is rejected first, we get unexpected
  121. // results. What happens is:
  122. //
  123. // 1) Rejecting the insertion deletes the added word "quux", i.e., it removes 4 chars
  124. // starting from position 4;
  125. //
  126. // "foo quux baz" -> "foo baz"
  127. // |--| -> 4 characters to be removed
  128. //
  129. // 2) Rejecting the deletion adds the deleted word "bar" at position 8 (i.e. it will act as if
  130. // the word "quuux" was still present).
  131. //
  132. // "foo baz" -> "foo bazbar"
  133. // | -> deletion of "bar" is reverted by reinserting "bar" at position 8
  134. //
  135. // While the intended result would be "foo bar baz", what we get is:
  136. //
  137. // "foo bazbar" (note "bar" readded at position 8)
  138. //
  139. // The issue happens because of step 1. To revert the insertion of "quux", 4 characters are deleted
  140. // from position 4. This includes the position where the deletion exists; when that position is
  141. // cleared, the RangesTracker considers that the deletion is gone and stops tracking/updating it.
  142. // As we still hold a reference to it, the code tries to revert it by readding the deleted text, but
  143. // does so at the outdated position (position 8, which was valid when "quux" was present).
  144. //
  145. // To avoid this kind of problem, we need to make sure that reverting operations doesn't affect
  146. // subsequent operations that come after. Reverse sorting the operations based on position will
  147. // achieve it; in the case above, it makes sure that the the deletion is reverted first:
  148. //
  149. // 1) Rejecting the deletion adds the deleted word "bar" at position 8
  150. //
  151. // "foo quux baz" -> "foo quuxbar baz"
  152. // | -> deletion of "bar" is reverted by
  153. // reinserting "bar" at position 8
  154. //
  155. // 2) Rejecting the insertion deletes the added word "quux", i.e., it removes 4 chars
  156. // starting from position 4 and achieves the expected result:
  157. //
  158. // "foo quuxbar baz" -> "foo bar baz"
  159. // |--| -> 4 characters to be removed
  160. changes.sort((a, b) => b.op.p - a.op.p)
  161. const changesToDispatch = changes.map(change => {
  162. const { op } = change
  163. const opType = 'i' in op ? 'i' : 'c' in op ? 'c' : 'd'
  164. switch (opType) {
  165. case 'd': {
  166. return {
  167. from: op.p,
  168. to: op.p,
  169. insert: op.d,
  170. }
  171. }
  172. case 'i': {
  173. const from = op.p
  174. const content = op.i
  175. const to = from + content.length
  176. const text = view.state.doc.sliceString(from, to)
  177. if (text !== content) {
  178. throw new Error(
  179. `Op to be removed (${JSON.stringify(
  180. change.op
  181. )}) does not match editor text '${text}'`
  182. )
  183. }
  184. return { from, to, insert: '' }
  185. }
  186. default: {
  187. throw new Error(`unknown change: ${JSON.stringify(change)}`)
  188. }
  189. }
  190. })
  191. return {
  192. changes: changesToDispatch,
  193. annotations: [trackChangesAnnotation.of('reject')],
  194. }
  195. }
  196. /**
  197. * If the current selection is empty, select the whole line.
  198. *
  199. * Used when adding a comment with no selected range, e.g. with a keyboard shortcut.
  200. */
  201. const selectCurrentLine = () => {
  202. if (view.state.selection.main.empty) {
  203. const line = view.state.doc.lineAt(view.state.selection.main.from)
  204. view.dispatch({
  205. selection: {
  206. anchor: line.from,
  207. head: line.to === view.state.doc.length ? line.to : line.to + 1,
  208. },
  209. })
  210. }
  211. }
  212. /**
  213. * Collapse the current selection to a single point (after inserting a comment)
  214. */
  215. const collapseSelection = () => {
  216. view.dispatch({
  217. selection: EditorSelection.cursor(view.state.selection.main.head),
  218. })
  219. }
  220. /**
  221. * Listen for events dispatched from the (Angular) review panel.
  222. *
  223. * These are combined into a single listener, avoiding the need to add and remove event listeners individually.
  224. */
  225. const reviewPanelEventListener = (event: Event) => {
  226. const { type, payload } = (
  227. event as CustomEvent<{ type: string; payload: any }>
  228. ).detail
  229. switch (type) {
  230. // receive review panel scroll events
  231. case 'scroll': {
  232. view.scrollDOM.scrollBy(0, payload)
  233. break
  234. }
  235. case 'overview-closed': {
  236. window.setTimeout(() => {
  237. dispatchScrollEvent()
  238. }, 0)
  239. break
  240. }
  241. case 'recalculate-screen-positions': {
  242. const changed = recalculateScreenPositions(payload)
  243. if (changed) {
  244. dispatchEditorEvent('track-changes:visibility_changed')
  245. }
  246. break
  247. }
  248. case 'changes:accept': {
  249. acceptChanges(payload)
  250. view.dispatch(buildChangeMarkers())
  251. broadcastChange()
  252. break
  253. }
  254. case 'changes:reject': {
  255. view.dispatch(rejectChanges(payload))
  256. broadcastChange()
  257. break
  258. }
  259. case 'comment:select_line': {
  260. selectCurrentLine()
  261. broadcastChange()
  262. break
  263. }
  264. case 'comment:add': {
  265. addComment(payload.offset, payload.length, payload.threadId)
  266. collapseSelection()
  267. broadcastChange()
  268. break
  269. }
  270. case 'comment:remove': {
  271. removeComment(payload)
  272. view.dispatch(buildChangeMarkers())
  273. broadcastChange()
  274. break
  275. }
  276. case 'comment:resolve_threads':
  277. case 'comment:unresolve_thread': {
  278. view.dispatch(buildChangeMarkers())
  279. broadcastChange()
  280. break
  281. }
  282. case 'loaded_threads': {
  283. view.dispatch(buildChangeMarkers())
  284. broadcastChange()
  285. break
  286. }
  287. case 'sizes': {
  288. const { overflowTop, height } = payload
  289. const padding = view.documentPadding
  290. const contentHeight =
  291. view.contentDOM.clientHeight - padding.top - padding.bottom
  292. const paddingNeeded = height - contentHeight
  293. if (
  294. overflowTop !== editorVerticalTopPadding(view) ||
  295. paddingNeeded !== padding.bottom
  296. ) {
  297. view.dispatch(
  298. setVerticalOverflow({
  299. top: overflowTop,
  300. bottom: paddingNeeded,
  301. })
  302. )
  303. }
  304. break
  305. }
  306. }
  307. }
  308. const broadcastChange = debounce(() => {
  309. dispatchEditorEvent('track-changes:changed')
  310. }, 50)
  311. /**
  312. * When the editor content, focus, size, viewport or selection changes,
  313. * tell the review panel to update.
  314. *
  315. * @param state object
  316. */
  317. const dispatchFocusChangedEvent = debounce((state: EditorState) => {
  318. // TODO: multiple selections?
  319. const { from, to, empty } = state.selection.main
  320. dispatchEditorEvent('focus:changed', { from, to, empty })
  321. }, 50)
  322. /**
  323. * When the editor is scrolled, tell the review panel so it can scroll in sync.
  324. */
  325. const dispatchScrollEvent = () => {
  326. window.dispatchEvent(
  327. new CustomEvent('editor:scroll', {
  328. detail: {
  329. height: view.scrollDOM.scrollHeight,
  330. scrollTop: view.scrollDOM.scrollTop,
  331. paddingTop: editorVerticalTopPadding(view),
  332. },
  333. })
  334. )
  335. }
  336. /**
  337. * Add event listeners to the ShareJS doc so that change markers are rebuilt when the tracked changes are updated.
  338. *
  339. * Also add event listeners to the editor scroll DOM and window.
  340. */
  341. const addListeners = () => {
  342. // NOTE: the namespace "cm6" is needed so the listeners can be removed individually
  343. currentDoc.on('ranges:dirty.cm6', () => {
  344. // TODO: use currentDoc.ranges.getDirtyState and only update those which have changed?
  345. window.setTimeout(() => {
  346. view.dispatch(buildChangeMarkers())
  347. broadcastChange()
  348. }, 0)
  349. })
  350. // called on joinDoc
  351. currentDoc.on('ranges:clear.cm6', () => {
  352. window.setTimeout(() => {
  353. view.dispatch(clearChangeMarkers())
  354. broadcastChange()
  355. }, 0)
  356. })
  357. // called on joinDoc
  358. currentDoc.on('ranges:redraw.cm6', () => {
  359. window.setTimeout(() => {
  360. view.dispatch(buildChangeMarkers())
  361. broadcastChange()
  362. }, 0)
  363. })
  364. // sync review panel scroll with editor scroll
  365. view.scrollDOM.addEventListener('scroll', dispatchScrollEvent)
  366. // listen for events from the review panel controller
  367. window.addEventListener('review-panel:event', reviewPanelEventListener)
  368. }
  369. /**
  370. * Remove event listeners
  371. */
  372. const removeListeners = () => {
  373. currentDoc.off('ranges:clear.cm6')
  374. currentDoc.off('ranges:dirty.cm6')
  375. currentDoc.off('ranges:redraw.cm6')
  376. view.scrollDOM.removeEventListener('scroll', dispatchScrollEvent)
  377. window.removeEventListener('review-panel:event', reviewPanelEventListener)
  378. }
  379. let ignoreGeometryChangesUntil = 0
  380. return {
  381. initialize() {
  382. addListeners()
  383. broadcastChange()
  384. },
  385. handleUpdate(update: ViewUpdate) {
  386. if (update.geometryChanged && !update.docChanged) {
  387. broadcastChange()
  388. }
  389. if (updateSetsVerticalOverflow(update)) {
  390. ignoreGeometryChangesUntil = Date.now() + 50 // ignore changes for 50ms
  391. } else if (
  392. (update.geometryChanged || update.viewportChanged) &&
  393. Date.now() < ignoreGeometryChangesUntil
  394. ) {
  395. // Ignore a change to the editor geometry or viewport that occurs immediately after
  396. // an update to the vertical padding because otherwise it triggers
  397. // another update to the padding and so on ad infinitum. This is not an
  398. // ideal way to handle this but I couldn't see another way.
  399. return
  400. }
  401. if (
  402. update.docChanged ||
  403. update.focusChanged ||
  404. update.viewportChanged ||
  405. update.selectionSet ||
  406. update.geometryChanged
  407. ) {
  408. dispatchFocusChangedEvent(update.state)
  409. }
  410. },
  411. destroy() {
  412. removeListeners()
  413. },
  414. }
  415. }