-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
Image.js
117 lines (102 loc) · 2.83 KB
/
Image.js
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
import { Node, Plugin } from 'tiptap'
import { nodeInputRule } from 'tiptap-commands'
/**
* Matches following attributes in Markdown-typed image: [, alt, src, title]
*
* Example:
*  -> [, "Lorem", "image.jpg"]
*  -> [, "", "image.jpg", "Ipsum"]
*  -> [, "Lorem", "image.jpg", "Ipsum"]
*/
const IMAGE_INPUT_REGEX = /!\[(.+|:?)]\((\S+)(?:(?:\s+)["'](\S+)["'])?\)/
export default class Image extends Node {
get name() {
return 'image'
}
get schema() {
return {
inline: true,
attrs: {
src: {},
alt: {
default: null,
},
title: {
default: null,
},
},
group: 'inline',
draggable: true,
parseDOM: [
{
tag: 'img[src]',
getAttrs: dom => ({
src: dom.getAttribute('src'),
title: dom.getAttribute('title'),
alt: dom.getAttribute('alt'),
}),
},
],
toDOM: node => ['img', node.attrs],
}
}
commands({ type }) {
return attrs => (state, dispatch) => {
const { selection } = state
const position = selection.$cursor ? selection.$cursor.pos : selection.$to.pos
const node = type.create(attrs)
const transaction = state.tr.insert(position, node)
dispatch(transaction)
}
}
inputRules({ type }) {
return [
nodeInputRule(IMAGE_INPUT_REGEX, type, match => {
const [, alt, src, title] = match
return {
src,
alt,
title,
}
}),
]
}
get plugins() {
return [
new Plugin({
props: {
handleDOMEvents: {
drop(view, event) {
const hasFiles = event.dataTransfer
&& event.dataTransfer.files
&& event.dataTransfer.files.length
if (!hasFiles) {
return
}
const images = Array
.from(event.dataTransfer.files)
.filter(file => (/image/i).test(file.type))
if (images.length === 0) {
return
}
event.preventDefault()
const { schema } = view.state
const coordinates = view.posAtCoords({ left: event.clientX, top: event.clientY })
images.forEach(image => {
const reader = new FileReader()
reader.onload = readerEvent => {
const node = schema.nodes.image.create({
src: readerEvent.target.result,
})
const transaction = view.state.tr.insert(coordinates.pos, node)
view.dispatch(transaction)
}
reader.readAsDataURL(image)
})
},
},
},
}),
]
}
}