Skip to content

Instantly share code, notes, and snippets.

@takashi
Created May 4, 2017 10:36
Show Gist options
  • Save takashi/ef112922b6c90756bea4715679b8b3f7 to your computer and use it in GitHub Desktop.
Save takashi/ef112922b6c90756bea4715679b8b3f7 to your computer and use it in GitHub Desktop.
slate.js example
import React from 'react';
import { Editor, Raw } from 'slate';
import Layout from '../layout';
function CodeNode(props) {
return <pre {...props.attributes}><code>{props.children}</code></pre>
}
function MarkHotkey(options) {
const { type, code } = options;
return {
onKeyDown(event, data, state) {
if(!event.metaKey || event.which != code) return
event.preventDefault();
return state
.transform()
.toggleMark(type)
.apply()
}
}
}
const boldPlugin = MarkHotkey({
type: 'bold',
code: 66
});
const plugins = [
boldPlugin
]
const initialContent = JSON.parse(localStorage.getItem('content'))
const initialState = Raw.deserialize(initialContent || {
nodes: [
{
kind: 'block',
type: 'paragraph',
nodes: [
{
kind: 'text',
text: 'A line of text in a paragraph.'
}
]
}
]
}, { terse: true });
export default class Note extends React.Component {
state = {
state: initialState,
schema: {
marks: {
bold: props => <strong>{props.children}</strong>
}
}
}
onChange = (state) => {
this.setState({ state });
}
onDocumentChange = (document, state) => {
const content = JSON.stringify(Raw.serialize(state))
localStorage.setItem('content', content)
}
render(){
return (
<Layout>
<Editor
plugins={plugins}
schema={this.state.schema}
state={this.state.state}
onChange={this.onChange}
onDocumentChange={this.onDocumentChange}
// onKeyDown={this.onKeyDown}
/>
</Layout>
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment