UNPKG

ehsas_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.

16 lines (13 loc) 13.2 kB
import e from"papaparse";import n,{useState as r,useEffect as t,useMemo as o,useRef as i,useReducer as a,useCallback as c}from"react";import u from"jschardet"; /*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */var s=function(){return s=Object.assign||function(e){for(var n,r=1,t=arguments.length;r<t;r++)for(var o in n=arguments[r])Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o]);return e},s.apply(this,arguments)};function l(e,n){var r={};for(var t in e)Object.prototype.hasOwnProperty.call(e,t)&&n.indexOf(t)<0&&(r[t]=e[t]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(t=Object.getOwnPropertySymbols(e);o<t.length;o++)n.indexOf(t[o])<0&&Object.prototype.propertyIsEnumerable.call(e,t[o])&&(r[t[o]]=e[t[o]])}return r}function f(e,n){for(var r=0,t=n.length,o=e.length;r<t;r++,o++)e[o]=n[r];return e}function d(e){var n=1024,r=1048576,t=1073741824;if(e<r){var o=Number((e/n).toFixed(0));return o<=0?e+" B":o+" KB"}return e<t?(e/r).toFixed(0)+" MB":e<1099511627776?(e/t).toFixed(0)+" GB":""}function p(e,n){var r=!1;"#"==e[0]&&(e=e.slice(1),r=!0);var t=parseInt(e,16),o=(t>>16)+n;o>255?o=255:o<0&&(o=0);var i=(t>>8&255)+n;i>255?i=255:i<0&&(i=0);var a=(255&t)+n;return a>255?a=255:a<0&&(a=0),(r?"#":"")+(a|i<<8|o<<16).toString(16)}function v(e){return"function"==typeof e.isPropagationStopped?e.isPropagationStopped():void 0!==e.cancelBubble&&e.cancelBubble}function g(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];return function(n){for(var r=[],t=1;t<arguments.length;t++)r[t-1]=arguments[t];return e.some((function(e){return!v(n)&&e&&e.apply(void 0,f([n],r)),v(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 y=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 h(e,n){var r="application/x-moz-file"===e.type||function(e,n){if(e&&n){var r=Array.isArray(n)?n:n.split(","),t=e.name||"",o=(e.type||"").toLowerCase(),i=o.replace(/\/.*$/,"");return r.some((function(e){var n=e.trim().toLowerCase();return"."===n.charAt(0)?t.toLowerCase().endsWith(n):n.endsWith("/*")?i===n.replace(/\/.*$/,""):o===n}))}return!0}(e,n);return[r,r?null:y(n)]}function D(e){return null!=e}var F=function(e){return{code:"file-too-large",message:"File is larger than ".concat(e," bytes")}},b=function(e){return{code:"file-too-small",message:"File is smaller than ".concat(e," bytes")}},w={code:"too-many-files",message:"Too many files"};function E(e){e.preventDefault()}function B(n,r){return e.parse(n,r)}function P(n,r){e.parse(n,Object.assign({},{download:!0},r))}function O(n,r){return void 0===r&&(r={}),e.unparse(n,r)}function C(){return{readString:B,readRemoteFile:P,jsonToCSV:O}}var x={Link:"link",Button:"button"};function A(){var r;return{CSVDownloader:(r=function(r){var t=r.children,o=r.data,i=void 0===o?{}:o,a=r.filename,c=r.type,u=void 0===c?x.Link:c,s=r.style,l=void 0===s?{}:s,f=r.className,d=void 0===f?"":f,p=r.bom,v=void 0!==p&&p,g=r.config,m=void 0===g?{}:g,y=function(){var n=v?"\ufeff":"",r=null,t=null;"function"==typeof i&&(i=i()),r="object"==typeof i?e.unparse(i,m):i;var o=new Blob(["".concat(n).concat(r)],{type:"text/csv;charset=utf-8;"}),c=window.navigator;t=c.msSaveBlob?c.msSaveBlob(o,"".concat(a,".csv")):window.URL.createObjectURL(o);var u=document.createElement("a");u.href=t,u.setAttribute("download","".concat(a,".csv")),u.click(),u.remove()};return n.createElement(n.Fragment,null,u===x.Button?n.createElement("button",{onClick:function(){return y()},style:l,className:d},t):n.createElement("a",{onClick:function(){return y()},style:l,className:d},t))},n.useMemo((function(){return r}),[])),Type:x}}var S={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 k(e){var o=e.style,i=e.className,a=e.display,c=r(0),u=c[0],s=c[1];return t((function(){s(e.percentage)}),[e.percentage]),n.createElement("span",{style:Object.assign({},S.progressBar,S.fill,o,{width:"".concat(u,"%"),display:a}),className:i})}function L(e){var r=e.color,t=e.width,o=void 0===t?23:t,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:r,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 R="text/csv, .csv, application/vnd.ms-excel";function j(){var r=function(r){var d=r.children,p=r.accept,y=void 0===p?R:p,B=r.config,P=void 0===B?{}:B,O=r.minSize,C=void 0===O?0:O,x=r.maxSize,A=void 0===x?1/0:x,S=r.maxFiles,j=void 0===S?1:S,T=r.disabled,M=void 0!==T&&T,N=r.noClick,I=void 0!==N&&N,U=r.noDrag,_=void 0!==U&&U,V=r.noDragEventsBubbling,W=void 0!==V&&V,$=r.noKeyboard,q=void 0!==$&&$,G=r.multiple,H=void 0!==G&&G,J=r.preventDropOnDocument,Q=void 0===J||J,X=r.onUploadAccepted,Y=r.validator,Z=r.onUploadRejected,ee=r.onDragEnter,ne=r.onDragOver,re=r.onDragLeave,te=i(null),oe=i(null),ie=i([]),ae=a(K,z),ce=ae[0],ue=ae[1],se=ce.acceptedFile,le=ce.displayProgressBar,fe=ce.progressBarPercentage,de=ce.draggedFiles,pe=ce.isFileDialogActive,ve=function(e){oe.current&&oe.current.contains(e.target)||(e.preventDefault(),ie.current=[])};t((function(){return Q&&(document.addEventListener("dragover",E,!1),document.addEventListener("drop",ve,!1)),function(){Q&&(document.removeEventListener("dragover",E),document.removeEventListener("drop",ve))}}),[oe,Q]);var ge=function(e){return M?null:e},me=function(e){return _?null:ge(e)},ye=function(e){W&&e.stopPropagation()},he=function(e){e.preventDefault(e),e.persist(),ye(e)},De=function(e){ue({displayProgressBar:e,type:"setDisplayProgressBar"})},Fe=function(e){ue({progressBarPercentage:e,type:"setProgressBarPercentage"})},be=function(e){return n.createElement(k,s({display:le,percentage:fe},e))},we=function(e){return n.createElement(L,s({},e))},Ee=c((function(){te.current&&ce.displayProgressBar&&(ue({type:"openDialog"}),te.current.value=null,te.current.click())}),[ue]),Be=function(){pe&&setTimeout((function(){te.current&&(te.current.files.length||ue({type:"closeDialog"}))}),300)};t((function(){return window.addEventListener("focus",Be,!1),function(){window.removeEventListener("focus",Be,!1)}}),[te,pe]);var Pe=c((function(){var e;I||(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(Ee,0):Ee())}),[te,I]),Oe=c((function(n){if(he(n),Fe(0),ie.current=[],m(n)){if(v(n)&&!W)return;var r=[],t=[],o=n.target.files||n.dataTransfer&&n.dataTransfer.files;if(Array.from(o).forEach((function(e){var n=h(e,y),o=n[0],i=n[1],a=function(e,n,r){if(D(e.size))if(D(n)&&D(r)){if(e.size>r)return[!1,F(r)];if(e.size<n)return[!1,b(n)]}else{if(D(n)&&e.size<n)return[!1,b(n)];if(D(r)&&e.size>r)return[!1,F(r)]}return[!0,null]}(e,C,A),c=a[0],u=a[1],s=Y?Y(e):null;if(o&&c&&!s)r.push(e);else{var l=[i,u];s&&(l=l.concat(s)),t.push({file:e,errors:l.filter((function(e){return e}))})}})),(!H&&r.length>1||H&&j>=1&&r.length>j)&&(r.forEach((function(e){t.push({file:e,errors:[w]})})),r.splice(0)),ue({acceptedFiles:r,fileRejections:t,type:"setFiles"}),De("block"),t.length>0&&Z&&Z(t,n),r.length>0&&X){var i={},a=[],c=[],s=[],l=new window.FileReader,f=0;r.forEach((function(n){ue({acceptedFile:n,type:"setFile"}),i={complete:(null==P?void 0:P.complete)||(null==P?void 0:P.step)?P.complete:function(){X({data:a,errors:c,meta:s},n)},step:(null==P?void 0:P.step)?P.step:function(e){if(a.push(e.data),e.errors.length>0&&c.push(e.errors),e.length>0&&s.push(e[0].meta),P&&P.preview){if(f=Math.round(a.length/P.preview*100),a.length===P.preview)X({data:a,errors:c,meta:s},n)}else{var r=e.meta.cursor,t=Math.round(r/n.size*100);if(t===f)return;f=t}Fe(f)}},i=Object.assign({},P,i),l.onload=function(n){P.encoding||(P.encoding=u.detect(n.target.result).encoding,i=Object.assign({},P,i)),e.parse(n.target.result,i)},l.onloadend=function(){setTimeout((function(){De("none")}),2e3)},(null==P?void 0:P.encoding)?l.readAsText(n,P.encoding||"utf-8"):l.readAsBinaryString(n)}))}}}),[H,y,C,A,j,Y,X]),Ce=c((function(e){ye(e)}),[]),xe=function(e){return q?null:ge(e)},Ae=c((function(e){if(he(e),ie.current=f(f([],ie.current),[e.target]),m(e)){if(v(e)&&!W)return;ue({draggedFiles:de,isDragActive:!0,type:"setDraggedFiles"}),ee&&ee(e)}}),[ee,W]),Se=c((function(e){he(e);var n=m(e);if(n&&e.dataTransfer)try{e.dataTransfer.dropEffect="copy"}catch(e){}return n&&ne&&ne(e),!1}),[ne,W]),ke=c((function(e){he(e);var n=ie.current.filter((function(e){return oe.current&&oe.current.contains(e)})),r=n.indexOf(e.target);-1!==r&&n.splice(r,1),ie.current=n,n.length>0||(ue({isDragActive:!1,type:"setDraggedFiles",draggedFiles:[]}),m(e)&&re&&re(e))}),[oe,re,W]),Le=c((function(e){oe.current&&oe.current.isEqualNode(e.target)&&("Space"!==e.key&&"Enter"!==e.key||(e.preventDefault(),Ee()))}),[oe,te]),Re=c((function(){ue({type:"focus"})}),[]),je=c((function(){ue({type:"blur"})}),[]),Te=o((function(){return function(e){void 0===e&&(e={});var n=e.onClick,r=void 0===n?function(){}:n,t=e.onDrop,o=void 0===t?function(){}:t,i=e.onDragOver,a=void 0===i?function(){}:i,c=e.onDragLeave,u=void 0===c?function(){}:c,f=e.onKeyDown,d=void 0===f?function(){}:f,p=e.onFocus,v=void 0===p?function(){}:p,m=e.onBlur,y=void 0===m?function(){}:m,h=e.onDragEnter,D=void 0===h?function(){}:h,F=l(e,["onClick","onDrop","onDragOver","onDragLeave","onKeyDown","onFocus","onBlur","onDragEnter"]);return s({onClick:ge(g(r,Pe)),onDrop:me(g(o,Oe)),onDragEnter:me(g(D,Ae)),onDragOver:me(g(a,Se)),onDragLeave:me(g(u,ke)),onKeyDown:xe(g(d,Le)),onFocus:xe(g(v,Re)),onBlur:xe(g(y,je))},F)}}),[oe,Le,Re,je,Pe,Ae,Se,ke,Oe,q,_,M]),ze=o((function(){return function(e){var n;void 0===e&&(e={});var r=e.refKey,t=void 0===r?"ref":r,o=e.onChange,i=void 0===o?function(){}:o,a=e.onClick,c=void 0===a?function(){}:a,u=l(e,["refKey","onChange","onClick"]),f=((n={accept:y,multiple:H,type:"file",style:{display:"none"},onChange:ge(g(i,Oe)),onClick:ge(g(c,Ce)),autoComplete:"off",tabIndex:-1})[t]=te,n);return s(s({},f),u)}}),[te,y,Oe,M]),Ke=c((function(e){te.current.value="",ue({type:"reset"}),e.stopPropagation()}),[]),Me=o((function(){return function(e){void 0===e&&(e={});var n=e.onClick,r=void 0===n?function(){}:n,t=l(e,["onClick"]);return s({onClick:ge(g(r,Ke))},t)}}),[Ke]);return n.createElement(n.Fragment,null,n.createElement("input",s({},ze())),d({getRootProps:Te,acceptedFile:se,ProgressBar:be,getRemoveFileProps:Me,Remove:we}))};return o((function(){return r}),[])}function T(){return{CSVReader:j()}}var z={displayProgressBar:"none",progressBarPercentage:0,isDragActive:!1,isFileDialogActive:!1,isFocused:!1,draggedFiles:[],acceptedFiles:[],acceptedFile:null};function K(e,n){switch(n.type){case"openDialog":return s(s({},e),{isFileDialogActive:!0});case"closeDialog":return s(s({},e),{isFileDialogActive:!1});case"setFiles":return s(s({},e),{acceptedFiles:n.acceptedFiles,fileRejections:n.fileRejections});case"setFile":return s(s({},e),{acceptedFile:n.acceptedFile});case"setDisplayProgressBar":return s(s({},e),{displayProgressBar:n.displayProgressBar});case"setProgressBarPercentage":return s(s({},e),{progressBarPercentage:n.progressBarPercentage});case"setDraggedFiles":var r=n.isDragActive,t=n.draggedFiles;return s(s({},e),{draggedFiles:t,isDragActive:r});case"focus":return s(s({},e),{isFocused:!0});case"blur":return s(s({},e),{isFocused:!1});case"reset":return s({},z);default:return e}}var M=e.BAD_DELIMITERS,N=e.RECORD_SEP,I=e.UNIT_SEP,U=e.WORKERS_SUPPORTED,_=e.LocalChunkSize,V=e.DefaultDelimiter;export{M as BAD_DELIMITERS,V as DefaultDelimiter,_ as LocalChunkSize,N as RECORD_SEP,I as UNIT_SEP,U as WORKERS_SUPPORTED,d as formatFileSize,p as lightenDarkenColor,A as useCSVDownloader,T as useCSVReader,C as usePapaParse};