Skip to content
GitHub

Commit

Track changes in the editor and display them in a diff view. This is built on top of prosemirror-changeset.

import { defineBasicExtension } from 'prosekit/basic'
import {
  createEditor,
  union,
} from 'prosekit/core'
import {
  defineCommitViewer,
  type Commit,
} from 'prosekit/extensions/commit'
import { defineReadonly } from 'prosekit/extensions/readonly'
import { ProseKit } from 'prosekit/react'
import { useMemo } from 'react'

export default function DiffViewer({ commit }: { commit: Commit }) {
  const editor = useMemo(() => {
    const extension = union(
      defineBasicExtension(),
      defineReadonly(),
      defineCommitViewer(commit),
    )
    return createEditor({ extension })
  }, [commit])

  return (
    <ProseKit editor={editor}>
      <div className="box-border h-full w-full min-h-36 overflow-y-hidden overflow-x-hidden rounded-md border border-solid border-gray-200 dark:border-gray-700 shadow flex flex-col bg-white dark:bg-gray-950 color-black dark:color-white">
        <div className="relative w-full flex-1 box-border overflow-y-scroll">
          <div ref={editor.mount} className="ProseMirror box-border min-h-full px-[max(4rem,_calc(50%-20rem))] py-8 outline-none outline-0 [&_span[data-mention=user]]:text-blue-500 [&_span[data-mention=tag]]:text-violet-500"></div>
        </div>
      </div>
    </ProseKit>
  )
}

To record changes, first create a CommitRecorder instance. Then, pass it to the defineCommitRecorder function.

import {
  CommitRecorder,
  defineCommitRecorder,
} from 'prosekit/extensions/commit'

const commitRecorder = new CommitRecorder()
const extension = defineCommitRecorder(commitRecorder)

When you want to save the changes, call the commit method. This will return a JSON Commit object if there are any changes. You can then serialize and save this object to your database.

import type { Commit } from 'prosekit/extensions/commit'

const commit = commitRecorder.commit()

To display the changes, create another editor instance and call defineCommitViewer with the Commit object.

import { defineCommitViewer } from 'prosekit/extensions/commit'

const extension = defineCommitViewer(commit)

To highlight the changes, you must load the style.css file or define your own styles for the .prosekit-commit-addition and .prosekit-commit-deletion classes.

import 'prosekit/extensions/commit/style.css'