Skip to content
This repository was archived by the owner on Oct 11, 2022. It is now read-only.

Commit b0d2e8b

Browse files
authored
Merge pull request #70 from cusxio/atomic-image
insert image as atomic block
2 parents 9304310 + 855b7c2 commit b0d2e8b

File tree

2 files changed

+50
-19
lines changed

2 files changed

+50
-19
lines changed

src/modifiers/__test__/insertImage-test.js

Lines changed: 37 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,13 @@
11
import Draft, { EditorState, SelectionState } from "draft-js";
22
import insertImage from "../insertImage";
33

4+
jest.mock("draft-js/lib/generateRandomKey", () => {
5+
let count = 0;
6+
return () => {
7+
return `key${count++}`;
8+
};
9+
});
10+
411
describe("insertImage", () => {
512
const markup =
613
'![bar](http://cultofthepartyparrot.com/parrots/aussieparrot.gif "party")';
@@ -20,6 +27,35 @@ describe("insertImage", () => {
2027
],
2128
};
2229
const afterRawContentState = {
30+
blocks: [
31+
{
32+
data: {},
33+
depth: 0,
34+
entityRanges: [],
35+
inlineStyleRanges: [],
36+
key: "item1",
37+
text: "foo ",
38+
type: "unstyled",
39+
},
40+
{
41+
data: {},
42+
depth: 0,
43+
entityRanges: [{ key: 0, length: 1, offset: 0 }],
44+
inlineStyleRanges: [],
45+
key: "key0",
46+
text: " ",
47+
type: "atomic",
48+
},
49+
{
50+
data: {},
51+
depth: 0,
52+
entityRanges: [],
53+
inlineStyleRanges: [],
54+
key: "key4",
55+
text: " baz",
56+
type: "unstyled",
57+
},
58+
],
2359
entityMap: {
2460
0: {
2561
data: {
@@ -31,24 +67,8 @@ describe("insertImage", () => {
3167
type: "IMG",
3268
},
3369
},
34-
blocks: [
35-
{
36-
key: "item1",
37-
text: "foo \u200B baz",
38-
type: "unstyled",
39-
depth: 0,
40-
inlineStyleRanges: [],
41-
entityRanges: [
42-
{
43-
key: 0,
44-
length: 1,
45-
offset: 4,
46-
},
47-
],
48-
data: {},
49-
},
50-
],
5170
};
71+
5272
const selection = new SelectionState({
5373
anchorKey: "item1",
5474
anchorOffset: 6,

src/modifiers/insertImage.js

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,10 @@
1-
import { EditorState, RichUtils, SelectionState, Modifier } from "draft-js";
1+
import {
2+
EditorState,
3+
RichUtils,
4+
SelectionState,
5+
Modifier,
6+
AtomicBlockUtils,
7+
} from "draft-js";
28

39
const insertImage = (editorState, matchArr) => {
410
const currentContent = editorState.getCurrentContent();
@@ -42,9 +48,14 @@ const insertImage = (editorState, matchArr) => {
4248
newWordSelection,
4349
entityKey
4450
);
51+
newEditorState = AtomicBlockUtils.insertAtomicBlock(
52+
newEditorState,
53+
newEditorState.getCurrentContent().getLastCreatedEntityKey(),
54+
" "
55+
);
4556
return EditorState.forceSelection(
4657
newEditorState,
47-
newContentState.getSelectionAfter()
58+
newEditorState.getCurrentContent().getSelectionAfter()
4859
);
4960
};
5061

0 commit comments

Comments
 (0)