@firecms/data_import_export 3.0.0-canary.6 → 3.0.0-canary.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.umd.js CHANGED
@@ -1,3 +1,3 @@
1
- (function(m,f){typeof exports=="object"&&typeof module<"u"?f(exports,require("react"),require("react/jsx-runtime"),require("@firecms/core"),require("@firecms/ui"),require("@firecms/schema_inference"),require("xlsx")):typeof define=="function"&&define.amd?define(["exports","react","react/jsx-runtime","@firecms/core","@firecms/ui","@firecms/schema_inference","xlsx"],f):(m=typeof globalThis<"u"?globalThis:m||self,f(m["FireCMS data import/export"]={},m.React,m.jsxRuntime,m.core,m.ui,m.schema_inference,m.XLSX))})(this,function(m,f,t,h,l,pe,fe){"use strict";function ge(e){const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const a in e)if(a!=="default"){const r=Object.getOwnPropertyDescriptor(e,a);Object.defineProperty(n,a,r.get?r:{enumerable:!0,get:()=>e[a]})}}return n.default=e,Object.freeze(n)}const G=ge(fe),Q=()=>{const[e,n]=f.useState(!1),[a,r]=f.useState(),[s,o]=f.useState([]),[i,c]=f.useState([]),[p,d]=f.useState({}),[g,y]=f.useState({});return{inUse:e,setInUse:n,idColumn:a,setIdColumn:r,entities:i,setEntities:c,importData:s,setImportData:o,headersMapping:p,setHeadersMapping:d,originProperties:g,setOriginProperties:y}};function Y(e){return new Promise((n,a)=>{if(e.type==="application/json"){console.debug("Converting JSON file to JSON",e.name);const r=new FileReader;r.onload=function(s){const o=s.target?.result,i=JSON.parse(o);Array.isArray(i)||a(new Error("JSON file should contain an array of objects")),n(i)},r.readAsText(e)}else{console.debug("Converting Excel file to JSON",e.name);const r=new FileReader;r.onload=function(s){const o=new Uint8Array(s.target?.result),i=G.read(o,{type:"array",codepage:65001,cellDates:!0}),c=i.SheetNames[0],p=i.Sheets[c],y=G.utils.sheet_to_json(p).map(he).map(L);n(y)},r.readAsArrayBuffer(e)}})}function he(e){return Object.keys(e).reduce((n,a)=>{try{n[a]=JSON.parse(e[a])}catch{n[a]=e[a]}return n},{})}function L(e){return Object.keys(e).reduce((n,a)=>{let r=n;const s=a.split(".");return s.forEach((o,i)=>{if(/^[\w]+\[\d+\]$/.test(o)){const c=o.slice(0,o.indexOf("[")),p=parseInt(o.slice(o.indexOf("[")+1,o.indexOf("]")));r[c]||(r[c]=[]),i!==s.length-1?(r[c][p]=r[c][p]||{},r=r[c][p]):r[c][p]=e[a]}else i!==s.length-1?(r[o]=r[o]||{},r=r[o]):r[o]=e[a]}),n},{})}function Z(e,n,a,r,s,o){const i=J(e);n&&delete i[n];const c=Object.entries(i).map(([d,g])=>{const y=a[d]??d;if(!h.getPropertyInPath(r,y))return{};const b=s[y];let T=g;return b&&(T=j(g,b)),{[y]:T}}).reduce((d,g)=>({...d,...g}),{}),p=L(c);return{id:n?e[n]:void 0,values:p,path:o}}function J(e,n=""){return Object.keys(e).reduce((a,r)=>{const s=n?`${n}.${r}`:r;return typeof e[r]=="object"&&e[r]!==null&&!Array.isArray(e[r])?Object.assign(a,J(e[r],s)):a[s]=e[r],a},{})}function j(e,n){if(n===void 0)return e;const{from:a,to:r}=n;if(a==="array"&&r==="array"&&n.fromSubtype&&n.toSubtype&&Array.isArray(e))return e.map(s=>j(s,{from:n.fromSubtype,to:n.toSubtype}));if(a==="string"&&r==="number"&&typeof e=="string")return Number(e);if(a==="string"&&r==="array"&&n.toSubtype&&typeof e=="string")return e.split(",").map(s=>j(s,{from:"string",to:n.toSubtype}));if(a==="string"&&r==="boolean")return e==="true";if(a==="number"&&r==="boolean")return e===1;if(a==="boolean"&&r==="number")return e?1:0;if(a==="boolean"&&r==="string")return e?"true":"false";if(a==="number"&&r==="string"&&typeof e=="number")return e.toString();if(a==="string"&&r==="array"&&typeof e=="string")return e.split(",").map(s=>s.trim());if(a==="string"&&r==="date"&&typeof e=="string")try{return new Date(e)}catch{return e}else{if(a==="date"&&r==="string")return e instanceof Date&&e.toISOString();if(a==="number"&&r==="date"&&typeof e=="number")try{return new Date(e)}catch{return e}else if(a==="string"&&r==="reference"&&typeof e=="string"){const s=e.split("/").slice(0,-1).join("/"),o=e.split("/").slice(-1)[0];return new h.EntityReference(o,s)}else{if(a===r)return e;if(a==="array"&&r==="string"&&Array.isArray(e))return e.join(",")}}return e}function K(e){return typeof e=="number"?"number":typeof e=="string"?"string":typeof e=="boolean"?"boolean":e instanceof Date?"date":Array.isArray(e)?"array":"map"}function R(e,n){function a(r,s){const o={};return Object.keys(r).forEach(i=>{const c=s?`${s}.${i}`:i,p=h.getPropertyInPath(r,i),d=h.getPropertyInPath(e,c);if(p){if(p.dataType==="map"&&p.properties){const g=a(p.properties,c);Object.keys(g).forEach(y=>{o[`${c}.${y}`]=g[y]});return}if(d){const g=d.dataType,y=p.dataType;let x,b;p.dataType==="array"&&p.of&&(b=p.of.dataType),d?.dataType==="array"&&d?.of&&(x=d.of.dataType),(g!==y||x!==b)&&(o[i]={from:g,to:y,fromSubtype:x,toSubtype:b})}}}),o}return a(n)}function ee({idColumn:e,headersMapping:n,originProperties:a,destinationProperties:r,onIdPropertyChanged:s,buildPropertyView:o}){return t.jsxs(t.Fragment,{children:[t.jsx(ye,{idColumn:e,headersMapping:n,onChange:s}),t.jsxs(l.Table,{style:{tableLayout:"fixed"},children:[t.jsxs(l.TableHeader,{children:[t.jsx(l.TableCell,{header:!0,style:{width:"20%"},children:"Column in file"}),t.jsx(l.TableCell,{header:!0}),t.jsx(l.TableCell,{header:!0,style:{width:"75%"},children:"Property"})]}),t.jsx(l.TableBody,{children:r&&Object.entries(n).map(([i,c])=>{const p=n[i],d=c?h.getPropertyInPath(r,c):null,g=h.getPropertyInPath(a,i),y=g?g.dataType==="array"&&typeof g.of=="object"?`${g.dataType} - ${g.of.dataType}`:g.dataType:void 0;return t.jsxs(l.TableRow,{style:{height:"90px"},children:[t.jsxs(l.TableCell,{style:{width:"20%"},children:[t.jsx(l.Typography,{variant:"body2",children:i}),g&&t.jsx(l.Typography,{variant:"caption",color:"secondary",children:y})]}),t.jsx(l.TableCell,{children:t.jsx(l.ChevronRightIcon,{})}),t.jsx(l.TableCell,{className:i===e?"text-center":void 0,style:{width:"75%"},children:o?.({isIdColumn:i===e,property:d,propertyKey:p,importKey:i})})]},i)})})]})]})}function ye({idColumn:e,headersMapping:n,onChange:a}){return t.jsx("div",{children:t.jsxs(l.Select,{size:"small",value:e??"",onChange:r=>{a(r.target.value)},renderValue:r=>t.jsx(l.Typography,{variant:"body2",children:r!==""?r:"Autogenerate ID"}),label:"Column that will be used as ID for each document",children:[t.jsx(l.SelectItem,{value:"",children:"Autogenerate ID"}),Object.entries(n).map(([r,s])=>t.jsx(l.SelectItem,{value:r,children:r},r))]})})}function re({onDataAdded:e}){const n=h.useSnackbarController();return t.jsx(l.FileUpload,{accept:{"text/*":[".csv",".xls",".xlsx"],"application/vnd.ms-excel":[".xls",".xlsx"],"application/msexcel":[".xls",".xlsx"],"application/vnd.ms-office":[".xls",".xlsx"],"application/xls":[".xls",".xlsx"],"application/x-xls":[".xls",".xlsx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":[".xls",".xlsx"],"application/json":[".json"]},preventDropOnDocument:!0,size:"small",maxFiles:1,uploadDescription:t.jsxs(t.Fragment,{children:[t.jsx(l.UploadIcon,{}),"Drag and drop a file here or click to upload"]}),onFilesAdded:a=>{a.length>0&&Y(a[0]).then(r=>{e(r)}).catch(r=>{console.error("Error parsing file",r),n.open({type:"error",message:r.message})})}})}function me({propertyKey:e,property:n,onEditClick:a,includeName:r=!0,onPropertyNameChanged:s,propertyTypeView:o}){const{propertyConfigs:i}=h.useCustomizationController(),c=n?h.getFieldConfig(n,i):null;return t.jsx(h.ErrorBoundary,{children:t.jsxs("div",{className:"flex flex-row w-full items-center",children:[t.jsx("div",{className:"mx-4",children:o??t.jsx(h.PropertyConfigBadge,{propertyConfig:c??void 0})}),t.jsx("div",{className:"w-full flex flex-col grow",children:t.jsxs("div",{className:"flex flex-row items-center gap-2",children:[r&&t.jsx(l.TextField,{size:"small",className:"text-base grow",value:n?.name??"",onChange:p=>{s&&e&&s(e,p.target.value)}}),t.jsx(l.IconButton,{onClick:a,size:"small",children:t.jsx(l.EditIcon,{size:"small"})})]})})]})})}function te({path:e,importConfig:n,collection:a,onImportSuccess:r}){console.log("ImportSaveInProgress",e);const s=h.useDataSource(),o=f.useRef(!1),[i,c]=f.useState(0);function p(){o.current||(o.current=!0,ne(s,a,e,n.entities,0,25,c).then(()=>{r(a),o.current=!1}))}return f.useEffect(()=>{p()},[]),t.jsxs(l.CenteredView,{className:"flex flex-col gap-4 items-center",children:[t.jsx(l.CircularProgress,{}),t.jsx(l.Typography,{variant:"h6",children:"Saving data"}),t.jsxs(l.Typography,{variant:"body2",children:[i,"/",n.entities.length," entities saved"]}),t.jsx(l.Typography,{variant:"caption",children:"Do not close this tab or the import will be interrupted."})]})}function ne(e,n,a,r,s=0,o=25,i){console.debug("Saving imported data",s,o);const c=r.slice(s,s+o);return Promise.all(c.map(p=>e.saveEntity({path:a,values:p.values,entityId:p.id,collection:n,status:"new"}))).then(()=>s+o<r.length?(i(s+o),ne(e,n,a,r,s+o,o,i)):(i(r.length),Promise.resolve()))}function be({collection:e,path:n,collectionEntitiesCount:a}){const r=h.useCustomizationController(),s=h.useSnackbarController(),[o,i]=f.useState(!1),[c,p]=f.useState("initial"),d=Q(),g=f.useCallback(()=>{i(!0),p("initial")},[i]),y=f.useCallback(()=>{i(!1)},[i]),x=f.useCallback(()=>{p("preview")},[]),b=f.useCallback(()=>{p("import_data_saving")},[]),T=async u=>{if(d.setImportData(u),u.length>0){const O=await pe.buildEntityPropertiesFromData(u,K);d.setOriginProperties(O);const N=oe(u);d.setHeadersMapping(N);const E=Object.keys(N)?.[0];if(E?.includes("id")||E?.includes("key")){const S=E;d.setIdColumn(S)}}setTimeout(()=>{p("mapping")},100)},D=h.resolveCollection({collection:e,path:n,fields:r.propertyConfigs}),F=h.getPropertiesWithPropertiesOrder(D.properties,D.propertiesOrder),I=Object.entries(F).flatMap(([u,O])=>ae(u,O,0)),_=D.propertiesOrder??Object.keys(D.properties);return e.collectionGroup?null:t.jsxs(t.Fragment,{children:[t.jsx(l.Tooltip,{title:"Import",children:t.jsx(l.IconButton,{color:"primary",onClick:g,children:t.jsx(l.FileUploadIcon,{})})}),t.jsxs(l.Dialog,{open:o,fullWidth:c==="preview",fullHeight:c==="preview",maxWidth:c==="initial"?"lg":"7xl",children:[t.jsxs(l.DialogContent,{className:"flex flex-col gap-4 my-4",fullHeight:c==="preview",children:[c==="initial"&&t.jsxs(t.Fragment,{children:[t.jsx(l.Typography,{variant:"h6",children:"Import data"}),t.jsx(l.Typography,{variant:"body2",children:"Upload a CSV, Excel or JSON file and map it to your existing schema"}),t.jsx(re,{onDataAdded:T})]}),c==="mapping"&&t.jsxs(t.Fragment,{children:[t.jsx(l.Typography,{variant:"h6",children:"Map fields"}),t.jsx(ee,{headersMapping:d.headersMapping,idColumn:d.idColumn,originProperties:d.originProperties,destinationProperties:F,onIdPropertyChanged:u=>d.setIdColumn(u),buildPropertyView:({isIdColumn:u,property:O,propertyKey:N,importKey:E})=>t.jsx(ue,{selectedPropertyKey:N??"",properties:F,propertiesAndLevel:I,isIdColumn:u,onIdSelected:()=>{d.setIdColumn(E)},onPropertySelected:S=>{const z=Object.entries(d.headersMapping).map(([C,A])=>A===S?{[C]:null}:C===E?{[C]:S}:{[C]:A}).reduce((C,A)=>({...C,...A}),{});d.setHeadersMapping(z),S===d.idColumn&&d.setIdColumn(void 0)}})})]}),c==="preview"&&t.jsx(xe,{importConfig:d,properties:F,propertiesOrder:_}),c==="import_data_saving"&&d&&t.jsx(te,{importConfig:d,collection:e,path:n,onImportSuccess:u=>{y(),s.open({type:"info",message:"Data imported successfully"})}})]}),t.jsxs(l.DialogActions,{children:[c==="mapping"&&t.jsx(l.Button,{onClick:()=>p("initial"),variant:"text",children:"Back"}),c==="preview"&&t.jsx(l.Button,{onClick:()=>p("mapping"),variant:"text",children:"Back"}),t.jsx(l.Button,{onClick:y,variant:"text",children:"Cancel"}),c==="mapping"&&t.jsx(l.Button,{variant:"filled",onClick:x,children:"Next"}),c==="preview"&&t.jsx(l.Button,{variant:"filled",onClick:b,children:"Save data"})]})]})]})}const M="__internal_id__";function ue({selectedPropertyKey:e,properties:n,onPropertySelected:a,onIdSelected:r,propertiesAndLevel:s,isIdColumn:o}){const i=e?h.getPropertyInPath(n,e):null,c=f.useCallback(d=>d===M?t.jsx(l.Typography,{variant:"body2",className:"p-4",children:"Use this column as ID"}):!d||!i?t.jsx(l.Typography,{variant:"body2",className:"p-4",children:"Do not import this property"}):t.jsx(se,{propertyKey:d,property:i}),[i]),p=f.useCallback(d=>{d===M?(r(),a(null)):a(d===""?null:d)},[]);return t.jsxs(l.Select,{value:o?M:e??void 0,onValueChange:p,renderValue:c,children:[t.jsx(l.SelectItem,{value:"",children:t.jsx(l.Typography,{variant:"body2",className:"p-4",children:"Do not import this property"})}),t.jsx(l.SelectItem,{value:M,children:t.jsx(l.Typography,{variant:"body2",className:"p-4",children:"Use this column as ID"})}),s.map(({property:d,level:g,propertyKey:y})=>t.jsx(l.SelectItem,{value:y,disabled:d.dataType==="map",children:t.jsx(se,{propertyKey:y,property:d,level:g})},y))]})}function ae(e,n,a){const r=[];return r.push({property:n,level:a,propertyKey:e}),n.dataType==="map"&&n.properties&&Object.entries(n.properties).forEach(([s,o])=>{r.push(...ae(`${e}.${s}`,o,a+1))}),r}function se({propertyKey:e,property:n,level:a=0}){const{propertyConfigs:r}=h.useCustomizationController(),s=h.getFieldConfig(n,r);return t.jsxs("div",{className:"flex flex-row w-full text-start items-center h-full",children:[new Array(a).fill(0).map((o,i)=>t.jsx("div",{className:l.cn(l.defaultBorderMixin,"ml-8 border-l h-12")},i)),t.jsx("div",{className:"m-4",children:t.jsx(l.Tooltip,{title:s?.name,children:t.jsx(h.PropertyConfigBadge,{propertyConfig:s})})}),t.jsxs("div",{className:"flex flex-col flex-grow p-2 pl-2",children:[t.jsx(l.Typography,{variant:"body1",component:"span",className:"flex-grow pr-2",children:n.name?n.name:" "}),t.jsx(l.Typography,{className:" pr-2",variant:"body2",component:"span",color:"secondary",children:e})]})]})}function xe({importConfig:e,properties:n,propertiesOrder:a}){f.useEffect(()=>{const s=R(e.originProperties,n),o=e.importData.map(i=>Z(i,e.idColumn,e.headersMapping,n,s,"TEMP_PATH"));e.setEntities(o)},[]);const r=h.useSelectionController();return t.jsx(h.EntityCollectionTable,{title:t.jsxs("div",{children:[t.jsx(l.Typography,{variant:"subtitle2",children:"Imported data preview"}),t.jsx(l.Typography,{variant:"caption",children:"Entities with the same id will be overwritten"})]}),tableController:{data:e.entities,dataLoading:!1,noMoreToLoad:!1},endAdornment:t.jsx("div",{className:"h-12"}),filterable:!1,sortable:!1,selectionController:r,displayedColumnIds:a.map(s=>({key:s,disabled:!1})),properties:n})}function oe(e){const n={};return e.filter(Boolean).forEach(a=>{Object.keys(a).forEach(r=>{const s=a[r];typeof s=="object"&&!Array.isArray(s)&&Object.entries(oe([s])).forEach(([o,i])=>{n[`${r}.${o}`]=`${r}.${i}`}),n[r]=r})}),n}function Ce(e,n,a,r,s,o,i){console.debug("Downloading export",{dataLength:e.length,collection:a,exportType:o,dateExportType:i});const c=a.properties;if(o==="csv"){const p=r?h.getArrayValuesCount(e.map(b=>b.values)):{},d=we(c,s,p),g=ve(e,n,c,d,i),y=le(d.map(b=>b.label)),x=g.map(b=>le(b));ie([y,...x],`${a.name}.csv`,"text/csv")}else{const p=Se(e,n,c,i),d=JSON.stringify(p,null,2);ie([d],`${a.name}.json`,"application/json")}}function ve(e,n,a,r,s){const o=e.map(i=>({id:i.id,...U(i.values,a,"csv",s)}));return n&&n.forEach((i,c)=>{o[c]={...o[c],...i}}),o&&o.map(i=>r.map(c=>h.getValueInPath(i,c.key)))}function Se(e,n,a,r){const s=e.map(o=>({id:o.id,...U(o.values,a,"json",r)}));return n&&n.forEach((o,i)=>{s[i]={...s[i],...o}}),s}function we(e,n,a){const r=[{label:"id",key:"id"},...Object.entries(e).flatMap(([s,o])=>a&&a[s]>1?Array.from({length:a[s]},(i,c)=>H(o,`${s}[${c}]`,"")).flat():H(o,s,""))];return n&&r.push(...n.map(s=>({label:s,key:s}))),r}function H(e,n,a=""){const r=a?`${a}.${n}`:n;return e.dataType==="map"&&e.properties?Object.entries(e.properties).map(([s,o])=>H(o,s,r)).flat():[{label:r,key:r}]}function B(e,n,a,r){let s;if(n.dataType==="map"&&n.properties)s=U(e,n.properties,a,r);else if(n.dataType==="array")n.of&&Array.isArray(e)?Array.isArray(n.of)?s=n.of.map((o,i)=>B(e[i],o,a,r)):n.of.dataType==="map"?s=a==="csv"?e.map(o=>JSON.stringify(o)):e.map(o=>B(o,n.of,a,r)):s=e.map(o=>B(o,n.of,a,r)):s=e;else if(n.dataType==="reference"&&e.isEntityReference&&e.isEntityReference()){const o=e||void 0;s=o?o.pathWithId:null}else n.dataType==="date"&&e instanceof Date?s=e?r==="timestamp"?e.getTime():e.toISOString():null:s=e;return s}function U(e,n,a,r){const s=Object.entries(n).map(([o,i])=>{const c=e&&e[o],p=B(c,i,a,r);return p===void 0?{}:{[o]:p}}).reduce((o,i)=>({...o,...i}),{});return{...e,...s}}function le(e){return e.map(n=>n==null?"":Array.isArray(n)?'"'+JSON.stringify(n).replaceAll('"','\\"')+'"':'"'+String(n).replaceAll('"','""')+'"').join(",")+`\r
2
- `}function ie(e,n,a){const r=new Blob(e,{type:a}),s=URL.createObjectURL(r),o=document.createElement("a");o.href=s,o.setAttribute("download",n),o.click()}const Te=500;function De({collection:e,path:n,collectionEntitiesCount:a,exportAllowed:r,notAllowedView:s}){const o=h.useCustomizationController(),i=typeof e.exportable=="object"?e.exportable:void 0,c=f.useRef(new Date),[p,d]=f.useState(!0),[g,y]=f.useState("csv"),[x,b]=f.useState("string"),T=h.useFireCMSContext(),D=h.useDataSource(),I=h.useNavigationController().resolveAliasesFrom(n),_=!r||r({collectionEntitiesCount:a,path:I,collection:e}),u=f.useMemo(()=>h.resolveCollection({collection:e,path:I,fields:o.propertyConfigs}),[e,I]),[O,N]=f.useState(!1),[E,S]=f.useState(),[z,C]=f.useState(!1),A=f.useCallback(()=>{C(!0)},[C]),q=f.useCallback(()=>{C(!1)},[C]),ce=f.useCallback(async k=>{const $=i?.additionalFields,w=u.additionalFields,V=$?await Promise.all(k.map(async P=>(await Promise.all($.map(async v=>({[v.key]:await v.builder({entity:P,context:T})})))).reduce((v,X)=>({...v,...X}),{}))):[],W=w?await Promise.all(k.map(async P=>(await Promise.all(w.map(async v=>v.value?{[v.key]:await v.value({entity:P,context:T})}:{}))).reduce((v,X)=>({...v,...X}),{}))):[];return[...V,...W]},[i?.additionalFields]),de=f.useCallback(async(k,$)=>{N(!0),D.fetchCollection({path:I,collection:k}).then(async w=>{S(void 0);const V=await ce(w),W=[...$?.additionalFields?.map(P=>P.key)??[],...k.additionalFields?.map(P=>P.key)??[]];Ce(w,V,k,p,W,g,x)}).catch(w=>{console.error("Error loading export data",w),S(w)}).finally(()=>N(!1))},[D,I,ce,p,g,x]),Oe=f.useCallback(()=>{de(u,i),q()},[de,u,i,q]);return t.jsxs(t.Fragment,{children:[t.jsx(l.Tooltip,{title:"Export",children:t.jsx(l.IconButton,{color:"primary",onClick:A,children:t.jsx(l.GetAppIcon,{})})}),t.jsxs(l.Dialog,{open:z,onOpenChange:C,maxWidth:"xl",children:[t.jsxs(l.DialogContent,{className:"flex flex-col gap-4 my-4",children:[t.jsx(l.Typography,{variant:"h6",children:"Export data"}),t.jsx("div",{children:"Download the the content of this table as a CSV"}),a>Te&&t.jsx(l.Alert,{color:"warning",children:t.jsxs("div",{children:["This collections has a large number of documents (",a,")."]})}),t.jsxs("div",{className:"flex flex-row gap-4",children:[t.jsxs("div",{className:"p-4 flex flex-col",children:[t.jsxs("div",{className:"flex items-center",children:[t.jsx("input",{id:"radio-csv",type:"radio",value:"csv",name:"exportType",checked:g==="csv",onChange:()=>y("csv"),className:l.cn(l.focusedMixin,"w-4 text-primary-dark bg-gray-100 border-gray-300 dark:bg-gray-700 dark:border-gray-600")}),t.jsx("label",{htmlFor:"radio-csv",className:"p-2 text-sm font-medium text-gray-900 dark:text-gray-300",children:"CSV"})]}),t.jsxs("div",{className:"flex items-center",children:[t.jsx("input",{id:"radio-json",type:"radio",value:"json",name:"exportType",checked:g==="json",onChange:()=>y("json"),className:l.cn(l.focusedMixin,"w-4 text-primary-dark bg-gray-100 border-gray-300 dark:bg-gray-700 dark:border-gray-600")}),t.jsx("label",{htmlFor:"radio-json",className:"p-2 text-sm font-medium text-gray-900 dark:text-gray-300",children:"JSON"})]})]}),t.jsxs("div",{className:"p-4 flex flex-col",children:[t.jsxs("div",{className:"flex items-center",children:[t.jsx("input",{id:"radio-timestamp",type:"radio",value:"timestamp",name:"dateExportType",checked:x==="timestamp",onChange:()=>b("timestamp"),className:l.cn(l.focusedMixin,"w-4 text-primary-dark bg-gray-100 border-gray-300 dark:bg-gray-700 dark:border-gray-600")}),t.jsxs("label",{htmlFor:"radio-timestamp",className:"p-2 text-sm font-medium text-gray-900 dark:text-gray-300",children:["Dates as timestamps (",c.current.getTime(),")"]})]}),t.jsxs("div",{className:"flex items-center",children:[t.jsx("input",{id:"radio-string",type:"radio",value:"string",name:"dateExportType",checked:x==="string",onChange:()=>b("string"),className:l.cn(l.focusedMixin,"w-4 text-primary-dark bg-gray-100 border-gray-300 dark:bg-gray-700 dark:border-gray-600")}),t.jsxs("label",{htmlFor:"radio-string",className:"p-2 text-sm font-medium text-gray-900 dark:text-gray-300",children:["Dates as strings (",c.current.toISOString(),")"]})]})]})]}),t.jsx(l.BooleanSwitchWithLabel,{size:"small",disabled:g!=="csv",value:p,onValueChange:d,label:"Flatten arrays"}),!_&&s]}),t.jsxs(l.DialogActions,{children:[O&&t.jsx(l.CircularProgress,{size:"small"}),t.jsx(l.Button,{onClick:q,variant:"text",children:"Cancel"}),t.jsx(l.Button,{variant:"filled",onClick:Oe,disabled:O||!_,children:"Download"})]})]})]})}function Ie(e){return f.useMemo(()=>({name:"Import/Export",collections:{CollectionActions:[be,De],collectionActionsProps:e}}),[e])}m.DataNewPropertiesMapping=ee,m.ImportFileUpload=re,m.ImportNewPropertyFieldPreview=me,m.ImportSaveInProgress=te,m.convertDataToEntity=Z,m.convertFileToJson=Y,m.flattenEntry=J,m.getInferenceType=K,m.getPropertiesMapping=R,m.processValueMapping=j,m.unflattenObject=L,m.useImportConfig=Q,m.useImportExportPlugin=Ie,Object.defineProperty(m,Symbol.toStringTag,{value:"Module"})});
1
+ (function(m,g){typeof exports=="object"&&typeof module<"u"?g(exports,require("react"),require("react/jsx-runtime"),require("@firecms/core"),require("@firecms/ui"),require("@firecms/schema_inference"),require("xlsx")):typeof define=="function"&&define.amd?define(["exports","react","react/jsx-runtime","@firecms/core","@firecms/ui","@firecms/schema_inference","xlsx"],g):(m=typeof globalThis<"u"?globalThis:m||self,g(m["FireCMS data import/export"]={},m.React,m.jsxRuntime,m.core,m.ui,m.schema_inference,m.XLSX))})(this,function(m,g,r,h,l,pe,fe){"use strict";function ge(e){const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const a in e)if(a!=="default"){const t=Object.getOwnPropertyDescriptor(e,a);Object.defineProperty(n,a,t.get?t:{enumerable:!0,get:()=>e[a]})}}return n.default=e,Object.freeze(n)}const G=ge(fe),Q=()=>{const[e,n]=g.useState(!1),[a,t]=g.useState(),[s,o]=g.useState([]),[i,p]=g.useState([]),[d,c]=g.useState({}),[f,y]=g.useState({});return{inUse:e,setInUse:n,idColumn:a,setIdColumn:t,entities:i,setEntities:p,importData:s,setImportData:o,headersMapping:d,setHeadersMapping:c,originProperties:f,setOriginProperties:y}};function Y(e){return new Promise((n,a)=>{if(e.type==="application/json"){console.debug("Converting JSON file to JSON",e.name);const t=new FileReader;t.onload=function(s){const o=s.target?.result,i=JSON.parse(o);Array.isArray(i)||a(new Error("JSON file should contain an array of objects")),n(i)},t.readAsText(e)}else{console.debug("Converting Excel file to JSON",e.name);const t=new FileReader;t.onload=function(s){const o=new Uint8Array(s.target?.result),i=G.read(o,{type:"array",codepage:65001,cellDates:!0}),p=i.SheetNames[0],d=i.Sheets[p],y=G.utils.sheet_to_json(d).map(he).map(H);n(y)},t.readAsArrayBuffer(e)}})}function he(e){return Object.keys(e).reduce((n,a)=>{try{n[a]=JSON.parse(e[a])}catch{n[a]=e[a]}return n},{})}function H(e){return Object.keys(e).reduce((n,a)=>{let t=n;const s=a.split(".");return s.forEach((o,i)=>{if(/^[\w]+\[\d+\]$/.test(o)){const p=o.slice(0,o.indexOf("[")),d=parseInt(o.slice(o.indexOf("[")+1,o.indexOf("]")));t[p]||(t[p]=[]),i!==s.length-1?(t[p][d]=t[p][d]||{},t=t[p][d]):t[p][d]=e[a]}else i!==s.length-1?(t[o]=t[o]||{},t=t[o]):t[o]=e[a]}),n},{})}function Z(e,n,a,t,s,o){const i=U(e);n&&delete i[n];const p=Object.entries(i).map(([f,y])=>{const b=a[f]??f;if(!h.getPropertyInPath(t,b))return{};const I=s[b];let O=y;return I&&(O=_(y,I)),{[b]:O}}).reduce((f,y)=>({...f,...y}),{}),d=H(p);let c=n?e[n]:void 0;return typeof c=="string"?c=c.trim():typeof c=="number"||typeof c=="boolean"?c=c.toString():c instanceof Date?c=c.toISOString():c&&"toString"in c&&(c=c.toString()),{id:c,values:d,path:o}}function U(e,n=""){return Object.keys(e).reduce((a,t)=>{const s=n?`${n}.${t}`:t;return typeof e[t]=="object"&&e[t]!==null&&!Array.isArray(e[t])?Object.assign(a,U(e[t],s)):a[s]=e[t],a},{})}function _(e,n){if(n===void 0)return e;const{from:a,to:t}=n;if(a==="array"&&t==="array"&&n.fromSubtype&&n.toSubtype&&Array.isArray(e))return e.map(s=>_(s,{from:n.fromSubtype,to:n.toSubtype}));if(a==="string"&&t==="number"&&typeof e=="string")return Number(e);if(a==="string"&&t==="array"&&n.toSubtype&&typeof e=="string")return e.split(",").map(s=>_(s,{from:"string",to:n.toSubtype}));if(a==="string"&&t==="boolean")return e==="true";if(a==="number"&&t==="boolean")return e===1;if(a==="boolean"&&t==="number")return e?1:0;if(a==="boolean"&&t==="string")return e?"true":"false";if(a==="number"&&t==="string"&&typeof e=="number")return e.toString();if(a==="string"&&t==="array"&&typeof e=="string")return e.split(",").map(s=>s.trim());if(a==="string"&&t==="date"&&typeof e=="string")try{return new Date(e)}catch{return e}else{if(a==="date"&&t==="string")return e instanceof Date&&e.toISOString();if(a==="number"&&t==="date"&&typeof e=="number")try{return new Date(e)}catch{return e}else if(a==="string"&&t==="reference"&&typeof e=="string"){const s=e.split("/").slice(0,-1).join("/"),o=e.split("/").slice(-1)[0];return new h.EntityReference(o,s)}else{if(a===t)return e;if(a==="array"&&t==="string"&&Array.isArray(e))return e.join(",")}}return e}function K(e){return typeof e=="number"?"number":typeof e=="string"?"string":typeof e=="boolean"?"boolean":e instanceof Date?"date":Array.isArray(e)?"array":"map"}function R(e,n){function a(t,s){const o={};return Object.keys(t).forEach(i=>{const p=s?`${s}.${i}`:i,d=h.getPropertyInPath(t,i),c=h.getPropertyInPath(e,p);if(d){if(d.dataType==="map"&&d.properties){const f=a(d.properties,p);Object.keys(f).forEach(y=>{o[`${p}.${y}`]=f[y]});return}if(c){const f=c.dataType,y=d.dataType;let b,u;d.dataType==="array"&&d.of&&(u=d.of.dataType),c?.dataType==="array"&&c?.of&&(b=c.of.dataType),(f!==y||b!==u)&&(o[i]={from:f,to:y,fromSubtype:b,toSubtype:u})}}}),o}return a(n)}function ee({idColumn:e,headersMapping:n,originProperties:a,destinationProperties:t,onIdPropertyChanged:s,buildPropertyView:o}){return r.jsxs(r.Fragment,{children:[r.jsx(ye,{idColumn:e,headersMapping:n,onChange:s}),r.jsxs(l.Table,{style:{tableLayout:"fixed"},children:[r.jsxs(l.TableHeader,{children:[r.jsx(l.TableCell,{header:!0,style:{width:"20%"},children:"Column in file"}),r.jsx(l.TableCell,{header:!0}),r.jsx(l.TableCell,{header:!0,style:{width:"75%"},children:"Property"})]}),r.jsx(l.TableBody,{children:t&&Object.entries(n).map(([i,p])=>{const d=n[i],c=p?h.getPropertyInPath(t,p):null,f=h.getPropertyInPath(a,i),y=f?f.dataType==="array"&&typeof f.of=="object"?`${f.dataType} - ${f.of.dataType}`:f.dataType:void 0;return r.jsxs(l.TableRow,{style:{height:"90px"},children:[r.jsxs(l.TableCell,{style:{width:"20%"},children:[r.jsx(l.Typography,{variant:"body2",children:i}),f&&r.jsx(l.Typography,{variant:"caption",color:"secondary",children:y})]}),r.jsx(l.TableCell,{children:r.jsx(l.ChevronRightIcon,{})}),r.jsx(l.TableCell,{className:i===e?"text-center":void 0,style:{width:"75%"},children:o?.({isIdColumn:i===e,property:c,propertyKey:d,importKey:i})})]},i)})})]})]})}function ye({idColumn:e,headersMapping:n,onChange:a}){return r.jsx("div",{children:r.jsxs(l.Select,{size:"small",value:e??"",onChange:t=>{const s=t.target.value;a(s==="none"?null:s)},renderValue:t=>r.jsx(l.Typography,{variant:"body2",children:t!==""?t:"Autogenerate ID"}),label:"Column that will be used as ID for each document",children:[r.jsx(l.SelectItem,{value:"none",children:"Autogenerate ID"}),Object.entries(n).map(([t,s])=>r.jsx(l.SelectItem,{value:t,children:t},t))]})})}function re({onDataAdded:e}){const n=h.useSnackbarController();return r.jsx(l.FileUpload,{accept:{"text/*":[".csv",".xls",".xlsx"],"application/vnd.ms-excel":[".xls",".xlsx"],"application/msexcel":[".xls",".xlsx"],"application/vnd.ms-office":[".xls",".xlsx"],"application/xls":[".xls",".xlsx"],"application/x-xls":[".xls",".xlsx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":[".xls",".xlsx"],"application/json":[".json"]},preventDropOnDocument:!0,size:"small",maxFiles:1,uploadDescription:r.jsxs(r.Fragment,{children:[r.jsx(l.UploadIcon,{}),"Drag and drop a file here or click to upload"]}),onFilesAdded:a=>{a.length>0&&Y(a[0]).then(t=>{e(t)}).catch(t=>{console.error("Error parsing file",t),n.open({type:"error",message:t.message})})}})}function me({propertyKey:e,property:n,onEditClick:a,includeName:t=!0,onPropertyNameChanged:s,propertyTypeView:o}){const{propertyConfigs:i}=h.useCustomizationController(),p=n?h.getFieldConfig(n,i):null;return r.jsx(h.ErrorBoundary,{children:r.jsxs("div",{className:"flex flex-row w-full items-center",children:[r.jsx("div",{className:"mx-4",children:o??r.jsx(h.PropertyConfigBadge,{propertyConfig:p??void 0})}),r.jsx("div",{className:"w-full flex flex-col grow",children:r.jsxs("div",{className:"flex flex-row items-center gap-2",children:[t&&r.jsx(l.TextField,{size:"small",className:"text-base grow",value:n?.name??"",onChange:d=>{s&&e&&s(e,d.target.value)}}),r.jsx(l.IconButton,{onClick:a,size:"small",children:r.jsx(l.EditIcon,{size:"small"})})]})})]})})}function te({path:e,importConfig:n,collection:a,onImportSuccess:t}){const[s,o]=g.useState(void 0),i=h.useDataSource(),p=g.useRef(!1),[d,c]=g.useState(0);function f(){p.current||(p.current=!0,ne(i,a,e,n.entities,0,25,c).then(()=>{t(a),p.current=!1}).catch(y=>{o(y),p.current=!1}))}return g.useEffect(()=>{f()},[]),s?r.jsxs(l.CenteredView,{className:"flex flex-col gap-4 items-center",children:[r.jsx(l.Typography,{variant:"h6",children:"Error saving data"}),r.jsx(l.Typography,{variant:"body2",color:"error",children:s.message}),r.jsx(l.Button,{onClick:f,variant:"outlined",children:"Retry"})]}):r.jsxs(l.CenteredView,{className:"flex flex-col gap-4 items-center",children:[r.jsx(l.CircularProgress,{}),r.jsx(l.Typography,{variant:"h6",children:"Saving data"}),r.jsxs(l.Typography,{variant:"body2",children:[d,"/",n.entities.length," entities saved"]}),r.jsx(l.Typography,{variant:"caption",children:"Do not close this tab or the import will be interrupted."})]})}function ne(e,n,a,t,s=0,o=25,i){console.debug("Saving imported data",s,o);const p=t.slice(s,s+o);return Promise.all(p.map(d=>e.saveEntity({path:a,values:d.values,entityId:d.id,collection:n,status:"new"}))).then(()=>s+o<t.length?(i(s+o),ne(e,n,a,t,s+o,o,i)):(i(t.length),Promise.resolve()))}function be({collection:e,path:n,collectionEntitiesCount:a,onAnalyticsEvent:t}){const s=h.useCustomizationController(),o=h.useSnackbarController(),[i,p]=g.useState(!1),[d,c]=g.useState("initial"),f=Q(),y=g.useCallback(()=>{p(!0),c("initial")},[p]),b=g.useCallback(()=>{p(!1)},[p]),u=g.useCallback(()=>{c("preview")},[]),I=g.useCallback(()=>{c("import_data_saving")},[]),O=async x=>{if(f.setImportData(x),x.length>0){const N=await pe.buildEntityPropertiesFromData(x,K);f.setOriginProperties(N);const k=oe(x,e?.properties);f.setHeadersMapping(k);const S=Object.keys(k)?.[0];(S?.includes("id")||S?.includes("key"))&&f.setIdColumn(S)}setTimeout(()=>{c("mapping")},100)},F=h.resolveCollection({collection:e,path:n,fields:s.propertyConfigs}),C=h.getPropertiesWithPropertiesOrder(F.properties,F.propertiesOrder),L=Object.entries(C).flatMap(([x,N])=>ae(x,N,0)),j=F.propertiesOrder??Object.keys(F.properties);return e.collectionGroup?null:r.jsxs(r.Fragment,{children:[r.jsx(l.Tooltip,{title:"Import",children:r.jsx(l.IconButton,{color:"primary",onClick:y,children:r.jsx(l.FileUploadIcon,{})})}),r.jsxs(l.Dialog,{open:i,fullWidth:d==="preview",fullHeight:d==="preview",maxWidth:d==="initial"?"lg":"7xl",children:[r.jsxs(l.DialogContent,{className:"flex flex-col gap-4 my-4",fullHeight:d==="preview",children:[d==="initial"&&r.jsxs(r.Fragment,{children:[r.jsx(l.Typography,{variant:"h6",children:"Import data"}),r.jsx(l.Typography,{variant:"body2",children:"Upload a CSV, Excel or JSON file and map it to your existing schema"}),r.jsx(re,{onDataAdded:O})]}),d==="mapping"&&r.jsxs(r.Fragment,{children:[r.jsx(l.Typography,{variant:"h6",children:"Map fields"}),r.jsx(ee,{headersMapping:f.headersMapping,idColumn:f.idColumn,originProperties:f.originProperties,destinationProperties:C,onIdPropertyChanged:x=>f.setIdColumn(x??void 0),buildPropertyView:({isIdColumn:x,property:N,propertyKey:k,importKey:S})=>r.jsx(ue,{selectedPropertyKey:k??"",properties:C,propertiesAndLevel:L,isIdColumn:x,onIdSelected:()=>{f.setIdColumn(S)},onPropertySelected:M=>{const E=Object.entries(f.headersMapping).map(([w,T])=>T===M?{[w]:null}:w===S?{[w]:M}:{[w]:T}).reduce((w,T)=>({...w,...T}),{});f.setHeadersMapping(E),M===f.idColumn&&f.setIdColumn(void 0)}})})]}),d==="preview"&&r.jsx(xe,{importConfig:f,properties:C,propertiesOrder:j}),d==="import_data_saving"&&f&&r.jsx(te,{importConfig:f,collection:e,path:n,onImportSuccess:x=>{b(),o.open({type:"info",message:"Data imported successfully"})}})]}),r.jsxs(l.DialogActions,{children:[d==="mapping"&&r.jsx(l.Button,{onClick:()=>c("initial"),variant:"text",children:"Back"}),d==="preview"&&r.jsx(l.Button,{onClick:()=>c("mapping"),variant:"text",children:"Back"}),r.jsx(l.Button,{onClick:b,variant:"text",children:"Cancel"}),d==="mapping"&&r.jsx(l.Button,{variant:"filled",onClick:u,children:"Next"}),d==="preview"&&r.jsx(l.Button,{variant:"filled",onClick:I,children:"Save data"})]})]})]})}const B="__internal_id__";function ue({selectedPropertyKey:e,properties:n,onPropertySelected:a,onIdSelected:t,propertiesAndLevel:s,isIdColumn:o}){const i=e?h.getPropertyInPath(n,e):null,p=g.useCallback(c=>c===B?r.jsx(l.Typography,{variant:"body2",className:"p-4",children:"Use this column as ID"}):!c||!i?r.jsx(l.Typography,{variant:"body2",className:"p-4",children:"Do not import this property"}):r.jsx(se,{propertyKey:c,property:i}),[i]),d=g.useCallback(c=>{c===B?(t(),a(null)):a(c==="__do_not_import"?null:c)},[]);return r.jsxs(l.Select,{value:o?B:e??void 0,onValueChange:d,renderValue:p,children:[r.jsx(l.SelectItem,{value:"__do_not_import",children:r.jsx(l.Typography,{variant:"body2",className:"p-4",children:"Do not import this property"})}),r.jsx(l.SelectItem,{value:B,children:r.jsx(l.Typography,{variant:"body2",className:"p-4",children:"Use this column as ID"})}),s.map(({property:c,level:f,propertyKey:y})=>r.jsx(l.SelectItem,{value:y,disabled:c.dataType==="map",children:r.jsx(se,{propertyKey:y,property:c,level:f})},y))]})}function ae(e,n,a){const t=[];return t.push({property:n,level:a,propertyKey:e}),n.dataType==="map"&&n.properties&&Object.entries(n.properties).forEach(([s,o])=>{t.push(...ae(`${e}.${s}`,o,a+1))}),t}function se({propertyKey:e,property:n,level:a=0}){const{propertyConfigs:t}=h.useCustomizationController(),s=h.getFieldConfig(n,t);return r.jsxs("div",{className:"flex flex-row w-full text-start items-center h-full",children:[new Array(a).fill(0).map((o,i)=>r.jsx("div",{className:l.cn(l.defaultBorderMixin,"ml-8 border-l h-12")},i)),r.jsx("div",{className:"m-4",children:r.jsx(l.Tooltip,{title:s?.name,children:r.jsx(h.PropertyConfigBadge,{propertyConfig:s})})}),r.jsxs("div",{className:"flex flex-col flex-grow p-2 pl-2",children:[r.jsx(l.Typography,{variant:"body1",component:"span",className:"flex-grow pr-2",children:n.name?n.name:" "}),r.jsx(l.Typography,{className:" pr-2",variant:"body2",component:"span",color:"secondary",children:e})]})]})}function xe({importConfig:e,properties:n,propertiesOrder:a}){g.useEffect(()=>{const s=R(e.originProperties,n),o=e.importData.map(i=>Z(i,e.idColumn,e.headersMapping,n,s,"TEMP_PATH"));e.setEntities(o)},[]);const t=h.useSelectionController();return r.jsx(h.EntityCollectionTable,{title:r.jsxs("div",{children:[r.jsx(l.Typography,{variant:"subtitle2",children:"Imported data preview"}),r.jsx(l.Typography,{variant:"caption",children:"Entities with the same id will be overwritten"})]}),tableController:{data:e.entities,dataLoading:!1,noMoreToLoad:!1},endAdornment:r.jsx("div",{className:"h-12"}),filterable:!1,sortable:!1,selectionController:t,displayedColumnIds:a.map(s=>({key:s,disabled:!1})),properties:n})}function oe(e,n){const a={};return e.filter(Boolean).forEach(t=>{Object.keys(t).forEach(s=>{const o=t[s];if(typeof o=="object"&&!Array.isArray(o)){const i=n?.[s],p=i&&"properties"in i?i.properties:void 0,d=oe([o],p);Object.entries(d).forEach(([c,f])=>{a[`${s}.${c}`]=`${s}.${f}`})}if(!n)a[s]=s;else if(s in n)a[s]=s;else{const i=h.slugify(s);i in n?a[s]=i:a[s]=s}})}),a}function Ce(e,n,a,t,s,o,i){console.debug("Downloading export",{dataLength:e.length,collection:a,exportType:o,dateExportType:i});const p=a.properties;if(o==="csv"){const d=t?h.getArrayValuesCount(e.map(u=>u.values)):{},c=we(p,s,d),f=ve(e,n,p,c,i),y=le(c.map(u=>u.label)),b=f.map(u=>le(u));ie([y,...b],`${a.name}.csv`,"text/csv")}else{const d=Se(e,n,p,i),c=JSON.stringify(d,null,2);ie([c],`${a.name}.json`,"application/json")}}function ve(e,n,a,t,s){const o=e.map(i=>({id:i.id,...V(i.values,a,"csv",s)}));return n&&n.forEach((i,p)=>{o[p]={...o[p],...i}}),o&&o.map(i=>t.map(p=>h.getValueInPath(i,p.key)))}function Se(e,n,a,t){const s=e.map(o=>({id:o.id,...V(o.values,a,"json",t)}));return n&&n.forEach((o,i)=>{s[i]={...s[i],...o}}),s}function we(e,n,a){const t=[{label:"id",key:"id"},...Object.entries(e).flatMap(([s,o])=>a&&a[s]>1?Array.from({length:a[s]},(i,p)=>z(o,`${s}[${p}]`,"")).flat():z(o,s,""))];return n&&t.push(...n.map(s=>({label:s,key:s}))),t}function z(e,n,a=""){const t=a?`${a}.${n}`:n;return e.dataType==="map"&&e.properties?Object.entries(e.properties).map(([s,o])=>z(o,s,t)).flat():[{label:t,key:t}]}function $(e,n,a,t){let s;if(n.dataType==="map"&&n.properties)s=V(e,n.properties,a,t);else if(n.dataType==="array")n.of&&Array.isArray(e)?Array.isArray(n.of)?s=n.of.map((o,i)=>$(e[i],o,a,t)):n.of.dataType==="map"?s=a==="csv"?e.map(o=>JSON.stringify(o)):e.map(o=>$(o,n.of,a,t)):s=e.map(o=>$(o,n.of,a,t)):s=e;else if(n.dataType==="reference"&&e&&e.isEntityReference&&e.isEntityReference()){const o=e||void 0;s=o?o.pathWithId:null}else n.dataType==="date"&&e instanceof Date?s=e?t==="timestamp"?e.getTime():e.toISOString():null:s=e;return s}function V(e,n,a,t){const s=Object.entries(n).map(([o,i])=>{const p=e&&e[o],d=$(p,i,a,t);return d===void 0?{}:{[o]:d}}).reduce((o,i)=>({...o,...i}),{});return{...e,...s}}function le(e){return e.map(n=>n==null?"":Array.isArray(n)?'"'+JSON.stringify(n).replaceAll('"','\\"')+'"':'"'+String(n).replaceAll('"','""')+'"').join(",")+`\r
2
+ `}function ie(e,n,a){const t=new Blob(e,{type:a}),s=URL.createObjectURL(t),o=document.createElement("a");o.href=s,o.setAttribute("download",n),o.click()}const Te=500;function De({collection:e,path:n,collectionEntitiesCount:a,exportAllowed:t,notAllowedView:s}){const o=h.useCustomizationController(),i=typeof e.exportable=="object"?e.exportable:void 0,p=g.useRef(new Date),[d,c]=g.useState(!0),[f,y]=g.useState("csv"),[b,u]=g.useState("string"),I=h.useFireCMSContext(),O=h.useDataSource(),C=h.useNavigationController().resolveAliasesFrom(n),L=!t||t({collectionEntitiesCount:a,path:C,collection:e}),j=g.useMemo(()=>h.resolveCollection({collection:e,path:C,fields:o.propertyConfigs}),[e,C]),[x,N]=g.useState(!1),[k,S]=g.useState(),[M,E]=g.useState(!1),w=g.useCallback(()=>{E(!0)},[E]),T=g.useCallback(()=>{E(!1)},[E]),ce=g.useCallback(async A=>{const J=i?.additionalFields,D=j.additionalFields,q=J?await Promise.all(A.map(async P=>(await Promise.all(J.map(async v=>({[v.key]:await v.builder({entity:P,context:I})})))).reduce((v,X)=>({...v,...X}),{}))):[],W=D?await Promise.all(A.map(async P=>(await Promise.all(D.map(async v=>v.value?{[v.key]:await v.value({entity:P,context:I})}:{}))).reduce((v,X)=>({...v,...X}),{}))):[];return[...q,...W]},[i?.additionalFields]),de=g.useCallback(async(A,J)=>{N(!0),O.fetchCollection({path:C,collection:A}).then(async D=>{S(void 0);const q=await ce(D),W=[...J?.additionalFields?.map(P=>P.key)??[],...A.additionalFields?.map(P=>P.key)??[]];Ce(D,q,A,d,W,f,b)}).catch(D=>{console.error("Error loading export data",D),S(D)}).finally(()=>N(!1))},[O,C,ce,d,f,b]),Oe=g.useCallback(()=>{de(j,i),T()},[de,j,i,T]);return r.jsxs(r.Fragment,{children:[r.jsx(l.Tooltip,{title:"Export",children:r.jsx(l.IconButton,{color:"primary",onClick:w,children:r.jsx(l.GetAppIcon,{})})}),r.jsxs(l.Dialog,{open:M,onOpenChange:E,maxWidth:"xl",children:[r.jsxs(l.DialogContent,{className:"flex flex-col gap-4 my-4",children:[r.jsx(l.Typography,{variant:"h6",children:"Export data"}),r.jsx("div",{children:"Download the the content of this table as a CSV"}),a>Te&&r.jsx(l.Alert,{color:"warning",children:r.jsxs("div",{children:["This collections has a large number of documents (",a,")."]})}),r.jsxs("div",{className:"flex flex-row gap-4",children:[r.jsxs("div",{className:"p-4 flex flex-col",children:[r.jsxs("div",{className:"flex items-center",children:[r.jsx("input",{id:"radio-csv",type:"radio",value:"csv",name:"exportType",checked:f==="csv",onChange:()=>y("csv"),className:l.cn(l.focusedMixin,"w-4 text-primary-dark bg-gray-100 border-gray-300 dark:bg-gray-700 dark:border-gray-600")}),r.jsx("label",{htmlFor:"radio-csv",className:"p-2 text-sm font-medium text-gray-900 dark:text-slate-300",children:"CSV"})]}),r.jsxs("div",{className:"flex items-center",children:[r.jsx("input",{id:"radio-json",type:"radio",value:"json",name:"exportType",checked:f==="json",onChange:()=>y("json"),className:l.cn(l.focusedMixin,"w-4 text-primary-dark bg-gray-100 border-gray-300 dark:bg-gray-700 dark:border-gray-600")}),r.jsx("label",{htmlFor:"radio-json",className:"p-2 text-sm font-medium text-gray-900 dark:text-slate-300",children:"JSON"})]})]}),r.jsxs("div",{className:"p-4 flex flex-col",children:[r.jsxs("div",{className:"flex items-center",children:[r.jsx("input",{id:"radio-timestamp",type:"radio",value:"timestamp",name:"dateExportType",checked:b==="timestamp",onChange:()=>u("timestamp"),className:l.cn(l.focusedMixin,"w-4 text-primary-dark bg-gray-100 border-gray-300 dark:bg-gray-700 dark:border-gray-600")}),r.jsxs("label",{htmlFor:"radio-timestamp",className:"p-2 text-sm font-medium text-gray-900 dark:text-slate-300",children:["Dates as timestamps (",p.current.getTime(),")"]})]}),r.jsxs("div",{className:"flex items-center",children:[r.jsx("input",{id:"radio-string",type:"radio",value:"string",name:"dateExportType",checked:b==="string",onChange:()=>u("string"),className:l.cn(l.focusedMixin,"w-4 text-primary-dark bg-gray-100 border-gray-300 dark:bg-gray-700 dark:border-gray-600")}),r.jsxs("label",{htmlFor:"radio-string",className:"p-2 text-sm font-medium text-gray-900 dark:text-slate-300",children:["Dates as strings (",p.current.toISOString(),")"]})]})]})]}),r.jsx(l.BooleanSwitchWithLabel,{size:"small",disabled:f!=="csv",value:d,onValueChange:c,label:"Flatten arrays"}),!L&&s]}),r.jsxs(l.DialogActions,{children:[x&&r.jsx(l.CircularProgress,{size:"small"}),r.jsx(l.Button,{onClick:T,variant:"text",children:"Cancel"}),r.jsx(l.Button,{variant:"filled",onClick:Oe,disabled:x||!L,children:"Download"})]})]})]})}function Ie(e){return g.useMemo(()=>({name:"Import/Export",collectionView:{CollectionActions:[be,De],collectionActionsProps:e}}),[e])}m.DataNewPropertiesMapping=ee,m.ImportFileUpload=re,m.ImportNewPropertyFieldPreview=me,m.ImportSaveInProgress=te,m.convertDataToEntity=Z,m.convertFileToJson=Y,m.flattenEntry=U,m.getInferenceType=K,m.getPropertiesMapping=R,m.processValueMapping=_,m.unflattenObject=H,m.useImportConfig=Q,m.useImportExportPlugin=Ie,Object.defineProperty(m,Symbol.toStringTag,{value:"Module"})});
3
3
  //# sourceMappingURL=index.umd.js.map