not really known
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

65 lines
1.9 KiB

  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;