change-manager.ts 18 KB

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