tiptap/packages/react/src/ReactRenderer.tsx

87 lines
1.8 KiB
TypeScript
Raw Normal View History

2021-03-13 04:21:13 +08:00
import React from 'react'
2021-03-15 16:00:44 +08:00
import { AnyObject } from '@tiptap/core'
2021-03-13 04:21:13 +08:00
import { Editor } from './Editor'
2021-03-08 20:19:05 +08:00
2021-03-15 07:22:17 +08:00
function isClassComponent(Component: any) {
return !!(
typeof Component === 'function'
&& Component.prototype
&& Component.prototype.isReactComponent
2021-03-15 16:00:44 +08:00
)
}
export interface ReactRendererOptions {
editor: Editor,
props?: AnyObject,
as?: string,
2021-03-15 07:22:17 +08:00
}
2021-03-13 04:21:13 +08:00
export class ReactRenderer {
id: string
2021-03-08 20:19:05 +08:00
2021-03-13 04:21:13 +08:00
editor: Editor
2021-03-08 20:19:05 +08:00
2021-03-13 04:21:13 +08:00
component: any
2021-03-08 20:19:05 +08:00
2021-03-13 04:21:13 +08:00
element: Element
2021-03-08 20:19:05 +08:00
2021-03-15 16:00:44 +08:00
props: AnyObject
2021-03-08 20:19:05 +08:00
2021-03-15 00:01:52 +08:00
reactElement: React.ReactNode
2021-03-15 07:22:17 +08:00
ref: React.Component | null = null
constructor(component: React.Component | React.FunctionComponent, { editor, props = {}, as = 'div' }: ReactRendererOptions) {
2021-03-13 04:21:13 +08:00
this.id = Math.floor(Math.random() * 0xFFFFFFFF).toString()
this.component = component
this.editor = editor
this.props = props
this.element = document.createElement(as)
2021-03-15 01:00:50 +08:00
this.element.classList.add('react-renderer')
2021-03-14 23:30:06 +08:00
this.render()
}
2021-03-15 16:00:44 +08:00
render(): void {
2021-03-15 07:22:17 +08:00
const Component = this.component
const props = this.props
if (isClassComponent(Component)) {
2021-03-17 05:22:13 +08:00
props.ref = (ref: React.Component) => {
this.ref = ref
}
2021-03-15 07:22:17 +08:00
}
this.reactElement = <Component {...props } />
2021-03-13 04:21:13 +08:00
if (this.editor?.contentComponent) {
this.editor.contentComponent.setState({
renderers: this.editor.contentComponent.state.renderers.set(
this.id,
this,
),
})
}
}
2021-03-15 16:00:44 +08:00
updateProps(props: AnyObject = {}): void {
2021-03-15 00:01:52 +08:00
this.props = {
...this.props,
...props,
}
this.render()
2021-03-13 04:21:13 +08:00
}
2021-03-15 16:00:44 +08:00
destroy(): void {
2021-03-13 04:21:13 +08:00
if (this.editor?.contentComponent) {
const { renderers } = this.editor.contentComponent.state
renderers.delete(this.id)
this.editor.contentComponent.setState({
renderers,
})
}
}
}