npm package: @manuscripts/track-changes
Description: ProseMirror plugin to track and rapidly replace changes in a Manuscript
Author: @CAYdenberg
Latest version: 0.3.3

# @manuscripts/track-changes

This repo provides a plugin for tracking the state of a ProseMirror document over time, and utilities for dealing with the data from that plugin.

## Usage

## Getting started

```
npm i @manuscripts/track-changes
```

```js
import TrackPlugin, { getTrackPluginState } from '@manuscripts/track-changes'

// other prosemirror imports

new EditorView(document.querySelector('#editor'), {
  state: EditorState.create({
    doc: DOMParser.fromSchema(mySchema).parse(
      document.querySelector('#content')
    ),
    plugins: exampleSetup({ schema: mySchema }).concat(TrackPlugin()),
  }),
})
```

### Concept

We use terminology similar to git as this is reasonably familiar to most programmers.

When the plugin is running, ProseMirror steps are gathered into the head commit as they occur (this is different from git, where new changes are not considered part of a commit). The commit can be frozen by executing a ProseMirror command, and a new head commit opened to gather the new steps. Each commit should be considered an atomic change for tracking purposes (e.g., made by one user).

The blame map tracks the location of the commit within the document. Decorations are added as `<span>` elements with defined classes.

The plugin can be run against an ancestral document that was authored without the plugin. Changes are tracked against that ancestor; we don't need an "initial commit", nor is the state of the document before tracking was started considered part of the history or blame.

### CSS Classes

The blame map can be styled (for example, using different background colors):

`.blame` - any span in the blame map

`.blame-uncommitted` - a span in the head (uncommitted) commit

`.blame-focused` - a span in the focused commit, ie if the cursor is positioned within this span or another span in the same commit

`.blame-point`, `.blame-focused-point` - similar to above, these represent zero-width spans (usually corresponding to a deletion). They can be styled to create a carot to indicate the deletion:

```css
.blame-point,
.blame-focused-point {
  position: relative;
}
.blame-point::after,
.blame-focused-point::after {
  position: absolute;
  left: -2.5px;
  display: inline-block;
  content: ' ';
  border: 1px solid rgba(255, 0, 0);
  transform: rotate(45deg);
  border-top: none;
  border-left: none;
  width: 5px;
  height: 5px;
}
```

### External API

`TrackPlugin(commit?: Commit) => Plugin` This is the default export

#### Plugin State

The edit history can be interrogated by examining at the plugin state.

`getTrackPluginState(state: EditorState) => {commit: Commit, deco: DecorationSet, focusedCommit: string | null}`

Get the whole plugin state. A Commit looks like this:

```
{
  id: string/unique
  blame: [{ from: number, to: number, commit: string}],
  steps: Step,
  prev: Commit | null
}
```

Notice that commits are recursive: each commit contains a reference to the previous commit in the chain. The first commit contains `null` as the value of `prev`.

Note that the `blame` consists of spans for this commit and all previous commits it knows about.

See [Steps](https://prosemirror.net/docs/ref/#transform.Step) in the ProseMirror documentation.

`getCommitsList(state: EditorState) => Commit[]`

Get the current commit history as a flat array

`findCommitWithin(state: EditorState) => (id: string) => Commit`

Find the nested commit with a particular id.

#### Commands

To work with the change history you can utilize [ProseMirror commands](https://prosemirror.net/docs/ref/#commands).

`commands.freezeCommit(state, dispatch)` - Commit (as a verb) the current changes. Opens a new head commit to collect changes. Move the current commit to the `prev` property of the current commit.

`commands.focusCommit(state, dispatch)` - Highlight the changes for a particular commit. See "CSS Classes" to see how to style the "focused" commit differently from the rest of the blame map. Focusing (and focusing) is done automatically when the editor selection falls within a span in the blame map; this command is needed only for externally assigning focus (for example, when the user selects a commit from a list).

#### Rebase

Similar to git, we can remap the changes in a commit to create a new commit. Recall that commits are recursive, so they represent not only their own changes, but also the previous commits upon which they are based.

`rebase.without(commit: Commit, without: string[]) => {commit: Commit, mapping: Mapping`

Produce a new commit without paritcular commits in the history (identified by their `id`). This is most useful for removing particular commits from the history.

`rebase.cherryPick(pick: Commit, onto: Commit) => {commit: Commit, mapping: Mapping}`

Map the changes for head commit of `pick` onto the entire history of `onto`. This is useful for "adding" a commit, or putting it back into history after removing it.

Note that these are pure functions; they don't alter the state of the editor on their own. Note also that they return both a new commit and [a Mapping](https://prosemirror.net/docs/ref/#transform.Mapping), which can be used to update the current selection or alter the undo/redo stack (good luck!).

(**TODO**: The rebase functions could use some optimizations to identify common ancestors and not bother remapping between them, which will both aid performance and in some cases the fidelity of mapping).

#### Checkout

This is a useful helper function for swapping the editor state with a new one produced by a rebase.

`checkout(ancestorDocument: ProsemirrorNode, currentState: EditorState, commit: Commit) => EditorState`

This produces an _entirely new_ EditorState by applying all the steps in `commit` to the `ancestorDocument`. `currentState` is utilized to reconstruct the state with the same plugins and schema, and to update the selection (if any).

As it stands, this will delete the undo/redo stack (**TODO**: decide what to do about this).

#### Persistent storage

`commitToJSON(commit: Commit) => string`

Creates a JSON representation of `commit`.

`commitFromJSON(json: string, schema: ProsemirrorSchema) => Commit`

Convert a JSON representation of a commit back to an object. Note that this requires schema. This commit can be loaded when the plugin is initialized by passing the commit to the plugin factory function.

## Development

```
git clone git@gitlab.com:mpapp-public/manuscripts-track-changes.git
cd manuscripts-track-changes
npm i
npm run typecheck
npm run lint
npm run test
npm run build
npm run sandbox
```