image.js 1.2 KB

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