tiptap/packages/extension-collaboration-cursor/index.ts

71 lines
1.7 KiB
TypeScript
Raw Normal View History

2020-10-22 18:34:49 +08:00
import { createExtension, Command } from '@tiptap/core'
2020-09-26 17:03:17 +08:00
import { yCursorPlugin } from 'y-prosemirror'
export interface CollaborationCursorOptions {
name: string,
color: string,
provider: any,
render (user: { name: string, color: string }): HTMLElement,
2020-09-26 17:03:17 +08:00
}
2020-10-23 04:40:40 +08:00
const CollaborationCursor = createExtension({
2020-10-22 18:34:49 +08:00
name: 'collaboration_cursor',
2020-10-22 18:34:49 +08:00
defaultOptions: <CollaborationCursorOptions>{
2020-09-26 17:03:17 +08:00
provider: null,
name: 'Someone',
color: '#cccccc',
render: user => {
const cursor = document.createElement('span')
2020-09-27 16:37:48 +08:00
cursor.classList.add('collaboration-cursor__caret')
cursor.setAttribute('style', `border-color: ${user.color}`)
const label = document.createElement('div')
2020-09-27 16:37:48 +08:00
label.classList.add('collaboration-cursor__label')
label.setAttribute('style', `background-color: ${user.color}`)
label.insertBefore(document.createTextNode(user.name), null)
cursor.insertBefore(label, null)
return cursor
},
2020-10-22 18:34:49 +08:00
},
addCommands() {
return {
2020-10-23 04:40:40 +08:00
user: (attributes: {
name: string,
color: string,
}): Command => () => {
2020-10-22 18:34:49 +08:00
this.options.provider.awareness.setLocalStateField('user', attributes)
return true
},
}
},
addProseMirrorPlugins() {
return [
yCursorPlugin((() => {
this.options.provider.awareness.setLocalStateField('user', {
name: this.options.name,
color: this.options.color,
})
return this.options.provider.awareness
})(),
// @ts-ignore
{
cursorBuilder: this.options.render,
}),
]
},
})
2020-10-23 04:40:40 +08:00
export default CollaborationCursor
declare module '@tiptap/core/src/Editor' {
interface AllExtensions {
CollaborationCursor: typeof CollaborationCursor,
}
}