utilities-lite.js.es6 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // lite version of discourse/lib/utilities
  2. export function determinePostReplaceSelection({ selection, needle, replacement }) {
  3. const diff = (replacement.end - replacement.start) - (needle.end - needle.start);
  4. if (selection.end <= needle.start) {
  5. // Selection ends (and starts) before needle.
  6. return { start: selection.start, end: selection.end };
  7. } else if (selection.start <= needle.start) {
  8. // Selection starts before needle...
  9. if (selection.end < needle.end) {
  10. // ... and ends inside needle.
  11. return { start: selection.start, end: needle.start };
  12. } else {
  13. // ... and spans needle completely.
  14. return { start: selection.start, end: selection.end + diff };
  15. }
  16. } else if (selection.start < needle.end) {
  17. // Selection starts inside needle...
  18. if (selection.end <= needle.end) {
  19. // ... and ends inside needle.
  20. return { start: replacement.end, end: replacement.end };
  21. } else {
  22. // ... and spans end of needle.
  23. return { start: replacement.end, end: selection.end + diff };
  24. }
  25. } else {
  26. // Selection starts (and ends) behind needle.
  27. return { start: selection.start + diff, end: selection.end + diff };
  28. }
  29. }
  30. const toArray = items => {
  31. items = items || [];
  32. if (!Array.isArray(items)) {
  33. return Array.from(items);
  34. }
  35. return items;
  36. };
  37. export function clipboardData(e, canUpload) {
  38. const clipboard = e.clipboardData ||
  39. e.originalEvent.clipboardData ||
  40. e.delegatedEvent.originalEvent.clipboardData;
  41. const types = toArray(clipboard.types);
  42. let files = toArray(clipboard.files);
  43. if (types.includes("Files") && files.length === 0) { // for IE
  44. files = toArray(clipboard.items).filter(i => i.kind === "file");
  45. }
  46. canUpload = files && canUpload && !types.includes("text/plain");
  47. const canUploadImage = canUpload && files.filter(f => f.type.match('^image/'))[0];
  48. const canPasteHtml = Discourse.SiteSettings.enable_rich_text_paste && types.includes("text/html") && !canUploadImage;
  49. return { clipboard, types, canUpload, canPasteHtml };
  50. }