More and more fixes

This commit is contained in:
Tom Moor
2017-12-03 19:59:54 -08:00
parent 802f6e6594
commit 751b468e92
14 changed files with 194 additions and 257 deletions

View File

@@ -4,7 +4,7 @@ import { observable } from 'mobx';
import { observer } from 'mobx-react';
import { Value, Change } from 'slate';
import { Editor } from 'slate-react';
import type { SlateNodeProps } from './types';
import type { SlateNodeProps, Plugin } from './types';
import Plain from 'slate-plain-serializer';
import keydown from 'react-keydown';
import getDataTransferFiles from 'utils/getDataTransferFiles';
@@ -16,9 +16,10 @@ import Placeholder from './components/Placeholder';
import Contents from './components/Contents';
import Markdown from './serializer';
import createPlugins from './plugins';
import insertImage from './insertImage';
import { insertImageFile } from './changes';
import renderMark from './marks';
import createRenderNode from './nodes';
import schema from './schema';
import styled from 'styled-components';
type Props = {
@@ -37,7 +38,7 @@ class MarkdownEditor extends Component {
props: Props;
editor: Editor;
renderNode: SlateNodeProps => *;
plugins: Object[];
plugins: Plugin[];
@observable editorValue: Value;
constructor(props: Props) {
@@ -60,12 +61,11 @@ class MarkdownEditor extends Component {
}
componentDidMount() {
if (!this.props.readOnly) {
if (this.props.text) {
this.focusAtEnd();
} else {
this.focusAtStart();
}
if (this.props.readOnly) return;
if (this.props.text) {
this.focusAtEnd();
} else {
this.focusAtStart();
}
}
@@ -78,8 +78,8 @@ class MarkdownEditor extends Component {
onChange = (change: Change) => {
if (this.editorValue !== change.value) {
this.props.onChange(Markdown.serialize(change.value));
this.editorValue = change.value;
}
this.editorValue = change.value;
};
handleDrop = async (ev: SyntheticEvent) => {
@@ -100,15 +100,13 @@ class MarkdownEditor extends Component {
};
insertImageFile = async (file: window.File) => {
this.editor.change(
async change =>
await insertImage(
change,
file,
this.editor,
this.props.onImageUploadStart,
this.props.onImageUploadStop
)
this.editor.change(change =>
change.call(
insertImageFile,
file,
this.props.onImageUploadStart,
this.props.onImageUploadStop
)
);
};
@@ -206,10 +204,12 @@ class MarkdownEditor extends Component {
value={this.editorValue}
renderNode={this.renderNode}
renderMark={renderMark}
schema={schema}
onKeyDown={this.onKeyDown}
onChange={this.onChange}
onSave={onSave}
readOnly={readOnly}
spellCheck={!readOnly}
/>
<ClickablePadding
onClick={!readOnly ? this.focusAtEnd : undefined}

View File

@@ -1,18 +1,46 @@
// @flow
import uuid from 'uuid';
import uploadFile from 'utils/uploadFile';
import { Change } from 'slate';
import { Editor } from 'slate-react';
import uuid from 'uuid';
import EditList from './plugins/EditList';
import uploadFile from 'utils/uploadFile';
export default async function insertImageFile(
const { changes } = EditList;
type Options = {
type: string | Object,
wrapper?: string | Object,
append?: string | Object,
};
export function splitAndInsertBlock(change: Change, options: Options) {
const { type, wrapper, append } = options;
const parent = change.value.document.getParent(change.value.startBlock.key);
// lists get some special treatment
if (parent && parent.type === 'list-item') {
change = changes.unwrapList(
changes
.splitListItem(change.collapseToStart())
.collapseToEndOfPreviousBlock()
);
}
change = change.insertBlock(type);
if (wrapper) change = change.wrapBlock(wrapper);
if (append) change = change.insertBlock(append);
return change;
}
export async function insertImageFile(
change: Change,
file: window.File,
editor: Editor,
onImageUploadStart: () => void,
onImageUploadStop: () => void
) {
onImageUploadStart();
console.log(file);
try {
// load the file as a data URL
const id = uuid.v4();
@@ -27,6 +55,7 @@ export default async function insertImageFile(
isVoid: true,
data: { src, id, alt, loading: true },
});
console.log('insertBlock', change);
});
reader.readAsDataURL(file);
@@ -37,12 +66,12 @@ export default async function insertImageFile(
// we dont use the original change provided to the callback here
// as the state may have changed significantly in the time it took to
// upload the file.
const finalTransform = editor.value.change();
const placeholder = editor.value.document.findDescendant(
const placeholder = change.value.document.findDescendant(
node => node.data && node.data.get('id') === id
);
console.log('placeholder', placeholder);
return finalTransform.setNodeByKey(placeholder.key, {
return change.setNodeByKey(placeholder.key, {
data: { src, alt, loading: false },
});
} catch (err) {

View File

@@ -10,12 +10,9 @@ export default class TodoItem extends Component {
handleChange = (ev: SyntheticInputEvent) => {
const checked = ev.target.checked;
const { editor, node } = this.props;
const change = editor
.getState()
.change()
.setNodeByKey(node.key, { data: { checked } });
editor.onChange(change);
editor.change(change =>
change.setNodeByKey(node.key, { data: { checked } })
);
};
render() {

View File

@@ -16,7 +16,7 @@ import ToolbarButton from './components/ToolbarButton';
import type { SlateNodeProps } from '../../types';
import { color } from 'shared/styles/constants';
import { fadeIn } from 'shared/styles/animations';
import { splitAndInsertBlock } from '../../transforms';
import { splitAndInsertBlock } from '../../changes';
type Props = SlateNodeProps & {
onInsertImage: *,
@@ -61,7 +61,7 @@ class BlockToolbar extends Component {
editor.change(change => {
splitAndInsertBlock(change, options);
change.value.document.nodes.forEach(node => {
editor.value.document.nodes.forEach(node => {
if (node.type === 'block-toolbar') {
change.removeNodeByKey(node.key);
}

View File

@@ -4,7 +4,6 @@ import ReactDOM from 'react-dom';
import { observable, action } from 'mobx';
import { observer, inject } from 'mobx-react';
import { withRouter } from 'react-router-dom';
import { Change } from 'slate';
import { Editor } from 'slate-react';
import styled from 'styled-components';
import ArrowKeyNavigation from 'boundless-arrow-key-navigation';
@@ -28,7 +27,6 @@ class LinkToolbar extends Component {
link: Object,
documents: DocumentsStore,
onBlur: () => void,
onChange: Change => *,
};
@observable isEditing: boolean = false;

View File

@@ -22,7 +22,7 @@ type Options = {
onInsertImage: *,
};
export default function createRenderNode({ onChange, onInsertImage }: Options) {
export default function createRenderNode({ onInsertImage }: Options) {
return function renderNode(props: SlateNodeProps) {
const { attributes } = props;

View File

@@ -1,5 +1,5 @@
// @flow
// import DropOrPasteImages from '@tommoor/slate-drop-or-paste-images';
import InsertImages from 'slate-drop-or-paste-images';
import PasteLinkify from 'slate-paste-linkify';
import CollapseOnEscape from 'slate-collapse-on-escape';
import TrailingBlock from 'slate-trailing-block';
@@ -8,7 +8,7 @@ import Prism from 'slate-prism';
import EditList from './plugins/EditList';
import KeyboardShortcuts from './plugins/KeyboardShortcuts';
import MarkdownShortcuts from './plugins/MarkdownShortcuts';
// import insertImage from './insertImage';
import { insertImageFile } from './changes';
const onlyInCode = node => node.type === 'code';
@@ -23,18 +23,17 @@ const createPlugins = ({ onImageUploadStart, onImageUploadStop }: Options) => {
type: 'link',
collapseTo: 'end',
}),
// DropOrPasteImages({
// extensions: ['png', 'jpg', 'gif'],
// applyTransform: (transform, file, editor) => {
// return insertImage(
// transform,
// file,
// editor,
// onImageUploadStart,
// onImageUploadStop
// );
// },
// }),
InsertImages({
extensions: ['png', 'jpg', 'gif'],
insertImage(change, file) {
return change.call(
insertImageFile,
file,
onImageUploadStart,
onImageUploadStop
);
},
}),
EditList,
EditCode({
onlyIn: onlyInCode,

View File

@@ -4,4 +4,5 @@ import EditList from 'slate-edit-list';
export default EditList({
types: ['ordered-list', 'bulleted-list', 'todo-list'],
typeItem: 'list-item',
typeDefault: 'paragraph',
});

View File

@@ -182,8 +182,8 @@ export default function MarkdownShortcuts() {
change.removeMarkByKey(
textNode.key,
change.startOffset - charsInCodeBlock.size,
change.startOffset,
startOffset - charsInCodeBlock.size,
startOffset,
'code'
);
}
@@ -210,10 +210,13 @@ export default function MarkdownShortcuts() {
onEnter(ev: SyntheticKeyboardEvent, change: Change) {
const { value } = change;
if (value.isExpanded) return;
const { startBlock, startOffset, endOffset } = value;
if (startOffset === 0 && startBlock.length === 0)
return this.onBackspace(ev, change);
if (endOffset !== startBlock.length) return;
// Hitting enter at the end of the line reverts to standard behavior
if (endOffset === startBlock.length) return;
// Hitting enter while an image is selected should jump caret below and
// insert a new paragraph
@@ -225,19 +228,12 @@ export default function MarkdownShortcuts() {
// Hitting enter in a heading or blockquote will split the node at that
// point and make the new node a paragraph
if (
startBlock.type !== 'heading1' &&
startBlock.type !== 'heading2' &&
startBlock.type !== 'heading3' &&
startBlock.type !== 'heading4' &&
startBlock.type !== 'heading5' &&
startBlock.type !== 'heading6' &&
startBlock.type !== 'block-quote'
startBlock.type.startsWith('heading') ||
startBlock.type === 'block-quote'
) {
return;
ev.preventDefault();
return change.splitBlock().setBlock('paragraph');
}
ev.preventDefault();
change.splitBlock().setBlock('paragraph');
},
/**

View File

@@ -1,133 +1,82 @@
// // @flow
// import React from 'react';
// import Code from './components/Code';
// import HorizontalRule from './components/HorizontalRule';
// import InlineCode from './components/InlineCode';
// import Image from './components/Image';
// import Link from './components/Link';
// import ListItem from './components/ListItem';
// import TodoList from './components/TodoList';
// import {
// Heading1,
// Heading2,
// Heading3,
// Heading4,
// Heading5,
// Heading6,
// } from './components/Heading';
// import Paragraph from './components/Paragraph';
// import BlockToolbar from './components/Toolbar/BlockToolbar';
// import type { Props, Node, Transform } from './types';
//
// type Options = {
// onInsertImage: Function,
// onChange: Function,
// };
//
// const createSchema = ({ onInsertImage, onChange }: Options) => {
// return {
// marks: {
// bold: (props: Props) => <strong>{props.children}</strong>,
// code: (props: Props) => <InlineCode>{props.children}</InlineCode>,
// italic: (props: Props) => <em>{props.children}</em>,
// underlined: (props: Props) => <u>{props.children}</u>,
// deleted: (props: Props) => <del>{props.children}</del>,
// added: (props: Props) => <mark>{props.children}</mark>,
// },
//
// nodes: {
// 'block-toolbar': (props: Props) => (
// <BlockToolbar
// onChange={onChange}
// onInsertImage={onInsertImage}
// {...props}
// />
// ),
// paragraph: (props: Props) => <Paragraph {...props} />,
// 'block-quote': (props: Props) => (
// <blockquote {...props.attributes}>{props.children}</blockquote>
// ),
// 'horizontal-rule': HorizontalRule,
// 'bulleted-list': (props: Props) => (
// <ul {...props.attributes}>{props.children}</ul>
// ),
// 'ordered-list': (props: Props) => (
// <ol {...props.attributes}>{props.children}</ol>
// ),
// 'todo-list': (props: Props) => (
// <TodoList {...props.attributes}>{props.children}</TodoList>
// ),
// table: (props: Props) => (
// <table {...props.attributes}>{props.children}</table>
// ),
// 'table-row': (props: Props) => (
// <tr {...props.attributes}>{props.children}</tr>
// ),
// 'table-head': (props: Props) => (
// <th {...props.attributes}>{props.children}</th>
// ),
// 'table-cell': (props: Props) => (
// <td {...props.attributes}>{props.children}</td>
// ),
// code: Code,
// image: Image,
// link: Link,
// 'list-item': ListItem,
// heading1: (props: Props) => <Heading1 placeholder {...props} />,
// heading2: (props: Props) => <Heading2 {...props} />,
// heading3: (props: Props) => <Heading3 {...props} />,
// heading4: (props: Props) => <Heading4 {...props} />,
// heading5: (props: Props) => <Heading5 {...props} />,
// heading6: (props: Props) => <Heading6 {...props} />,
// },
//
// rules: [
// // ensure first node is always a heading
// {
// match: (node: Node) => {
// return node.kind === 'document';
// },
// validate: (document: Node) => {
// const firstNode = document.nodes.first();
// return firstNode && firstNode.type === 'heading1' ? null : firstNode;
// },
// normalize: (transform: Transform, document: Node, firstNode: Node) => {
// transform.setBlock({ type: 'heading1' });
// },
// },
//
// // automatically removes any marks in first heading
// {
// match: (node: Node) => {
// return node.kind === 'heading1';
// },
// validate: (heading: Node) => {
// const hasMarks = heading.getMarks().isEmpty();
// const hasInlines = heading.getInlines().isEmpty();
//
// return !(hasMarks && hasInlines);
// },
// normalize: (transform: Transform, heading: Node) => {
// transform.unwrapInlineByKey(heading.key);
//
// heading.getMarks().forEach(mark => {
// heading.nodes.forEach(textNode => {
// if (textNode.kind === 'text') {
// transform.removeMarkByKey(
// textNode.key,
// 0,
// textNode.text.length,
// mark
// );
// }
// });
// });
//
// return transform;
// },
// },
// ],
// };
// };
//
// export default createSchema;
// @flow
import { Block, Change, Node, Mark } from 'slate';
const schema = {
blocks: {
heading1: { marks: [''] },
heading2: { marks: [''] },
heading3: { marks: [''] },
heading4: { marks: [''] },
heading5: { marks: [''] },
heading6: { marks: [''] },
'ordered-list': {
nodes: [{ types: ['list-item'] }],
},
'bulleted-list': {
nodes: [{ types: ['list-item'] }],
},
table: {
nodes: [{ types: ['table-row', 'table-head', 'table-cell'] }],
},
image: {
isVoid: true,
},
'horizontal-rule': {
isVoid: true,
},
'block-toolbar': {
isVoid: true,
},
},
document: {
nodes: [
{ types: ['heading1'], min: 1, max: 1 },
{
types: [
'paragraph',
'heading1',
'heading2',
'heading3',
'heading4',
'heading5',
'heading6',
'code',
'horizontal-rule',
'image',
'bulleted-list',
'ordered-list',
'todo-list',
'block-toolbar',
'table',
],
min: 1,
},
],
normalize: (
change: Change,
reason: string,
{
node,
child,
mark,
index,
}: { node: Node, mark?: Mark, child: Node, index: number }
) => {
switch (reason) {
case 'child_type_invalid': {
return change.setNodeByKey(
child.key,
index === 0 ? 'heading1' : 'paragraph'
);
}
case 'child_required': {
const block = Block.create(index === 0 ? 'heading1' : 'paragraph');
return change.insertNodeByKey(node.key, index, block);
}
default:
}
},
},
};
export default schema;

View File

@@ -1,34 +0,0 @@
// @flow
import { Change } from 'slate';
import EditList from './plugins/EditList';
const { changes } = EditList;
type Options = {
type: string | Object,
wrapper?: string | Object,
append?: string | Object,
};
export function splitAndInsertBlock(change: Change, options: Options) {
const { type, wrapper, append } = options;
const { value } = change;
const { document } = value;
const parent = document.getParent(value.startBlock.key);
// lists get some special treatment
if (parent && parent.type === 'list-item') {
change = changes.unwrapList(
changes
.splitListItem(change.collapseToStart())
.collapseToEndOfPreviousBlock()
);
}
change = change.insertBlock(type);
if (wrapper) change = change.wrapBlock(wrapper);
if (append) change = change.insertBlock(append);
return change;
}

View File

@@ -1,5 +1,5 @@
// @flow
import { Value, Node } from 'slate';
import { Value, Change, Node } from 'slate';
import { Editor } from 'slate-react';
export type SlateNodeProps = {
@@ -11,3 +11,9 @@ export type SlateNodeProps = {
node: Node,
parent: Node,
};
export type Plugin = {
validateNode?: Node => *,
onClick?: SyntheticEvent => *,
onKeyDown?: (SyntheticKeyboardEvent, Change) => *,
};