aboutsummaryrefslogtreecommitdiff
path: root/src/client/util/ProseMirrorEditorView.tsx
blob: b42adfbb400aaaa0f080d46dd5675d8003f92dd4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import React from "react";
import { EditorView } from "prosemirror-view";
import { EditorState } from "prosemirror-state";

export interface ProseMirrorEditorViewProps {
    /* EditorState instance to use. */
    editorState: EditorState;
    /* Called when EditorView produces new EditorState. */
    onEditorState: (editorState: EditorState) => any;
}

/**
 * This wraps ProseMirror's EditorView into React component.
 * This code was found on https://discuss.prosemirror.net/t/using-with-react/904
 */
export class ProseMirrorEditorView extends React.Component<ProseMirrorEditorViewProps>  {

    private _editorView?: EditorView;

    _createEditorView = (element: HTMLDivElement | null) => {
        if (element !== null) {
            this._editorView = new EditorView(element, {
                state: this.props.editorState,
                dispatchTransaction: this.dispatchTransaction,
            });
        }
    }

    dispatchTransaction = (tx: any) => {
        // In case EditorView makes any modification to a state we funnel those
        // modifications up to the parent and apply to the EditorView itself.
        const editorState = this.props.editorState.apply(tx);
        if (this._editorView) {
            this._editorView.updateState(editorState);
        }
        this.props.onEditorState(editorState);
    }

    focus() {
        if (this._editorView) {
            this._editorView.focus();
        }
    }

    componentWillReceiveProps(nextProps: { editorState: EditorState<any>; }) {
        // In case we receive new EditorState through props — we apply it to the
        // EditorView instance.
        if (this._editorView) {
            if (nextProps.editorState !== this.props.editorState) {
                this._editorView.updateState(nextProps.editorState);
            }
        }
    }

    componentWillUnmount() {
        if (this._editorView) {
            this._editorView.destroy();
        }
    }

    shouldComponentUpdate() {
        // Note that EditorView manages its DOM itself so we'd ratrher don't mess
        // with it.
        return false;
    }

    render() {
        // Render just an empty div which is then used as a container for an
        // EditorView instance.
        return (
            <div ref={this._createEditorView} />
        );
    }
}