ranges.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. import { StateEffect, StateField, TransactionSpec } from '@codemirror/state'
  2. import {
  3. Decoration,
  4. type DecorationSet,
  5. EditorView,
  6. type PluginValue,
  7. ViewPlugin,
  8. WidgetType,
  9. } from '@codemirror/view'
  10. import {
  11. AnyOperation,
  12. Change,
  13. DeleteOperation,
  14. } from '../../../../../types/change'
  15. import { debugConsole } from '@/utils/debugging'
  16. import {
  17. isCommentOperation,
  18. isDeleteOperation,
  19. isInsertOperation,
  20. } from '@/utils/operations'
  21. import { Ranges } from '@/features/review-panel-new/context/ranges-context'
  22. import { Threads } from '@/features/review-panel-new/context/threads-context'
  23. import { isSelectionWithinOp } from '@/features/review-panel-new/utils/is-selection-within-op'
  24. type RangesData = {
  25. ranges: Ranges
  26. threads: Threads
  27. }
  28. const updateRangesEffect = StateEffect.define<RangesData>()
  29. const highlightRangesEffect = StateEffect.define<AnyOperation>()
  30. const clearHighlightRangesEffect = StateEffect.define<AnyOperation>()
  31. export const updateRanges = (data: RangesData): TransactionSpec => {
  32. return {
  33. effects: updateRangesEffect.of(data),
  34. }
  35. }
  36. export const highlightRanges = (op: AnyOperation): TransactionSpec => {
  37. return {
  38. effects: highlightRangesEffect.of(op),
  39. }
  40. }
  41. export const clearHighlightRanges = (op: AnyOperation): TransactionSpec => {
  42. return {
  43. effects: clearHighlightRangesEffect.of(op),
  44. }
  45. }
  46. export const rangesDataField = StateField.define<RangesData | null>({
  47. create() {
  48. return null
  49. },
  50. update(rangesData, tr) {
  51. for (const effect of tr.effects) {
  52. if (effect.is(updateRangesEffect)) {
  53. return effect.value
  54. }
  55. }
  56. return rangesData
  57. },
  58. })
  59. /**
  60. * A custom extension that initialises the change manager, passes any updates to it,
  61. * and produces decorations for tracked changes and comments.
  62. */
  63. export const ranges = () => [
  64. rangesDataField,
  65. // handle viewportChanged updates
  66. ViewPlugin.define(view => {
  67. let timer: number
  68. return {
  69. update(update) {
  70. if (update.viewportChanged) {
  71. if (timer) {
  72. window.clearTimeout(timer)
  73. }
  74. timer = window.setTimeout(() => {
  75. dispatchEvent(new Event('editor:viewport-changed'))
  76. }, 25)
  77. }
  78. },
  79. }
  80. }),
  81. // draw change decorations
  82. ViewPlugin.define<
  83. PluginValue & {
  84. decorations: DecorationSet
  85. }
  86. >(
  87. () => {
  88. return {
  89. decorations: Decoration.none,
  90. update(update) {
  91. for (const transaction of update.transactions) {
  92. this.decorations = this.decorations.map(transaction.changes)
  93. for (const effect of transaction.effects) {
  94. if (effect.is(updateRangesEffect)) {
  95. this.decorations = buildChangeDecorations(effect.value)
  96. } else if (
  97. effect.is(highlightRangesEffect) &&
  98. isDeleteOperation(effect.value)
  99. ) {
  100. this.decorations = updateDeleteWidgetHighlight(
  101. this.decorations,
  102. widget =>
  103. widget.change.op.p === effect.value.p &&
  104. widget.highlightType !== 'focus',
  105. 'highlight'
  106. )
  107. } else if (
  108. effect.is(clearHighlightRangesEffect) &&
  109. isDeleteOperation(effect.value)
  110. ) {
  111. this.decorations = updateDeleteWidgetHighlight(
  112. this.decorations,
  113. widget =>
  114. widget.change.op.p === effect.value.p &&
  115. widget.highlightType !== 'focus',
  116. null
  117. )
  118. }
  119. }
  120. if (transaction.selection) {
  121. this.decorations = updateDeleteWidgetHighlight(
  122. this.decorations,
  123. ({ change }) =>
  124. isSelectionWithinOp(change.op, update.state.selection.main),
  125. 'focus'
  126. )
  127. this.decorations = updateDeleteWidgetHighlight(
  128. this.decorations,
  129. ({ change }) =>
  130. !isSelectionWithinOp(change.op, update.state.selection.main),
  131. null
  132. )
  133. }
  134. }
  135. },
  136. }
  137. },
  138. {
  139. decorations: value => value.decorations,
  140. }
  141. ),
  142. // draw highlight decorations
  143. ViewPlugin.define<
  144. PluginValue & {
  145. decorations: DecorationSet
  146. }
  147. >(
  148. () => {
  149. return {
  150. decorations: Decoration.none,
  151. update(update) {
  152. for (const transaction of update.transactions) {
  153. this.decorations = this.decorations.map(transaction.changes)
  154. for (const effect of transaction.effects) {
  155. if (effect.is(highlightRangesEffect)) {
  156. this.decorations = buildHighlightDecorations(
  157. 'ol-cm-change-highlight',
  158. effect.value
  159. )
  160. } else if (effect.is(clearHighlightRangesEffect)) {
  161. this.decorations = Decoration.none
  162. }
  163. }
  164. }
  165. },
  166. }
  167. },
  168. {
  169. decorations: value => value.decorations,
  170. }
  171. ),
  172. // draw focus decorations
  173. ViewPlugin.define<
  174. PluginValue & {
  175. decorations: DecorationSet
  176. }
  177. >(
  178. view => {
  179. return {
  180. decorations: Decoration.none,
  181. update(update) {
  182. if (
  183. !update.transactions.some(
  184. tr =>
  185. tr.selection ||
  186. tr.effects.some(effect => effect.is(updateRangesEffect))
  187. )
  188. ) {
  189. return
  190. }
  191. this.decorations = Decoration.none
  192. const rangesData = view.state.field(rangesDataField)
  193. if (!rangesData?.ranges) {
  194. return
  195. }
  196. const { changes, comments } = rangesData.ranges
  197. const unresolvedComments = rangesData.threads
  198. ? comments.filter(
  199. comment =>
  200. comment.op.t &&
  201. rangesData.threads[comment.op.t] &&
  202. !rangesData.threads[comment.op.t].resolved
  203. )
  204. : []
  205. for (const range of [...changes, ...unresolvedComments]) {
  206. if (isSelectionWithinOp(range.op, update.state.selection.main)) {
  207. this.decorations = buildHighlightDecorations(
  208. 'ol-cm-change-focus',
  209. range.op
  210. )
  211. break
  212. }
  213. }
  214. },
  215. }
  216. },
  217. {
  218. decorations: value => value.decorations,
  219. }
  220. ),
  221. // styles for change decorations
  222. trackChangesTheme,
  223. ]
  224. const buildChangeDecorations = (data: RangesData) => {
  225. if (!data.ranges) {
  226. return Decoration.none
  227. }
  228. const changes = [...data.ranges.changes, ...data.ranges.comments]
  229. const decorations = []
  230. for (const change of changes) {
  231. try {
  232. decorations.push(...createChangeRange(change, data))
  233. } catch (error) {
  234. // ignore invalid changes
  235. debugConsole.debug('invalid change position', error)
  236. }
  237. }
  238. return Decoration.set(decorations, true)
  239. }
  240. const updateDeleteWidgetHighlight = (
  241. decorations: DecorationSet,
  242. predicate: (widget: ChangeDeletedWidget) => boolean,
  243. highlightType?: 'focus' | 'highlight' | null
  244. ) => {
  245. const widgetsToReplace: ChangeDeletedWidget[] = []
  246. const cursor = decorations.iter()
  247. while (cursor.value) {
  248. const widget = cursor.value.spec?.widget
  249. if (widget instanceof ChangeDeletedWidget && predicate(widget)) {
  250. widgetsToReplace.push(cursor.value.spec.widget)
  251. }
  252. cursor.next()
  253. }
  254. return decorations.update({
  255. sort: true,
  256. filter: (from, to, decoration) => {
  257. return !widgetsToReplace.includes(decoration.spec?.widget)
  258. },
  259. add: widgetsToReplace.map(({ change }) =>
  260. Decoration.widget({
  261. widget: new ChangeDeletedWidget(change, highlightType),
  262. side: 1,
  263. opType: 'd',
  264. id: change.id,
  265. metadata: change.metadata,
  266. }).range(change.op.p, change.op.p)
  267. ),
  268. })
  269. }
  270. const buildHighlightDecorations = (className: string, op: AnyOperation) => {
  271. if (isDeleteOperation(op)) {
  272. // delete indicators are handled in change decorations
  273. return Decoration.none
  274. }
  275. const opFrom = op.p
  276. const opLength = isInsertOperation(op) ? op.i.length : op.c.length
  277. const opType = isInsertOperation(op) ? 'i' : 'c'
  278. if (opLength === 0) {
  279. return Decoration.none
  280. }
  281. return Decoration.set(
  282. Decoration.mark({
  283. class: `${className} ${className}-${opType}`,
  284. }).range(opFrom, opFrom + opLength),
  285. true
  286. )
  287. }
  288. class ChangeDeletedWidget extends WidgetType {
  289. constructor(
  290. public change: Change<DeleteOperation>,
  291. public highlightType: 'highlight' | 'focus' | null = null
  292. ) {
  293. super()
  294. }
  295. toDOM() {
  296. const widget = document.createElement('span')
  297. widget.classList.add('ol-cm-change')
  298. widget.classList.add('ol-cm-change-d')
  299. if (this.highlightType) {
  300. widget.classList.add(`ol-cm-change-d-${this.highlightType}`)
  301. }
  302. return widget
  303. }
  304. eq(old: ChangeDeletedWidget) {
  305. return old.highlightType === this.highlightType
  306. }
  307. }
  308. const createChangeRange = (change: Change, data: RangesData) => {
  309. const { id, metadata, op } = change
  310. const from = op.p
  311. if (isDeleteOperation(op)) {
  312. const opType = 'd'
  313. const changeWidget = Decoration.widget({
  314. widget: new ChangeDeletedWidget(change as Change<DeleteOperation>),
  315. side: 1,
  316. opType,
  317. id,
  318. metadata,
  319. })
  320. return [changeWidget.range(from, from)]
  321. }
  322. const _isCommentOperation = isCommentOperation(op)
  323. if (_isCommentOperation) {
  324. const thread = data.threads[op.t]
  325. if (!thread || thread.resolved) {
  326. return []
  327. }
  328. }
  329. const opType = _isCommentOperation ? 'c' : 'i'
  330. const changedText = _isCommentOperation ? op.c : op.i
  331. const to = from + changedText.length
  332. // Mark decorations must not be empty
  333. if (from === to) {
  334. return []
  335. }
  336. const changeMark = Decoration.mark({
  337. tagName: 'span',
  338. class: `ol-cm-change ol-cm-change-${opType}`,
  339. opType,
  340. id,
  341. metadata,
  342. })
  343. return [changeMark.range(from, to)]
  344. }
  345. const trackChangesTheme = EditorView.baseTheme({
  346. '.ol-cm-change-i, .ol-cm-change-highlight-i, .ol-cm-change-focus-i': {
  347. backgroundColor: 'rgba(44, 142, 48, 0.30)',
  348. },
  349. '&light .ol-cm-change-c, &light .ol-cm-change-highlight-c, &light .ol-cm-change-focus-c':
  350. {
  351. backgroundColor: 'rgba(243, 177, 17, 0.30)',
  352. },
  353. '&dark .ol-cm-change-c, &dark .ol-cm-change-highlight-c, &dark .ol-cm-change-focus-c':
  354. {
  355. backgroundColor: 'rgba(194, 93, 11, 0.15)',
  356. },
  357. '.ol-cm-change': {
  358. padding: 'var(--half-leading, 0) 0',
  359. },
  360. '.ol-cm-change-highlight': {
  361. padding: 'var(--half-leading, 0) 0',
  362. },
  363. '.ol-cm-change-focus': {
  364. padding: 'var(--half-leading, 0) 0',
  365. },
  366. '&light .ol-cm-change-d': {
  367. borderLeft: '2px dotted #c5060b',
  368. marginLeft: '-1px',
  369. },
  370. '&dark .ol-cm-change-d': {
  371. borderLeft: '2px dotted #c5060b',
  372. marginLeft: '-1px',
  373. },
  374. '&light .ol-cm-change-d-highlight': {
  375. borderLeft: '3px solid #c5060b',
  376. marginLeft: '-2px',
  377. },
  378. '&dark .ol-cm-change-d-highlight': {
  379. borderLeft: '3px solid #c5060b',
  380. marginLeft: '-2px',
  381. },
  382. '&light .ol-cm-change-d-focus': {
  383. borderLeft: '3px solid #B83A33',
  384. marginLeft: '-2px',
  385. },
  386. '&dark .ol-cm-change-d-focus': {
  387. borderLeft: '3px solid #B83A33',
  388. marginLeft: '-2px',
  389. },
  390. })