ranges.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  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 && !rangesData.threads[comment.op.t].resolved
  201. )
  202. : []
  203. for (const range of [...changes, ...unresolvedComments]) {
  204. if (isSelectionWithinOp(range.op, update.state.selection.main)) {
  205. this.decorations = buildHighlightDecorations(
  206. 'ol-cm-change-focus',
  207. range.op
  208. )
  209. break
  210. }
  211. }
  212. },
  213. }
  214. },
  215. {
  216. decorations: value => value.decorations,
  217. }
  218. ),
  219. // styles for change decorations
  220. trackChangesTheme,
  221. ]
  222. const buildChangeDecorations = (data: RangesData) => {
  223. if (!data.ranges) {
  224. return Decoration.none
  225. }
  226. const changes = [...data.ranges.changes, ...data.ranges.comments]
  227. const decorations = []
  228. for (const change of changes) {
  229. try {
  230. decorations.push(...createChangeRange(change, data))
  231. } catch (error) {
  232. // ignore invalid changes
  233. debugConsole.debug('invalid change position', error)
  234. }
  235. }
  236. return Decoration.set(decorations, true)
  237. }
  238. const updateDeleteWidgetHighlight = (
  239. decorations: DecorationSet,
  240. predicate: (widget: ChangeDeletedWidget) => boolean,
  241. highlightType?: 'focus' | 'highlight' | null
  242. ) => {
  243. const widgetsToReplace: ChangeDeletedWidget[] = []
  244. const cursor = decorations.iter()
  245. while (cursor.value) {
  246. const widget = cursor.value.spec?.widget
  247. if (widget instanceof ChangeDeletedWidget && predicate(widget)) {
  248. widgetsToReplace.push(cursor.value.spec.widget)
  249. }
  250. cursor.next()
  251. }
  252. return decorations.update({
  253. filter: (from, to, decoration) => {
  254. return !widgetsToReplace.includes(decoration.spec?.widget)
  255. },
  256. add: widgetsToReplace.map(({ change }) =>
  257. Decoration.widget({
  258. widget: new ChangeDeletedWidget(change, highlightType),
  259. side: 1,
  260. opType: 'd',
  261. id: change.id,
  262. metadata: change.metadata,
  263. }).range(change.op.p, change.op.p)
  264. ),
  265. })
  266. }
  267. const buildHighlightDecorations = (className: string, op: AnyOperation) => {
  268. if (isDeleteOperation(op)) {
  269. // delete indicators are handled in change decorations
  270. return Decoration.none
  271. }
  272. const opFrom = op.p
  273. const opLength = isInsertOperation(op) ? op.i.length : op.c.length
  274. const opType = isInsertOperation(op) ? 'i' : 'c'
  275. if (opLength === 0) {
  276. return Decoration.none
  277. }
  278. return Decoration.set(
  279. Decoration.mark({
  280. class: `${className} ${className}-${opType}`,
  281. }).range(opFrom, opFrom + opLength),
  282. true
  283. )
  284. }
  285. class ChangeDeletedWidget extends WidgetType {
  286. constructor(
  287. public change: Change<DeleteOperation>,
  288. public highlightType: 'highlight' | 'focus' | null = null
  289. ) {
  290. super()
  291. }
  292. toDOM() {
  293. const widget = document.createElement('span')
  294. widget.classList.add('ol-cm-change')
  295. widget.classList.add('ol-cm-change-d')
  296. widget.textContent = '[ — ]'
  297. if (this.highlightType) {
  298. widget.classList.add(`ol-cm-change-d-${this.highlightType}`)
  299. }
  300. return widget
  301. }
  302. eq(old: ChangeDeletedWidget) {
  303. return old.highlightType === this.highlightType
  304. }
  305. }
  306. const createChangeRange = (change: Change, data: RangesData) => {
  307. const { id, metadata, op } = change
  308. const from = op.p
  309. if (isDeleteOperation(op)) {
  310. const opType = 'd'
  311. const changeWidget = Decoration.widget({
  312. widget: new ChangeDeletedWidget(change as Change<DeleteOperation>),
  313. side: 1,
  314. opType,
  315. id,
  316. metadata,
  317. })
  318. return [changeWidget.range(from, from)]
  319. }
  320. const _isCommentOperation = isCommentOperation(op)
  321. if (_isCommentOperation) {
  322. const thread = data.threads[op.t]
  323. if (!thread || thread.resolved) {
  324. return []
  325. }
  326. }
  327. const opType = _isCommentOperation ? 'c' : 'i'
  328. const changedText = _isCommentOperation ? op.c : op.i
  329. const to = from + changedText.length
  330. // Mark decorations must not be empty
  331. if (from === to) {
  332. return []
  333. }
  334. const changeMark = Decoration.mark({
  335. tagName: 'span',
  336. class: `ol-cm-change ol-cm-change-${opType}`,
  337. opType,
  338. id,
  339. metadata,
  340. })
  341. return [changeMark.range(from, to)]
  342. }
  343. const trackChangesTheme = EditorView.baseTheme({
  344. '&light .ol-cm-change-i': {
  345. backgroundColor: '#2c8e304d',
  346. },
  347. '&dark .ol-cm-change-i': {
  348. backgroundColor: 'rgba(37, 107, 41, 0.15)',
  349. },
  350. '&light .ol-cm-change-c': {
  351. backgroundColor: '#f3b1114d',
  352. },
  353. '&dark .ol-cm-change-c': {
  354. backgroundColor: 'rgba(194, 93, 11, 0.15)',
  355. },
  356. '.ol-cm-change': {
  357. padding: 'var(--half-leading, 0) 0',
  358. },
  359. '.ol-cm-change-highlight': {
  360. padding: 'var(--half-leading, 0) 0',
  361. },
  362. '.ol-cm-change-focus': {
  363. padding: 'var(--half-leading, 0) 0',
  364. },
  365. // TODO: fix dark mode colors
  366. '&light .ol-cm-change-d': {
  367. color: '#c5060b',
  368. backgroundColor: '#f5beba57',
  369. },
  370. '&dark .ol-cm-change-d': {
  371. color: '#c5060b',
  372. backgroundColor: '#f5beba57',
  373. },
  374. '&light .ol-cm-change-d-highlight': {
  375. backgroundColor: '#f5bebaa4',
  376. },
  377. '&dark .ol-cm-change-d-highlight': {
  378. backgroundColor: '#f5bebaa4',
  379. },
  380. '&light .ol-cm-change-d-focus': {
  381. backgroundColor: '#F5BEBA',
  382. },
  383. '&dark .ol-cm-change-d-focus': {
  384. backgroundColor: '#F5BEBA',
  385. },
  386. '&light .ol-cm-change-highlight-i': {
  387. backgroundColor: '#b8dbc899',
  388. },
  389. '&dark .ol-cm-change-highlight-i': {
  390. backgroundColor: '#b8dbc899',
  391. },
  392. '&light .ol-cm-change-highlight-c': {
  393. backgroundColor: '#fcc4837d',
  394. },
  395. '&dark .ol-cm-change-highlight-c': {
  396. backgroundColor: '#fcc4837d',
  397. },
  398. '&light .ol-cm-change-focus-i': {
  399. backgroundColor: '#B8DBC8',
  400. },
  401. '&dark .ol-cm-change-focus-i': {
  402. backgroundColor: '#B8DBC8',
  403. },
  404. '&light .ol-cm-change-focus-c': {
  405. backgroundColor: '#FCC483',
  406. },
  407. '&dark .ol-cm-change-focus-c': {
  408. backgroundColor: '#FCC483',
  409. },
  410. })