| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354 |
- import {
- EditorState,
- RangeSet,
- StateEffect,
- StateField,
- Transaction,
- } from '@codemirror/state'
- import {
- Decoration,
- type DecorationSet,
- EditorView,
- type PluginValue,
- ViewPlugin,
- WidgetType,
- } from '@codemirror/view'
- import {
- findCommentsInCut,
- findDetachedCommentsInChanges,
- restoreCommentsOnPaste,
- restoreDetachedComments,
- StoredComment,
- } from './changes/comments'
- import { invertedEffects } from '@codemirror/commands'
- import { CurrentDoc } from '../../../../../types/current-doc'
- import { Change, DeleteOperation } from '../../../../../types/change'
- import { ChangeManager } from './changes/change-manager'
- import { debugConsole } from '@/utils/debugging'
- import {
- isChangeOperation,
- isCommentOperation,
- isDeleteOperation,
- } from '@/utils/operations'
- const clearChangesEffect = StateEffect.define()
- const buildChangesEffect = StateEffect.define()
- const restoreDetachedCommentsEffect = StateEffect.define<RangeSet<any>>({
- map: (value, mapping) => {
- return value
- .update({
- filter: (from, to) => {
- return from <= mapping.length && to <= mapping.length
- },
- })
- .map(mapping)
- },
- })
- type Options = {
- currentDoc: CurrentDoc
- loadingThreads: boolean
- }
- /**
- * A custom extension that initialises the change manager, passes any updates to it,
- * and produces decorations for tracked changes and comments.
- */
- export const trackChanges = (
- { currentDoc, loadingThreads }: Options,
- changeManager: ChangeManager
- ) => {
- // A state field that stored any comments found within the ranges of a "cut" transaction,
- // to be restored when pasting matching text.
- const cutCommentsState = StateField.define<StoredComment[]>({
- create: () => {
- return []
- },
- update: (value, transaction) => {
- if (transaction.annotation(Transaction.remote)) {
- return value
- }
- if (!transaction.docChanged) {
- return value
- }
- if (transaction.isUserEvent('delete.cut')) {
- return findCommentsInCut(currentDoc, transaction)
- }
- if (transaction.isUserEvent('input.paste')) {
- restoreCommentsOnPaste(currentDoc, transaction, value)
- return []
- }
- return value
- },
- })
- return [
- // attach any comments detached by the transaction as an inverted effect, to be applied on undo
- invertedEffects.of(transaction => {
- if (
- transaction.docChanged &&
- !transaction.annotation(Transaction.remote)
- ) {
- const detachedComments = findDetachedCommentsInChanges(
- currentDoc,
- transaction
- )
- if (detachedComments.size) {
- return [restoreDetachedCommentsEffect.of(detachedComments)]
- }
- }
- return []
- }),
- // restore any detached comments on undo
- EditorState.transactionExtender.of(transaction => {
- for (const effect of transaction.effects) {
- if (effect.is(restoreDetachedCommentsEffect)) {
- // send the comments to the ShareJS doc
- restoreDetachedComments(currentDoc, transaction, effect.value)
- // return a transaction spec to rebuild the change markers
- return buildChangeMarkers()
- }
- }
- return null
- }),
- cutCommentsState,
- // initialize/destroy the change manager, and handle any updates
- ViewPlugin.define(() => {
- changeManager.initialize()
- return {
- update: update => {
- changeManager.handleUpdate(update)
- },
- destroy: () => {
- changeManager.destroy()
- },
- }
- }),
- // draw change decorations
- ViewPlugin.define<
- PluginValue & {
- decorations: DecorationSet
- }
- >(
- () => {
- return {
- decorations: loadingThreads
- ? Decoration.none
- : buildChangeDecorations(currentDoc),
- update(update) {
- for (const transaction of update.transactions) {
- this.decorations = this.decorations.map(transaction.changes)
- for (const effect of transaction.effects) {
- if (effect.is(clearChangesEffect)) {
- this.decorations = Decoration.none
- } else if (effect.is(buildChangesEffect)) {
- this.decorations = buildChangeDecorations(currentDoc)
- }
- }
- }
- },
- }
- },
- {
- decorations: value => value.decorations,
- }
- ),
- // styles for change decorations
- trackChangesTheme,
- ]
- }
- export const clearChangeMarkers = () => {
- return {
- effects: clearChangesEffect.of(null),
- }
- }
- export const buildChangeMarkers = () => {
- return {
- effects: buildChangesEffect.of(null),
- }
- }
- const buildChangeDecorations = (currentDoc: CurrentDoc) => {
- const changes = [...currentDoc.ranges.changes, ...currentDoc.ranges.comments]
- const decorations = []
- for (const change of changes) {
- try {
- decorations.push(...createChangeRange(change, currentDoc))
- } catch (error) {
- // ignore invalid changes
- debugConsole.debug('invalid change position', error)
- }
- }
- return Decoration.set(decorations, true)
- }
- class ChangeDeletedWidget extends WidgetType {
- constructor(public change: Change<DeleteOperation>) {
- super()
- }
- toDOM() {
- const widget = document.createElement('span')
- widget.classList.add('ol-cm-change')
- widget.classList.add('ol-cm-change-d')
- return widget
- }
- eq() {
- return true
- }
- }
- class ChangeCalloutWidget extends WidgetType {
- constructor(public change: Change, public opType: string) {
- super()
- }
- toDOM() {
- const widget = document.createElement('span')
- widget.className = 'ol-cm-change-callout'
- widget.classList.add(`ol-cm-change-callout-${this.opType}`)
- const inner = document.createElement('span')
- inner.classList.add('ol-cm-change-callout-inner')
- widget.appendChild(inner)
- return widget
- }
- eq(widget: ChangeCalloutWidget) {
- return widget.opType === this.opType
- }
- updateDOM(element: HTMLElement) {
- element.className = 'ol-cm-change-callout'
- element.classList.add(`ol-cm-change-callout-${this.opType}`)
- return true
- }
- }
- const createChangeRange = (change: Change, currentDoc: CurrentDoc) => {
- const { id, metadata, op } = change
- const from = op.p
- // TODO: find valid positions?
- if (isDeleteOperation(op)) {
- const opType = 'd'
- const changeWidget = Decoration.widget({
- widget: new ChangeDeletedWidget(change as Change<DeleteOperation>),
- side: 1,
- opType,
- id,
- metadata,
- })
- const calloutWidget = Decoration.widget({
- widget: new ChangeCalloutWidget(change, opType),
- side: 1,
- opType,
- id,
- metadata,
- })
- return [calloutWidget.range(from, from), changeWidget.range(from, from)]
- }
- if (isChangeOperation(op) && currentDoc.ranges.resolvedThreadIds[op.t]) {
- return []
- }
- const isChangeOrCommentOperation =
- isChangeOperation(op) || isCommentOperation(op)
- const opType = isChangeOrCommentOperation ? 'c' : 'i'
- const changedText = isChangeOrCommentOperation ? op.c : op.i
- const to = from + changedText.length
- // Mark decorations must not be empty
- if (from === to) {
- return []
- }
- const changeMark = Decoration.mark({
- tagName: 'span',
- class: `ol-cm-change ol-cm-change-${opType}`,
- opType,
- id,
- metadata,
- })
- const calloutWidget = Decoration.widget({
- widget: new ChangeCalloutWidget(change, opType),
- opType,
- id,
- metadata,
- })
- return [calloutWidget.range(from, from), changeMark.range(from, to)]
- }
- const trackChangesTheme = EditorView.baseTheme({
- '.cm-line': {
- overflowX: 'hidden', // needed so the callout elements don't overflow (requires line wrapping to be on)
- },
- '&light .ol-cm-change-i': {
- backgroundColor: '#2c8e304d',
- },
- '&dark .ol-cm-change-i': {
- backgroundColor: 'rgba(37, 107, 41, 0.15)',
- },
- '&light .ol-cm-change-c': {
- backgroundColor: '#f3b1114d',
- },
- '&dark .ol-cm-change-c': {
- backgroundColor: 'rgba(194, 93, 11, 0.15)',
- },
- '.ol-cm-change': {
- padding: 'var(--half-leading, 0) 0',
- },
- '.ol-cm-change-d': {
- borderLeft: '2px dotted #c5060b',
- marginLeft: '-1px',
- },
- '.ol-cm-change-callout': {
- position: 'relative',
- pointerEvents: 'none',
- padding: 'var(--half-leading, 0) 0',
- },
- '.ol-cm-change-callout-inner': {
- display: 'inline-block',
- position: 'absolute',
- left: 0,
- bottom: 0,
- width: '10000px',
- borderBottom: '1px dashed black',
- },
- '.ol-cm-change-callout-i .ol-cm-change-callout-inner': {
- borderColor: '#2c8e30',
- },
- '.ol-cm-change-callout-c .ol-cm-change-callout-inner': {
- borderColor: '#f3b111',
- },
- '.ol-cm-change-callout-d .ol-cm-change-callout-inner': {
- borderColor: '#c5060b',
- },
- })
|