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

72 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
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-11-13 22:08:30 +08:00
/**
* Update details of the current user
*/
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
2020-11-11 04:18:22 +08:00
declare module '@tiptap/core' {
2020-10-23 04:40:40 +08:00
interface AllExtensions {
CollaborationCursor: typeof CollaborationCursor,
}
}