uploader.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import Delta from 'quill-delta';
  2. import Emitter from '../core/emitter';
  3. import Module from '../core/module';
  4. class Uploader extends Module {
  5. constructor(quill, options) {
  6. super(quill, options);
  7. quill.root.addEventListener('drop', e => {
  8. e.preventDefault();
  9. let native;
  10. if (document.caretRangeFromPoint) {
  11. native = document.caretRangeFromPoint(e.clientX, e.clientY);
  12. } else if (document.caretPositionFromPoint) {
  13. const position = document.caretPositionFromPoint(e.clientX, e.clientY);
  14. native = document.createRange();
  15. native.setStart(position.offsetNode, position.offset);
  16. native.setEnd(position.offsetNode, position.offset);
  17. } else {
  18. return;
  19. }
  20. const normalized = quill.selection.normalizeNative(native);
  21. const range = quill.selection.normalizedToRange(normalized);
  22. this.upload(range, e.dataTransfer.files);
  23. });
  24. }
  25. upload(range, files) {
  26. const uploads = [];
  27. Array.from(files).forEach(file => {
  28. if (file && this.options.mimetypes.includes(file.type)) {
  29. uploads.push(file);
  30. }
  31. });
  32. if (uploads.length > 0) {
  33. this.options.handler.call(this, range, uploads);
  34. }
  35. }
  36. }
  37. Uploader.DEFAULTS = {
  38. mimetypes: ['image/png', 'image/jpeg'],
  39. handler(range, files) {
  40. const promises = files.map(file => {
  41. return new Promise(resolve => {
  42. const reader = new FileReader();
  43. reader.onload = e => {
  44. resolve(e.target.result);
  45. };
  46. reader.readAsDataURL(file);
  47. });
  48. });
  49. Promise.all(promises).then(images => {
  50. const update = images.reduce((delta, image) => {
  51. return delta.insert({ image });
  52. }, new Delta().retain(range.index).delete(range.length));
  53. this.quill.updateContents(update, Emitter.sources.USER);
  54. this.quill.setSelection(
  55. range.index + images.length,
  56. Emitter.sources.SILENT,
  57. );
  58. });
  59. },
  60. };
  61. export default Uploader;