change-manager.ts 16 KB

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