change-manager.ts 16 KB

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