tiptap/packages/vue-3/src/VueRenderer.ts

60 lines
1.4 KiB
TypeScript
Raw Normal View History

2021-04-21 15:43:31 +08:00
import { Editor } from '@tiptap/core'
import { Component, markRaw, reactive } from 'vue'
import { Editor as ExtendedEditor } from './Editor'
2021-02-28 06:56:08 +08:00
export interface VueRendererOptions {
2021-03-15 01:00:50 +08:00
editor: Editor,
2021-04-21 15:43:31 +08:00
props?: Record<string, any>,
2021-02-28 06:56:08 +08:00
}
export class VueRenderer {
id: string
editor: ExtendedEditor
2021-02-28 06:56:08 +08:00
component: Component
teleportElement: Element
element: Element
2021-04-21 15:43:31 +08:00
props: Record<string, any>
2021-02-28 06:56:08 +08:00
constructor(component: Component, { props = {}, editor }: VueRendererOptions) {
this.id = Math.floor(Math.random() * 0xFFFFFFFF).toString()
this.editor = editor as ExtendedEditor
2021-02-28 06:56:08 +08:00
this.component = markRaw(component)
this.teleportElement = document.createElement('div')
this.element = this.teleportElement
2021-03-02 04:04:25 +08:00
this.props = reactive(props)
2021-02-28 06:56:08 +08:00
this.editor.vueRenderers.set(this.id, this)
if (this.editor.contentComponent) {
this.editor.contentComponent.update()
2021-03-05 16:46:47 +08:00
if (this.teleportElement.children.length !== 1) {
throw Error('VueRenderer doesnt support multiple child elements.')
}
2021-02-28 06:56:08 +08:00
this.element = this.teleportElement.firstElementChild as Element
}
}
2021-03-18 04:21:57 +08:00
get ref(): any {
return this.editor.contentComponent?.refs[this.id]
2021-02-28 06:56:08 +08:00
}
2021-04-21 15:43:31 +08:00
updateProps(props: Record<string, any> = {}): void {
2021-03-02 04:04:25 +08:00
Object
.entries(props)
.forEach(([key, value]) => {
this.props[key] = value
})
2021-02-28 06:56:08 +08:00
}
2021-03-18 04:21:57 +08:00
destroy(): void {
2021-02-28 06:56:08 +08:00
this.editor.vueRenderers.delete(this.id)
}
}