tiptap/packages/extension-collaboration/src/collaboration.ts

80 lines
1.6 KiB
TypeScript
Raw Normal View History

2020-12-02 16:28:55 +08:00
import { Extension, Command } from '@tiptap/core'
import {
2020-11-25 16:50:54 +08:00
redo,
undo,
ySyncPlugin,
yUndoPlugin,
} from 'y-prosemirror'
2021-02-10 16:59:35 +08:00
declare module '@tiptap/core' {
interface Commands {
undo: () => Command,
redo: () => Command,
}
}
2020-09-26 16:43:08 +08:00
export interface CollaborationOptions {
/**
* An initialized Y.js document.
*/
document: any,
2021-01-11 21:43:41 +08:00
/**
* Name of a Y.js fragment, can be changed to sync multiple fields with one Y.js document.
2021-01-11 21:43:41 +08:00
*/
field: string,
/**
* A raw Y.js fragment, can be used instead of `document` and `field`.
*/
fragment: any,
}
2020-12-08 04:32:50 +08:00
export const Collaboration = Extension.create({
2020-12-02 16:44:46 +08:00
name: 'collaboration',
2020-10-22 18:34:49 +08:00
defaultOptions: <CollaborationOptions>{
document: null,
field: 'default',
fragment: null,
2020-10-22 18:34:49 +08:00
},
2020-12-02 16:28:55 +08:00
addCommands() {
return {
/**
* Undo recent changes
*/
2021-02-10 16:59:35 +08:00
undo: () => ({ tr, state }) => {
2020-12-02 19:05:35 +08:00
tr.setMeta('preventDispatch', true)
2020-12-02 16:28:55 +08:00
return undo(state)
},
/**
* Reapply reverted changes
*/
2021-02-10 16:59:35 +08:00
redo: () => ({ tr, state }) => {
2020-12-02 19:05:35 +08:00
tr.setMeta('preventDispatch', true)
2020-12-02 16:28:55 +08:00
return redo(state)
},
}
},
addKeyboardShortcuts() {
return {
'Mod-z': () => this.editor.commands.undo(),
'Mod-y': () => this.editor.commands.redo(),
'Shift-Mod-z': () => this.editor.commands.redo(),
}
},
2020-10-22 18:34:49 +08:00
addProseMirrorPlugins() {
const fragment = this.options.fragment
? this.options.fragment
: this.options.document.getXmlFragment(this.options.field)
2020-10-22 18:34:49 +08:00
return [
ySyncPlugin(fragment),
2020-10-22 18:34:49 +08:00
yUndoPlugin(),
]
},
})