UNPKG

1.96 kBJavaScriptView Raw
1// @flow
2/* eslint-disable import/no-extraneous-dependencies */
3/* global document */
4import * as React from 'react';
5import ReactDOM from 'react-dom';
6import { Editor } from 'slate-react';
7import PluginEditCode from '../lib/';
8
9import INITIAL_VALUE from './value';
10
11const plugin = PluginEditCode();
12const plugins = [plugin];
13
14function renderNode(props: *) {
15 const { node, children, attributes } = props;
16
17 switch (node.type) {
18 case 'code_block':
19 return (
20 <div className="code" {...attributes}>
21 {children}
22 </div>
23 );
24 case 'code_line':
25 return <pre {...attributes}>{children}</pre>;
26 case 'paragraph':
27 return <p {...attributes}>{children}</p>;
28 case 'heading':
29 return <h1 {...attributes}>{children}</h1>;
30 default:
31 return null;
32 }
33}
34
35class Example extends React.Component<*, *> {
36 state = {
37 value: INITIAL_VALUE
38 };
39
40 onChange = ({ value }) => {
41 this.setState({
42 value
43 });
44 };
45
46 onToggleCode = () => {
47 const { value } = this.state;
48
49 this.onChange(
50 plugin.changes.toggleCodeBlock(value.change(), 'paragraph').focus()
51 );
52 };
53
54 render() {
55 const { value } = this.state;
56
57 return (
58 <div>
59 <button onClick={this.onToggleCode}>
60 {plugin.utils.isInCodeBlock(value)
61 ? 'Paragraph'
62 : 'Code Block'}
63 </button>
64 <Editor
65 placeholder={'Enter some text...'}
66 plugins={plugins}
67 value={value}
68 onChange={this.onChange}
69 renderNode={renderNode}
70 />
71 </div>
72 );
73 }
74}
75
76// $FlowFixMe
77ReactDOM.render(<Example />, document.getElementById('example'));
78
\No newline at end of file