UNPKG

1.2 kBJavaScriptView Raw
1import Parchment from 'parchment';
2import { sanitize } from '../formats/link';
3
4const ATTRIBUTES = [
5 'alt',
6 'height',
7 'width'
8];
9
10
11class Image extends Parchment.Embed {
12 static create(value) {
13 let node = super.create(value);
14 if (typeof value === 'string') {
15 node.setAttribute('src', this.sanitize(value));
16 }
17 return node;
18 }
19
20 static formats(domNode) {
21 return ATTRIBUTES.reduce(function(formats, attribute) {
22 if (domNode.hasAttribute(attribute)) {
23 formats[attribute] = domNode.getAttribute(attribute);
24 }
25 return formats;
26 }, {});
27 }
28
29 static match(url) {
30 return /\.(jpe?g|gif|png)$/.test(url) || /^data:image\/.+;base64/.test(url);
31 }
32
33 static sanitize(url) {
34 return sanitize(url, ['http', 'https', 'data']) ? url : '//:0';
35 }
36
37 static value(domNode) {
38 return domNode.getAttribute('src');
39 }
40
41 format(name, value) {
42 if (ATTRIBUTES.indexOf(name) > -1) {
43 if (value) {
44 this.domNode.setAttribute(name, value);
45 } else {
46 this.domNode.removeAttribute(name);
47 }
48 } else {
49 super.format(name, value);
50 }
51 }
52}
53Image.blotName = 'image';
54Image.tagName = 'IMG';
55
56
57export default Image;