UNPKG

react-forminate

Version:

React.js + Typescript package that creates dynamic UI forms based on the JSON schema

2 lines (1 loc) 2.78 kB
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("./index-BHL74Jf6.cjs"),u=require("react"),E=e=>e instanceof File,A=e=>!!e&&typeof e=="object"&&"name"in e,h=({file:e,previewUrl:y,storageFormat:d,onRemove:s})=>{if(!e)return null;const j=()=>{if(d==="blobUrl"||d==="base64"){const c=y||(typeof e=="string"?e:null);return c?r.jsxRuntimeExports.jsx("img",{src:c,alt:"File preview"}):null}return E(e)?r.jsxRuntimeExports.jsx("span",{children:e.name}):A(e)?r.jsxRuntimeExports.jsx("span",{children:e.name}):typeof e=="string"?r.jsxRuntimeExports.jsx("span",{children:e}):null};return r.jsxRuntimeExports.jsxs("div",{className:"file-preview",children:[j(),s&&r.jsxRuntimeExports.jsx("button",{type:"button",onClick:s,className:"remove-file",children:"Remove"})]})},L=e=>{const{eventHandlers:y,fieldParams:d,fieldValue:s=null,isTouched:j,setValue:c}=r.useField(e),i=e.storageFormat||"file",[m,x]=u.useState([]),{htmlHandlers:v,customHandlers:f}=y;u.useEffect(()=>()=>{m.forEach(t=>URL.revokeObjectURL(t))},[m]);const R=u.useCallback(async t=>({file:async()=>t,fileList:async()=>[t],base64:async()=>new Promise(a=>{const l=new FileReader;l.onload=()=>a(l.result),l.readAsDataURL(t)}),blobUrl:async()=>URL.createObjectURL(t),arrayBuffer:async()=>new Promise(a=>{const l=new FileReader;l.onload=()=>a(l.result),l.readAsArrayBuffer(t)}),remoteUrl:async()=>`https://example.com/uploads/${t.name}`,metadata:async()=>({name:t.name,type:t.type,size:t.size,lastModified:t.lastModified})})[i](),[i]),U=u.useCallback(async t=>{if(!t.target.files?.length)return;const n=Array.from(t.target.files),a=await Promise.all(n.map(R));["base64","blobUrl"].includes(i)&&x(n.map(o=>URL.createObjectURL(o)));const l=i==="fileList"?t.target.files:a.length===1?a[0]:a;c(e.fieldId,l),f?.onUpload?.(a,e.fieldId)},[R,i,c,e.fieldId,f]),p=u.useCallback(t=>{const n=Array.isArray(s),a=n?[s[t]]:[s],l=n?s.filter((o,b)=>b!==t):null;a.forEach(o=>{i==="blobUrl"&&typeof o=="string"&&URL.revokeObjectURL(o)}),c(e.fieldId,l),x(o=>n?o.filter((b,g)=>g!==t):[]),f?.onRemove?.(a[0],e.fieldId)},[s,i,c,e.fieldId,f]),F=u.useMemo(()=>Array.isArray(e.accept)?e.accept.join(","):e.accept,[e.accept]),w=()=>s?Array.isArray(s)?s.map((t,n)=>r.jsxRuntimeExports.jsx(h,{file:t,previewUrl:m[n],storageFormat:i,onRemove:()=>p(n)},`${e.fieldId}-${n}`)):typeof s=="object"&&!Object.keys(s).length?null:r.jsxRuntimeExports.jsx(h,{file:s,previewUrl:m[0],storageFormat:i,onRemove:()=>p()}):null;return r.jsxRuntimeExports.jsxs("div",{className:"file-input-container",children:[r.jsxRuntimeExports.jsx("input",{...d,...v,type:"file",onChange:U,accept:F,multiple:e.multiple,"data-touched":j}),r.jsxRuntimeExports.jsx("div",{className:"file-previews",children:w()})]})},I=u.memo(L);exports.default=I;