UNPKG

react-papaparse

Version:

The fastest in-browser CSV (or delimited text) parser for React. It is full of useful features such as CSVReader, CSVDownloader, readString, jsonToCSV, readRemoteFile, ... etc.

2 lines (1 loc) 14.1 kB
import e from"papaparse";import n,{useState as t,useEffect as r,useMemo as o,useRef as i,useReducer as a,useCallback as c}from"react";var u=function(){return u=Object.assign||function(e){for(var n,t=1,r=arguments.length;t<r;t++)for(var o in n=arguments[t])Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o]);return e},u.apply(this,arguments)};function l(e,n){var t={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&n.indexOf(r)<0&&(t[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(r=Object.getOwnPropertySymbols(e);o<r.length;o++)n.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(t[r[o]]=e[r[o]])}return t}function s(e,n,t,r){return new(t||(t=Promise))((function(o,i){function a(e){try{u(r.next(e))}catch(e){i(e)}}function c(e){try{u(r.throw(e))}catch(e){i(e)}}function u(e){var n;e.done?o(e.value):(n=e.value,n instanceof t?n:new t((function(e){e(n)}))).then(a,c)}u((r=r.apply(e,n||[])).next())}))}function f(e,n){var t,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function c(c){return function(u){return function(c){if(t)throw new TypeError("Generator is already executing.");for(;i&&(i=0,c[0]&&(a=0)),a;)try{if(t=1,r&&(o=2&c[0]?r.return:c[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,c[1])).done)return o;switch(r=0,o&&(c=[2&c[0],o.value]),c[0]){case 0:case 1:o=c;break;case 4:return a.label++,{value:c[1],done:!1};case 5:a.label++,r=c[1],c=[0];continue;case 7:c=a.ops.pop(),a.trys.pop();continue;default:if(!(o=a.trys,(o=o.length>0&&o[o.length-1])||6!==c[0]&&2!==c[0])){a=0;continue}if(3===c[0]&&(!o||c[1]>o[0]&&c[1]<o[3])){a.label=c[1];break}if(6===c[0]&&a.label<o[1]){a.label=o[1],o=c;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(c);break}o[2]&&a.ops.pop(),a.trys.pop();continue}c=n.call(e,a)}catch(e){c=[6,e],r=0}finally{t=o=0}if(5&c[0])throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}([c,u])}}}function d(e,n,t){if(t||2===arguments.length)for(var r,o=0,i=n.length;o<i;o++)!r&&o in n||(r||(r=Array.prototype.slice.call(n,0,o)),r[o]=n[o]);return e.concat(r||Array.prototype.slice.call(n))}"function"==typeof SuppressedError&&SuppressedError;function p(e){var n=1024,t=1048576,r=1073741824;if(e<t){var o=Number((e/n).toFixed(0));return o<=0?e+" B":o+" KB"}return e<r?(e/t).toFixed(0)+" MB":e<1099511627776?(e/r).toFixed(0)+" GB":""}function v(e,n){var t=!1;"#"==e[0]&&(e=e.slice(1),t=!0);var r=parseInt(e,16),o=(r>>16)+n;o>255?o=255:o<0&&(o=0);var i=(r>>8&255)+n;i>255?i=255:i<0&&(i=0);var a=(255&r)+n;return a>255?a=255:a<0&&(a=0),(t?"#":"")+(a|i<<8|o<<16).toString(16)}function g(e){return"function"==typeof e.isPropagationStopped?e.isPropagationStopped():void 0!==e.cancelBubble&&e.cancelBubble}function y(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];return function(n){for(var t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];return e.some((function(e){return!g(n)&&e&&e.apply(void 0,d([n],t,!1)),g(n)}))}}function m(e){return e.dataTransfer?Array.prototype.some.call(e.dataTransfer.types,(function(e){return"Files"===e||"application/x-moz-file"===e})):!!e.target&&!!e.target.files}var h=function(e){e=Array.isArray(e)&&1===e.length?e[0]:e;var n=Array.isArray(e)?"one of ".concat(e.join(", ")):e;return{code:"file-invalid-type",message:"File type must be ".concat(n)}};function b(e,n){var t="application/x-moz-file"===e.type||function(e,n){if(e&&n){var t=Array.isArray(n)?n:n.split(","),r=e.name||"",o=(e.type||"").toLowerCase(),i=o.replace(/\/.*$/,"");return t.some((function(e){var n=e.trim().toLowerCase();return"."===n.charAt(0)?r.toLowerCase().endsWith(n):n.endsWith("/*")?i===n.replace(/\/.*$/,""):o===n}))}return!0}(e,n);return[t,t?null:h(n)]}function w(e){return null!=e}var D=function(e){return{code:"file-too-large",message:"File is larger than ".concat(e," bytes")}},F=function(e){return{code:"file-too-small",message:"File is smaller than ".concat(e," bytes")}},E={code:"too-many-files",message:"Too many files"};function B(e){e.preventDefault()}function P(n,t){return e.parse(n,t)}function x(n,t){e.parse(n,Object.assign({},{download:!0},t))}function O(n,t){return void 0===t&&(t={}),e.unparse(n,t)}function S(){return{readString:P,readRemoteFile:x,jsonToCSV:O}}var k={Link:"link",Button:"button"};function C(){return{CSVDownloader:function(){var t=this,r=function(r){var o=r.children,i=r.data,a=void 0===i?{}:i,c=r.filename,u=r.type,l=void 0===u?k.Link:u,d=r.style,p=void 0===d?{}:d,v=r.className,g=void 0===v?"":v,y=r.bom,m=void 0!==y&&y,h=r.config,b=void 0===h?{}:h,w=function(){return s(t,void 0,void 0,(function(){var n,t,r,o,i,u;return f(this,(function(l){switch(l.label){case 0:return n=m?"\ufeff":"",t=null,r=null,"function"!=typeof a?[3,2]:[4,a()];case 1:a=l.sent(),l.label=2;case 2:return t="object"==typeof a?e.unparse(a,b):a,o=new Blob(["".concat(n).concat(t)],{type:"text/csv;charset=utf-8;"}),i=window.navigator,r=i.msSaveBlob?i.msSaveBlob(o,"".concat(c,".csv")):window.URL.createObjectURL(o),(u=document.createElement("a")).href=r,u.setAttribute("download","".concat(c,".csv")),u.click(),u.remove(),[2]}}))}))};return n.createElement(n.Fragment,null,l===k.Button?n.createElement("button",{onClick:function(){return w()},style:p,className:g},o):n.createElement("a",{onClick:function(){return w()},style:p,className:g},o))};return n.useMemo((function(){return r}),[])}(),Type:k}}var A={progressBar:{borderRadius:3,boxShadow:"inset 0 1px 3px rgba(0, 0, 0, .2)",bottom:14,width:"100%"},button:{position:"inherit",width:"100%"},fill:{backgroundColor:"#659cef",borderRadius:3,height:10,transition:"width 500ms ease-in-out"}};function L(e){var o=e.style,i=e.className,a=e.display,c=t(0),u=c[0],l=c[1];return r((function(){l(e.percentage)}),[e.percentage]),n.createElement("span",{style:Object.assign({},A.progressBar,A.fill,o,{width:"".concat(u,"%"),display:a}),className:i})}function R(e){var t=e.color,r=e.width,o=void 0===r?23:r,i=e.height,a=void 0===i?23:i;return n.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:o,height:a,viewBox:"0 0 512 512"},n.createElement("path",{fill:t,d:"M504.1 256C504.1 119 393 7.9 256 7.9S7.9 119 7.9 256 119 504.1 256 504.1 504.1 393 504.1 256z"}),n.createElement("path",{fill:"#FFF",d:"M285 256l72.5-84.2c7.9-9.2 6.9-23-2.3-31-9.2-7.9-23-6.9-30.9 2.3L256 222.4l-68.2-79.2c-7.9-9.2-21.8-10.2-31-2.3-9.2 7.9-10.2 21.8-2.3 31L227 256l-72.5 84.2c-7.9 9.2-6.9 23 2.3 31 4.1 3.6 9.2 5.3 14.3 5.3 6.2 0 12.3-2.6 16.6-7.6l68.2-79.2 68.2 79.2c4.3 5 10.5 7.6 16.6 7.6 5.1 0 10.2-1.7 14.3-5.3 9.2-7.9 10.2-21.8 2.3-31L285 256z"}))}var T="text/csv, .csv, application/vnd.ms-excel";function j(){var t=function(t){var s=t.children,f=t.accept,p=void 0===f?T:f,v=t.config,h=void 0===v?{}:v,P=t.minSize,x=void 0===P?0:P,O=t.maxSize,S=void 0===O?1/0:O,k=t.maxFiles,C=void 0===k?1:k,A=t.disabled,j=void 0!==A&&A,z=t.noClick,N=void 0!==z&&z,I=t.noDrag,U=void 0!==I&&I,_=t.noDragEventsBubbling,q=void 0!==_&&_,V=t.noKeyboard,W=void 0!==V&&V,G=t.multiple,$=void 0!==G&&G,H=t.required,J=void 0!==H&&H,Q=t.preventDropOnDocument,X=void 0===Q||Q,Y=t.onUploadAccepted,Z=t.validator,ee=t.onUploadRejected,ne=t.onDragEnter,te=t.onDragOver,re=t.onDragLeave,oe=i(null),ie=i(null),ae=i([]),ce=a(M,K),ue=ce[0],le=ce[1],se=ue.acceptedFile,fe=ue.displayProgressBar,de=ue.progressBarPercentage,pe=ue.draggedFiles,ve=ue.isFileDialogActive,ge=function(e){ie.current&&ie.current.contains(e.target)||(e.preventDefault(),ae.current=[])};r((function(){return X&&(document.addEventListener("dragover",B,!1),document.addEventListener("drop",ge,!1)),function(){X&&(document.removeEventListener("dragover",B),document.removeEventListener("drop",ge))}}),[ie,X]);var ye=function(e){return j?null:e},me=function(e){return U?null:ye(e)},he=function(e){q&&e.stopPropagation()},be=function(e){e.preventDefault(e),e.persist(),he(e)},we=function(e){le({displayProgressBar:e,type:"setDisplayProgressBar"})},De=function(e){le({progressBarPercentage:e,type:"setProgressBarPercentage"})},Fe=function(e){return n.createElement(L,u({display:fe,percentage:de},e))},Ee=function(e){return n.createElement(R,u({},e))},Be=c((function(){oe.current&&ue.displayProgressBar&&(le({type:"openDialog"}),oe.current.value=null,oe.current.click())}),[le]),Pe=function(){ve&&setTimeout((function(){oe.current&&(oe.current.files.length||le({type:"closeDialog"}))}),300)};r((function(){return window.addEventListener("focus",Pe,!1),function(){window.removeEventListener("focus",Pe,!1)}}),[oe,ve]);var xe=c((function(){var e;N||(void 0===e&&(e=window.navigator.userAgent),function(e){return-1!==e.indexOf("MSIE")||-1!==e.indexOf("Trident/")}(e)||function(e){return-1!==e.indexOf("Edge/")}(e)?setTimeout(Be,0):Be())}),[oe,N]),Oe=c((function(n){if(be(n),De(0),ae.current=[],m(n)){if(g(n)&&!q)return;var t=[],r=[],o=n.target.files||n.dataTransfer&&n.dataTransfer.files;if(Array.from(o).forEach((function(e){var n=b(e,p),o=n[0],i=n[1],a=function(e,n,t){if(w(e.size))if(w(n)&&w(t)){if(e.size>t)return[!1,D(t)];if(e.size<n)return[!1,F(n)]}else{if(w(n)&&e.size<n)return[!1,F(n)];if(w(t)&&e.size>t)return[!1,D(t)]}return[!0,null]}(e,x,S),c=a[0],u=a[1],l=Z?Z(e):null;if(o&&c&&!l)t.push(e);else{var s=[i,u];l&&(s=s.concat(l)),r.push({file:e,errors:s.filter((function(e){return e}))})}})),(!$&&t.length>1||$&&C>=1&&t.length>C)&&(t.forEach((function(e){r.push({file:e,errors:[E]})})),t.splice(0)),le({acceptedFiles:t,fileRejections:r,type:"setFiles"}),we("block"),r.length>0&&ee&&ee(r,n),t.length>0&&Y){var i={},a=[],c=[],u=[],l=new window.FileReader,s=0;t.forEach((function(n){le({acceptedFile:n,type:"setFile"}),i={complete:(null==h?void 0:h.complete)||(null==h?void 0:h.step)?h.complete:function(){Y({data:a,errors:c,meta:u},n)},step:(null==h?void 0:h.step)?h.step:function(e){if(a.push(e.data),e.errors.length>0&&c.push(e.errors),e.length>0&&u.push(e[0].meta),h&&h.preview){if(s=Math.round(a.length/h.preview*100),a.length===h.preview)Y({data:a,errors:c,meta:u},n)}else{var t=e.meta.cursor,r=Math.round(t/n.size*100);if(r===s)return;s=r}De(s)}},i=Object.assign({},h,i),l.onload=function(n){e.parse(n.target.result,i)},l.onloadend=function(){setTimeout((function(){we("none")}),2e3)},l.readAsText(n,h.encoding||"utf-8")}))}}}),[$,p,x,S,C,Z,Y]),Se=c((function(e){he(e)}),[]),ke=function(e){return W?null:ye(e)},Ce=c((function(e){if(be(e),ae.current=d(d([],ae.current,!0),[e.target],!1),m(e)){if(g(e)&&!q)return;le({draggedFiles:pe,isDragActive:!0,type:"setDraggedFiles"}),ne&&ne(e)}}),[ne,q]),Ae=c((function(e){be(e);var n=m(e);if(n&&e.dataTransfer)try{e.dataTransfer.dropEffect="copy"}catch(e){}return n&&te&&te(e),!1}),[te,q]),Le=c((function(e){be(e);var n=ae.current.filter((function(e){return ie.current&&ie.current.contains(e)})),t=n.indexOf(e.target);-1!==t&&n.splice(t,1),ae.current=n,n.length>0||(le({isDragActive:!1,type:"setDraggedFiles",draggedFiles:[]}),m(e)&&re&&re(e))}),[ie,re,q]),Re=c((function(e){ie.current&&ie.current.isEqualNode(e.target)&&("Space"!==e.key&&"Enter"!==e.key||(e.preventDefault(),Be()))}),[ie,oe]),Te=c((function(){le({type:"focus"})}),[]),je=c((function(){le({type:"blur"})}),[]),ze=o((function(){return function(e){void 0===e&&(e={});var n=e.onClick,t=void 0===n?function(){}:n,r=e.onDrop,o=void 0===r?function(){}:r,i=e.onDragOver,a=void 0===i?function(){}:i,c=e.onDragLeave,s=void 0===c?function(){}:c,f=e.onKeyDown,d=void 0===f?function(){}:f,p=e.onFocus,v=void 0===p?function(){}:p,g=e.onBlur,m=void 0===g?function(){}:g,h=e.onDragEnter,b=void 0===h?function(){}:h,w=l(e,["onClick","onDrop","onDragOver","onDragLeave","onKeyDown","onFocus","onBlur","onDragEnter"]);return u({onClick:ye(y(t,xe)),onDrop:me(y(o,Oe)),onDragEnter:me(y(b,Ce)),onDragOver:me(y(a,Ae)),onDragLeave:me(y(s,Le)),onKeyDown:ke(y(d,Re)),onFocus:ke(y(v,Te)),onBlur:ke(y(m,je))},w)}}),[ie,Re,Te,je,xe,Ce,Ae,Le,Oe,W,U,j]),Ke=o((function(){return function(e){var n;void 0===e&&(e={});var t=e.refKey,r=void 0===t?"ref":t,o=e.onChange,i=void 0===o?function(){}:o,a=e.onClick,c=void 0===a?function(){}:a,s=l(e,["refKey","onChange","onClick"]),f=((n={accept:p,multiple:$,required:J,type:"file",style:{display:"none"},onChange:ye(y(i,Oe)),onClick:ye(y(c,Se)),autoComplete:"off",tabIndex:-1})[r]=oe,n);return u(u({},f),s)}}),[oe,p,Oe,j]),Me=c((function(e){oe.current.value="",le({type:"reset"}),e.stopPropagation()}),[]),Ne=o((function(){return function(e){void 0===e&&(e={});var n=e.onClick,t=void 0===n?function(){}:n,r=l(e,["onClick"]);return u({onClick:ye(y(t,Me))},r)}}),[Me]);return n.createElement(n.Fragment,null,n.createElement("input",u({},Ke())),s({getRootProps:ze,acceptedFile:se,ProgressBar:Fe,getRemoveFileProps:Ne,Remove:Ee}))};return o((function(){return t}),[])}function z(){return{CSVReader:j()}}var K={displayProgressBar:"none",progressBarPercentage:0,isDragActive:!1,isFileDialogActive:!1,isFocused:!1,draggedFiles:[],acceptedFiles:[],acceptedFile:null};function M(e,n){switch(n.type){case"openDialog":return u(u({},e),{isFileDialogActive:!0});case"closeDialog":return u(u({},e),{isFileDialogActive:!1});case"setFiles":return u(u({},e),{acceptedFiles:n.acceptedFiles,fileRejections:n.fileRejections});case"setFile":return u(u({},e),{acceptedFile:n.acceptedFile});case"setDisplayProgressBar":return u(u({},e),{displayProgressBar:n.displayProgressBar});case"setProgressBarPercentage":return u(u({},e),{progressBarPercentage:n.progressBarPercentage});case"setDraggedFiles":var t=n.isDragActive,r=n.draggedFiles;return u(u({},e),{draggedFiles:r,isDragActive:t});case"focus":return u(u({},e),{isFocused:!0});case"blur":return u(u({},e),{isFocused:!1});case"reset":return u({},K);default:return e}}var N=e.BAD_DELIMITERS,I=e.RECORD_SEP,U=e.UNIT_SEP,_=e.WORKERS_SUPPORTED,q=e.LocalChunkSize,V=e.DefaultDelimiter;export{N as BAD_DELIMITERS,V as DefaultDelimiter,q as LocalChunkSize,I as RECORD_SEP,U as UNIT_SEP,_ as WORKERS_SUPPORTED,p as formatFileSize,O as jsonToCSV,v as lightenDarkenColor,x as readRemoteFile,P as readString,C as useCSVDownloader,z as useCSVReader,S as usePapaParse};