upload.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.upload = upload;
  6. var _dom = require("@testing-library/dom");
  7. var _click = require("./click");
  8. var _blur = require("./blur");
  9. var _focus = require("./focus");
  10. function upload(element, fileOrFiles, init, {
  11. applyAccept = false
  12. } = {}) {
  13. if (element.disabled) return;
  14. (0, _click.click)(element, init);
  15. const input = element.tagName === 'LABEL' ? element.control : element;
  16. const files = (Array.isArray(fileOrFiles) ? fileOrFiles : [fileOrFiles]).filter(file => !applyAccept || isAcceptableFile(file, element.accept)).slice(0, input.multiple ? undefined : 1); // blur fires when the file selector pops up
  17. (0, _blur.blur)(element, init); // focus fires when they make their selection
  18. (0, _focus.focus)(element, init); // do not fire an input event if the file selection does not change
  19. if (files.length === input.files.length && files.every((f, i) => f === input.files.item(i))) {
  20. return;
  21. } // the event fired in the browser isn't actually an "input" or "change" event
  22. // but a new Event with a type set to "input" and "change"
  23. // Kinda odd...
  24. const inputFiles = {
  25. length: files.length,
  26. item: index => files[index],
  27. ...files
  28. };
  29. (0, _dom.fireEvent)(input, (0, _dom.createEvent)('input', input, {
  30. target: {
  31. files: inputFiles
  32. },
  33. bubbles: true,
  34. cancelable: false,
  35. composed: true,
  36. ...init
  37. }));
  38. _dom.fireEvent.change(input, {
  39. target: {
  40. files: inputFiles
  41. },
  42. ...init
  43. });
  44. }
  45. function isAcceptableFile(file, accept) {
  46. if (!accept) {
  47. return true;
  48. }
  49. const wildcards = ['audio/*', 'image/*', 'video/*'];
  50. return accept.split(',').some(acceptToken => {
  51. if (acceptToken[0] === '.') {
  52. // tokens starting with a dot represent a file extension
  53. return file.name.endsWith(acceptToken);
  54. } else if (wildcards.includes(acceptToken)) {
  55. return file.type.startsWith(acceptToken.substr(0, acceptToken.length - 1));
  56. }
  57. return file.type === acceptToken;
  58. });
  59. }