tiptap/examples/Components/Routes/Collaboration/index.vue

78 lines
1.6 KiB
Vue
Raw Normal View History

2019-02-03 21:06:17 +08:00
<template>
<div class="editor">
2019-02-04 04:18:03 +08:00
<editor-content class="editor__content" :editor="editor" v-if="editor" />
2019-02-03 21:06:17 +08:00
</div>
</template>
<script>
2019-05-04 00:05:05 +08:00
import io from 'socket.io-client'
import { debounce } from 'lodash-es'
2019-02-03 21:06:17 +08:00
import { Editor, EditorContent } from 'tiptap'
import { Step } from 'prosemirror-transform'
import { receiveTransaction, sendableSteps, getVersion } from 'prosemirror-collab'
import Collab from './Collab'
export default {
components: {
EditorContent,
},
data() {
return {
2019-02-04 04:18:03 +08:00
editor: null,
2019-05-04 00:05:05 +08:00
socket: null,
2019-02-04 04:18:03 +08:00
}
},
2019-02-03 21:06:17 +08:00
2019-02-04 04:18:03 +08:00
methods: {
initEditor({ doc, version }) {
2019-05-04 00:05:05 +08:00
if (this.editor) {
this.editor.destroy()
}
2019-02-04 04:18:03 +08:00
this.editor = new Editor({
content: doc,
extensions: [
2019-05-04 00:05:05 +08:00
new Collab({ version }),
2019-02-04 04:18:03 +08:00
],
2019-02-03 21:06:17 +08:00
onUpdate: ({ state }) => {
2019-05-04 00:05:05 +08:00
this.getSendableSteps(state)
2019-02-03 21:06:17 +08:00
},
2019-02-04 04:18:03 +08:00
})
},
2019-02-03 21:06:17 +08:00
2019-05-04 00:05:05 +08:00
getSendableSteps: debounce(function (state) {
const sendable = sendableSteps(state)
2019-02-03 21:06:17 +08:00
2019-05-04 00:05:05 +08:00
if (sendable) {
this.socket.emit('update', sendable)
}
}, 250),
2019-02-03 21:06:17 +08:00
2019-05-04 00:05:05 +08:00
receiveData({ steps, version }) {
2019-02-03 21:06:17 +08:00
const { state, view, schema } = this.editor
2019-05-04 00:05:05 +08:00
if (getVersion(state) > version) {
return
2019-02-03 21:06:17 +08:00
}
2019-05-04 00:05:05 +08:00
view.dispatch(receiveTransaction(
state,
steps.map(item => Step.fromJSON(schema, item.step)),
steps.map(item => item.clientID),
))
2019-02-03 21:06:17 +08:00
},
},
mounted() {
2019-05-04 03:50:17 +08:00
this.socket = io('wss://tiptap-sockets.glitch.me')
.on('init', data => this.initEditor(data))
2019-05-04 00:05:05 +08:00
.on('update', data => this.receiveData(data))
2019-02-03 21:06:17 +08:00
},
beforeDestroy() {
this.editor.destroy()
},
}
</script>