image.js 1.4 KB

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