@uploadista/react-native-core 0.1.2 → 0.1.3-beta.11
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.d.mts +84 -38
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +5 -5
- package/src/components/flow-primitives.tsx +44 -0
- package/src/components/index.ts +2 -0
- package/src/hooks/use-flow.ts +31 -3
- package/src/index.ts +2 -0
package/dist/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import e,{createContext as t,useCallback as n,useContext as r,useEffect as i,useRef as a,useState as o}from"react";import{ActivityIndicator as s,FlatList as c,Pressable as l,StyleSheet as u,Text as d,View as f}from"react-native";import{FlowManager as p,UploadManager as m}from"@uploadista/client-core";import{EventType as h}from"@uploadista/core/flow";import{UploadEventType as g}from"@uploadista/core/types";import{Fragment as _,jsx as v,jsxs as y}from"react/jsx-runtime";const b=t(void 0);function x(e,t){let n=e instanceof ArrayBuffer?new Uint8Array(e):e;return new Blob([n],t)}function S(){let e=r(b);if(!e)throw Error(`useUploadistaClient must be used within an UploadistaProvider`);return e}const C={status:`idle`,progress:0,bytesUploaded:0,totalBytes:null,error:null,result:null};function w(e={}){let{client:t,fileSystemProvider:r}=S(),[s,c]=o(C),l=a(null),u=a(null);return i(()=>(l.current=new m(async(e,n)=>{let i=e;if(i.status===`success`){let e=x(await r.readFile(i.data.uri),{type:i.data.mimeType||`application/octet-stream`});return t.upload(e,n)}return Promise.resolve({abort:()=>{}})},{onStateChange:c,onProgress:e.onProgress,onChunkComplete:e.onChunkComplete,onSuccess:e.onSuccess,onError:e.onError,onAbort:e.onAbort},{metadata:e.metadata,uploadLengthDeferred:e.uploadLengthDeferred,uploadSize:e.uploadSize,onShouldRetry:e.onShouldRetry}),()=>{l.current?.cleanup()}),[t,r,e]),{state:s,upload:n(async e=>{u.current=e,await l.current?.upload(e)},[]),abort:n(()=>{l.current?.abort()},[]),reset:n(()=>{l.current?.reset(),u.current=null},[]),retry:n(()=>{u.current&&l.current?.canRetry()&&l.current.retry()},[]),isUploading:s.status===`uploading`,canRetry:l.current?.canRetry()??!1,metrics:{getInsights:()=>t.getChunkingInsights(),exportMetrics:()=>t.exportMetrics(),getNetworkMetrics:()=>t.getNetworkMetrics(),getNetworkCondition:()=>t.getNetworkCondition(),resetMetrics:()=>t.resetMetrics()}}}function T(e){let{fileSystemProvider:t}=S(),r=w({metadata:e?.metadata,onSuccess:e?.onSuccess,onError:e?.onError,onProgress:e?.onProgress}),i=n(async()=>{try{let n=await t.pickCamera(e?.cameraOptions);await r.upload(n)}catch(e){console.error(`Camera capture error:`,e)}},[t,e?.cameraOptions,r]);return{...r,captureAndUpload:i}}function E(e){let{fileSystemProvider:t}=S(),r=w({metadata:e?.metadata,onSuccess:e?.onSuccess,onError:e?.onError,onProgress:e?.onProgress}),i=n(async()=>{try{let n=await t.pickDocument({allowedTypes:e?.allowedTypes});await r.upload(n)}catch(e){throw console.error(`File selection error:`,e),e}},[t,e?.allowedTypes,r]);return{...r,pickAndUpload:i}}function ee(e){let t=e;return t.eventType===h.FlowStart||t.eventType===h.FlowEnd||t.eventType===h.FlowError||t.eventType===h.NodeStart||t.eventType===h.NodeEnd||t.eventType===h.NodePause||t.eventType===h.NodeResume||t.eventType===h.NodeError}const D=t(void 0);function te({children:e}){let{client:t,subscribeToEvents:r}=S(),o=a(new Map);i(()=>r(e=>{if(ee(e)){for(let t of o.current.values())t.manager.handleFlowEvent(e);return}if(`type`in e&&e.type===g.UPLOAD_PROGRESS&&`data`in e)for(let t of o.current.values())t.manager.handleUploadProgress(e.data.id,e.data.progress,e.data.total)}),[r]);let s=n((e,n,r)=>{let i=o.current.get(e);if(i)return i.refCount++,i.manager;let a=new p(t.uploadWithFlow,n,r,t.multiInputFlowUpload);return o.current.set(e,{manager:a,refCount:1,flowId:e}),a},[t]),c=n(e=>{let t=o.current.get(e);t&&(t.refCount--,t.refCount<=0&&(t.manager.cleanup(),o.current.delete(e)))},[]);return v(D.Provider,{value:{getManager:s,releaseManager:c},children:e})}function O(){let e=r(D);if(e===void 0)throw Error(`useFlowManagerContext must be used within a FlowManagerProvider. Make sure to wrap your component tree with <FlowManagerProvider>.`);return e}const ne={status:`idle`,progress:0,bytesUploaded:0,totalBytes:null,error:null,jobId:null,flowStarted:!1,currentNodeName:null,currentNodeType:null,flowOutputs:null};function k(e){let{client:t,fileSystemProvider:r}=S(),{getManager:s,releaseManager:c}=O(),[l,u]=o(ne),[d,f]=o(null),[p,m]=o(!1),[h,g]=o({}),[_,v]=o(new Map),y=a(null),b=a(null),C=a(e);i(()=>{C.current=e}),i(()=>{(async()=>{m(!0);try{let{flow:n}=await t.getFlow(e.flowId);f(n.nodes.filter(e=>e.type===`input`).map(e=>({nodeId:e.id,nodeName:e.name,nodeDescription:e.description,inputTypeId:e.inputTypeId,required:!0})))}catch(e){console.error(`Failed to discover flow inputs:`,e)}finally{m(!1)}})()},[t,e.flowId]),i(()=>{let t=e.flowId;y.current=s(t,{onStateChange:e=>{u(e)},onProgress:(e,t,n)=>{if(C.current.onProgress){let e=n?Math.round(t/n*100):0;C.current.onProgress(e,t,n)}},onChunkComplete:(e,t,n)=>{C.current.onChunkComplete?.(e,t,n)},onFlowComplete:e=>{C.current.onFlowComplete?.(e)},onSuccess:e=>{C.current.onSuccess?.(e)},onError:e=>{C.current.onError?.(e)},onAbort:()=>{}},{flowConfig:{flowId:e.flowId,storageId:e.storageId,outputNodeId:e.outputNodeId,metadata:e.metadata},onChunkComplete:e.onChunkComplete,onSuccess:e.onSuccess,onError:e.onError});let n=setInterval(()=>{if(y.current){let e=y.current.getInputStates();e.size>0&&v(new Map(e))}},100);return()=>{clearInterval(n),c(t),y.current=null}},[e.flowId,e.storageId,e.outputNodeId,s,c]);let w=n((e,t)=>{g(n=>({...n,[e]:t}))},[]),T=n(async e=>{if(e.status===`cancelled`)return null;if(e.status===`error`)throw e.error;return x(await r.readFile(e.data.uri),{type:e.data.mimeType||`application/octet-stream`})},[r]),E=n(async()=>{if(!y.current)throw Error(`FlowManager not initialized`);if(Object.keys(h).length===0)throw Error(`No inputs provided. Use setInput() to provide inputs before calling execute()`);b.current={...h};let e={};for(let[t,n]of Object.entries(h))if(n&&typeof n==`object`&&`status`in n&&(n.status===`success`||n.status===`cancelled`||n.status===`error`)){let r=await T(n);r&&(e[t]=r)}else e[t]=n;if(Object.keys(e).length===0)throw Error(`No valid inputs after processing. All files may have been cancelled.`);await y.current.executeFlow(e)},[h,T]);return{state:l,inputMetadata:d,inputStates:_,inputs:h,setInput:w,execute:E,upload:n(async t=>{if(t.status!==`cancelled`){if(t.status===`error`){e.onError?.(t.error);return}if(!y.current)throw Error(`FlowManager not initialized`);if(d&&d.length>0){let e=d[0];e&&(b.current={[e.nodeId]:t})}try{let e=x(await r.readFile(t.data.uri),{type:t.data.mimeType||`application/octet-stream`});if(d&&d.length>0){let n=d[0];if(!n)throw Error(`No input nodes found`);g({[n.nodeId]:t}),await y.current.executeFlow({[n.nodeId]:e})}else await y.current.upload(e)}catch(t){e.onError?.(t)}}},[d,r,e]),abort:n(()=>{y.current?.abort()},[]),reset:n(()=>{y.current?.reset(),g({}),v(new Map),b.current=null},[]),retry:n(()=>{b.current&&(l.status===`error`||l.status===`aborted`)&&(g(b.current),E())},[E,l.status]),isActive:l.status===`uploading`||l.status===`processing`,isUploadingFile:l.status===`uploading`,isProcessing:l.status===`processing`,isDiscoveringInputs:p,canRetry:(l.status===`error`||l.status===`aborted`)&&b.current!==null}}const A={items:[],totalProgress:0,totalUploaded:0,totalBytes:0,activeCount:0,completedCount:0,failedCount:0};function j(e={}){let{client:t}=S(),[r,i]=o(A),s=a(new Map),c=a(0),l=a([]),u=n(()=>`upload-${Date.now()}-${c.current++}`,[]),d=n(e=>{let t=e.reduce((e,t)=>e+t.totalBytes,0),n=e.reduce((e,t)=>e+t.bytesUploaded,0),r=t>0?Math.round(n/t*100):0,a=e.filter(e=>e.status===`uploading`).length,o=e.filter(e=>e.status===`success`).length,s=e.filter(e=>e.status===`error`).length;l.current=e,i(i=>({...i,items:e,totalProgress:r,totalUploaded:n,totalBytes:t,activeCount:a,completedCount:o,failedCount:s}))},[]),f=n(e=>{let t=e.filter(e=>e.status===`success`).map(e=>({id:u(),file:e,status:`idle`,progress:0,bytesUploaded:0,totalBytes:e.data.size,error:null,result:null})),n=[...l.current,...t];return l.current=n,i(e=>{let t=n.reduce((e,t)=>e+t.totalBytes,0);return{...e,items:n,totalBytes:t}}),t.map(e=>e.id)},[u]),p=n(async n=>{try{console.log(`Uploading item:`,n.file.data.name),d(l.current.map(e=>e.id===n.id?{...e,status:`uploading`}:e));let r=await(await fetch(n.file.data.uri)).blob(),i=r;if(n.file.data.mimeType){let e={type:n.file.data.mimeType,lastModified:Date.now()};i=new Blob([r],e)}console.log(`Uploading input:`,i);let a=await t.upload(i,{metadata:e.metadata,onProgress:(e,t,r)=>{let i=r?Math.round(t/r*100):0;d(l.current.map(e=>e.id===n.id?{...e,progress:i,bytesUploaded:t,totalBytes:r||e.totalBytes}:e))},onSuccess:t=>{d(l.current.map(e=>e.id===n.id?{...e,status:`success`,progress:100,result:t,bytesUploaded:t.size||e.totalBytes}:e)),e.onSuccess?.(t),s.current.delete(n.id)},onError:t=>{d(l.current.map(e=>e.id===n.id?{...e,status:`error`,error:t}:e)),e.onError?.(t),s.current.delete(n.id)}});s.current.set(n.id,a)}catch(t){console.error(`Error uploading item:`,t),d(l.current.map(e=>e.id===n.id?{...e,status:`error`,error:t}:e)),e.onError?.(t),s.current.delete(n.id)}},[t,e,d]),m=n(async t=>{let n=e.maxConcurrent||3,r=t?l.current.filter(e=>t.includes(e.id)&&e.status===`idle`):l.current.filter(e=>e.status===`idle`);console.log(`Items to upload:`,r.length,r);for(let e=0;e<r.length;e+=n){let t=r.slice(e,e+n);await Promise.all(t.map(e=>p(e)))}},[e.maxConcurrent,p]),h=n(e=>{let t=s.current.get(e);t&&(t.abort(),s.current.delete(e)),d(l.current.filter(t=>t.id!==e))},[d]),g=n(e=>{let t=s.current.get(e);t&&(t.abort(),s.current.delete(e)),d(l.current.map(t=>t.id===e?{...t,status:`aborted`}:t))},[d]),_=n(()=>{s.current.forEach(e=>{e.abort()}),s.current.clear(),l.current=[],i(A)},[]);return{state:r,addFiles:f,startUploads:m,removeItem:h,abortItem:g,retryItem:n(async e=>{let t=l.current.find(t=>t.id===e);if(t&&(t.status===`error`||t.status===`aborted`)){d(l.current.map(t=>t.id===e?{...t,status:`idle`,progress:0,bytesUploaded:0,error:null}:t));let t=l.current.find(t=>t.id===e);t&&await p(t)}},[p,d]),clear:_}}function M(e){let{fileSystemProvider:t}=S(),r=j({maxConcurrent:3,metadata:e?.metadata,onSuccess:e?.onSuccess,onError:e?.onError}),i=n(async()=>{let n;if(n=e?.mediaType===`video`?await t.pickVideo({allowMultiple:e?.allowMultiple??!0}):(e?.mediaType,await t.pickImage({allowMultiple:e?.allowMultiple??!0})),n.status===`cancelled`)return[];if(n.status===`error`)return console.error(`Gallery selection error:`,n.error),e?.onError?.(n.error),[];let i=r.addFiles([n]);return await r.startUploads(i),i},[t,e?.allowMultiple,e?.mediaType,e?.onError,r]);return{...r,selectAndUpload:i}}function re(){let e=a(null),t=a(0),r=a(0),[i,s]=o({totalBytes:0,durationMs:0,avgSpeed:0,peakSpeed:0,retries:0});return{metrics:i,start:n(()=>{e.current=Date.now(),t.current=0,r.current=0},[]),update:n((t,n,i=0)=>{if(!e.current)return;let a=Date.now()-e.current,o=a>0?t/a*1e3:0;o>r.current&&(r.current=o),s({totalBytes:t,durationMs:a,avgSpeed:a>0?t/a*1e3:0,peakSpeed:r.current,retries:i})},[]),end:n(()=>{let t=i;return e.current=null,t},[i]),reset:n(()=>{e.current=null,t.current=0,r.current=0,s({totalBytes:0,durationMs:0,avgSpeed:0,peakSpeed:0,retries:0})},[])}}function N(e){if(e===0)return`0 Bytes`;let t=1024,n=[`Bytes`,`KB`,`MB`,`GB`],r=Math.floor(Math.log(e)/Math.log(t));return`${Math.round(e/t**r*100)/100} ${n[r]}`}function P(e){return{".jpg":`image/jpeg`,".jpeg":`image/jpeg`,".png":`image/png`,".gif":`image/gif`,".bmp":`image/bmp`,".webp":`image/webp`,".svg":`image/svg+xml`,".mp4":`video/mp4`,".avi":`video/x-msvideo`,".mov":`video/quicktime`,".wmv":`video/x-ms-wmv`,".flv":`video/x-flv`,".mkv":`video/x-matroska`,".webm":`video/webm`,".mp3":`audio/mpeg`,".wav":`audio/wav`,".aac":`audio/aac`,".flac":`audio/flac`,".m4a":`audio/mp4`,".pdf":`application/pdf`,".doc":`application/msword`,".docx":`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,".xls":`application/vnd.ms-excel`,".xlsx":`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,".ppt":`application/vnd.ms-powerpoint`,".pptx":`application/vnd.openxmlformats-officedocument.presentationml.presentation`,".txt":`text/plain`,".csv":`text/csv`,".json":`application/json`,".xml":`application/xml`,".zip":`application/zip`}[e.toLowerCase().slice(e.lastIndexOf(`.`))]||`application/octet-stream`}function ie(e,t){if(!t||t.length===0)return!0;let n=P(e);return t.some(e=>{if(e.endsWith(`/*`)){let[t]=e.split(`/`);return n.startsWith(`${t}/`)}return e===n})}function ae(e,t,n){return!(t!==void 0&&e>t||n!==void 0&&e<n)}function oe(e){let t=e.lastIndexOf(`.`);return t===-1?``:e.slice(t+1).toLowerCase()}function se(e){let t=e.lastIndexOf(`.`);return t===-1?e:e.slice(0,t)}function ce(e){let t=[`.jpg`,`.jpeg`,`.png`,`.gif`,`.bmp`,`.webp`,`.svg`],n=e.toLowerCase().slice(e.lastIndexOf(`.`));return t.includes(n)}function le(e){let t=[`.mp4`,`.avi`,`.mov`,`.wmv`,`.flv`,`.mkv`,`.webm`],n=e.toLowerCase().slice(e.lastIndexOf(`.`));return t.includes(n)}function ue(e){let t=[`.pdf`,`.doc`,`.docx`,`.xls`,`.xlsx`,`.ppt`,`.pptx`,`.txt`,`.csv`],n=e.toLowerCase().slice(e.lastIndexOf(`.`));return t.includes(n)}let F=function(e){return e.CAMERA=`CAMERA`,e.PHOTO_LIBRARY=`PHOTO_LIBRARY`,e.WRITE_STORAGE=`WRITE_STORAGE`,e.READ_STORAGE=`READ_STORAGE`,e}({}),I=function(e){return e.GRANTED=`granted`,e.DENIED=`denied`,e.NOT_DETERMINED=`not_determined`,e.RESTRICTED=`restricted`,e}({});async function L(){try{return console.log(`Camera permission requested (handled by file system provider)`),!0}catch(e){return console.error(`Failed to request camera permission:`,e),!1}}async function R(){try{return console.log(`Photo library permission requested (handled by file system provider)`),!0}catch(e){return console.error(`Failed to request photo library permission:`,e),!1}}async function z(){try{return console.log(`Storage read permission requested (handled by file system provider)`),!0}catch(e){return console.error(`Failed to request storage read permission:`,e),!1}}async function B(){try{return console.log(`Storage write permission requested (handled by file system provider)`),!0}catch(e){return console.error(`Failed to request storage write permission:`,e),!1}}async function de(e){try{return(await Promise.all(e.map(async e=>{switch(e){case F.CAMERA:return L();case F.PHOTO_LIBRARY:return R();case F.READ_STORAGE:return z();case F.WRITE_STORAGE:return B();default:return!1}}))).every(e=>e)}catch(e){return console.error(`Failed to request permissions:`,e),!1}}async function fe(e){try{return!0}catch(e){return console.error(`Failed to check permissions:`,e),!1}}async function pe(e){try{return I.GRANTED}catch(e){return console.error(`Failed to get permission status:`,e),I.DENIED}}function me(){try{console.log(`Opening app settings (requires react-native-app-settings or platform implementation)`)}catch(e){console.error(`Failed to open app settings:`,e)}}function V(e){try{if(e.startsWith(`file://`))return e.replace(`file://`,``).split(`/`).pop()||`file`;if(e.startsWith(`content://`)){let t=e.split(`/`);return t[t.length-1]||`file`}let t=e.split(`/`);return t[t.length-1]||`file`}catch{return`file`}}function he(e){return e.startsWith(`file://`)||e.startsWith(`content://`)?e:`file://${e}`}function H(e){return e.startsWith(`file://`)?e.replace(`file://`,``):(e.startsWith(`content://`),e)}function ge(e){try{let t=H(e).split(`/`);return t.pop(),t.join(`/`)}catch{return``}}function _e(e){return e.startsWith(`content://`)}function ve(e){return e.startsWith(`file://`)}function ye(e){return e.replace(/([^:]\/)\/+/g,`$1`)}function be(e){let t=V(e);return{".jpg":`image/jpeg`,".jpeg":`image/jpeg`,".png":`image/png`,".gif":`image/gif`,".bmp":`image/bmp`,".webp":`image/webp`,".mp4":`video/mp4`,".mov":`video/quicktime`,".avi":`video/x-msvideo`,".mp3":`audio/mpeg`,".wav":`audio/wav`,".aac":`audio/aac`,".pdf":`application/pdf`,".txt":`text/plain`,".json":`application/json`}[t.toLowerCase().slice(t.lastIndexOf(`.`))]||`application/octet-stream`}function U({state:e,label:t}){let n=()=>{switch(e.status){case`uploading`:return`#007AFF`;case`success`:return`#34C759`;case`error`:case`aborted`:return`#FF3B30`;default:return`#999999`}};return y(f,{style:[W.wrapper,{borderLeftColor:n()}],children:[e.status===`uploading`&&v(s,{size:`small`,color:n(),style:W.spinner}),(()=>{switch(e.status){case`idle`:return v(f,{style:W.container,children:v(d,{style:W.label,children:t||`Ready to upload`})});case`uploading`:return y(f,{style:W.container,children:[y(f,{style:W.headerRow,children:[v(d,{style:W.label,children:t||`Uploading`}),y(d,{style:W.percentage,children:[e.progress,`%`]})]}),v(f,{style:W.progressBarContainer,children:v(f,{style:[W.progressBar,{width:`${e.progress}%`,backgroundColor:n()}]})}),v(f,{style:W.detailsRow,children:y(d,{style:W.detail,children:[N(e.bytesUploaded),` /`,` `,N(e.totalBytes||0)]})})]});case`success`:return y(f,{style:W.container,children:[y(f,{style:W.headerRow,children:[v(d,{style:[W.label,{color:n()}],children:t||`Upload complete`}),v(d,{style:[W.percentage,{color:n()}],children:`✓`})]}),v(d,{style:[W.detail,{color:n()}],children:N(e.totalBytes||0)})]});case`error`:return y(f,{style:W.container,children:[y(f,{style:W.headerRow,children:[v(d,{style:[W.label,{color:n()}],children:t||`Upload failed`}),v(d,{style:[W.percentage,{color:n()}],children:`✕`})]}),e.error&&v(d,{style:[W.detail,{color:n()}],children:e.error.message})]});case`aborted`:return v(f,{style:W.container,children:v(d,{style:[W.label,{color:n()}],children:t||`Upload cancelled`})});default:return null}})()]})}const W=u.create({wrapper:{flexDirection:`row`,alignItems:`flex-start`,paddingVertical:8,paddingHorizontal:12,borderLeftWidth:4,backgroundColor:`#f5f5f5`,borderRadius:4,gap:8},spinner:{marginTop:4},container:{flex:1,gap:4},headerRow:{flexDirection:`row`,justifyContent:`space-between`,alignItems:`center`},label:{fontSize:14,fontWeight:`600`,color:`#333333`,flex:1},percentage:{fontSize:14,fontWeight:`600`,color:`#007AFF`,minWidth:36,textAlign:`right`},progressBarContainer:{height:4,backgroundColor:`#e0e0e0`,borderRadius:2,overflow:`hidden`},progressBar:{height:`100%`,borderRadius:2},detailsRow:{flexDirection:`row`,justifyContent:`space-between`,alignItems:`center`},detail:{fontSize:12,color:`#666666`}});function xe({options:e,label:t=`Take Photo`,children:n,onSuccess:r,onError:a,onCancel:o,showProgress:c=!0}){let{state:u,captureAndUpload:p}=T(e),m=async()=>{try{await p()}catch(e){e instanceof Error&&(e.message.includes(`cancelled`)||e.message.includes(`aborted`)?o?.():a?.(e))}},h=u.status===`uploading`,g=h||u.status===`aborted`;return i(()=>{u.status===`success`&&u.result&&r?.(u.result)},[u.status,u.result,r]),i(()=>{u.status===`error`&&u.error&&a?.(u.error)},[u.status,u.error,a]),y(f,{style:G.container,children:[y(l,{style:[G.button,g&&G.buttonDisabled],onPress:m,disabled:g,children:[h&&v(s,{size:`small`,color:`#FFFFFF`,style:G.spinner}),v(d,{style:G.buttonText,children:n||t})]}),c&&u.status!==`idle`&&v(f,{style:G.progressContainer,children:v(U,{state:u,label:`Camera upload`})})]})}const G=u.create({container:{gap:8},button:{flexDirection:`row`,alignItems:`center`,justifyContent:`center`,paddingVertical:12,paddingHorizontal:16,backgroundColor:`#007AFF`,borderRadius:8,gap:8},buttonDisabled:{opacity:.6},buttonText:{fontSize:16,fontWeight:`600`,color:`#FFFFFF`},spinner:{marginRight:4},progressContainer:{marginTop:4}});function Se({options:e,label:t=`Choose File`,children:n,onSuccess:r,onError:a,onCancel:o,showProgress:c=!0}){let{state:u,pickAndUpload:p}=E(e),m=async()=>{try{await p()}catch(e){e instanceof Error&&(e.message.includes(`cancelled`)||e.message.includes(`aborted`)?o?.():a?.(e))}},h=u.status===`uploading`,g=h||u.status===`aborted`;return i(()=>{u.status===`success`&&u.result&&r?.(u.result)},[u.status,u.result,r]),i(()=>{u.status===`error`&&u.error&&a?.(u.error)},[u.status,u.error,a]),y(f,{style:K.container,children:[y(l,{style:[K.button,g&&K.buttonDisabled],onPress:m,disabled:g,children:[h&&v(s,{size:`small`,color:`#FFFFFF`,style:K.spinner}),v(d,{style:K.buttonText,children:n||t})]}),c&&u.status!==`idle`&&v(f,{style:K.progressContainer,children:v(U,{state:u,label:`File upload`})})]})}const K=u.create({container:{gap:8},button:{flexDirection:`row`,alignItems:`center`,justifyContent:`center`,paddingVertical:12,paddingHorizontal:16,backgroundColor:`#FF9500`,borderRadius:8,gap:8},buttonDisabled:{opacity:.6},buttonText:{fontSize:16,fontWeight:`600`,color:`#FFFFFF`},spinner:{marginRight:4},progressContainer:{marginTop:4}}),q=t(null);function J(){let e=r(q);if(!e)throw Error(`useFlowContext must be used within a <Flow> component. Wrap your component tree with <Flow flowId="..." storageId="...">`);return e}const Y=t(null);function X(){let e=r(Y);if(!e)throw Error(`useFlowInputContext must be used within a <Flow.Input> component. Wrap your component with <Flow.Input nodeId="...">`);return e}function Ce({flowId:e,storageId:t,outputNodeId:r,metadata:i,onSuccess:a,onError:o,onProgress:s,onFlowComplete:c,children:l}){let{fileSystemProvider:u}=S(),d=k({flowId:e,storageId:t,outputNodeId:r,metadata:i,onSuccess:a,onError:o,onProgress:s,onFlowComplete:c}),f=n(async e=>{if(!u?.pickDocument)throw Error(`File picker not available`);let t=await u.pickDocument();t.status===`success`&&d.setInput(e,t)},[u,d]),p=n(async()=>{if(!u?.pickDocument)throw Error(`File picker not available`);let e=await u.pickDocument();e.status===`success`&&await d.upload(e)},[u,d]),m={state:d.state,inputMetadata:d.inputMetadata,inputs:d.inputs,inputStates:d.inputStates,setInput:d.setInput,execute:d.execute,upload:d.upload,abort:d.abort,reset:d.reset,isActive:d.isActive,isUploadingFile:d.isUploadingFile,isProcessing:d.isProcessing,isDiscoveringInputs:d.isDiscoveringInputs,pickFileForInput:f,pickAndUpload:p},h={...m,submit:d.execute,cancel:d.abort};return v(q.Provider,{value:m,children:typeof l==`function`?l(h):l})}function we({children:e}){let t=J();return v(_,{children:e({inputs:t.inputMetadata??[],isLoading:t.isDiscoveringInputs})})}function Te({nodeId:e,children:t}){let n=J(),r=n.inputMetadata?.find(t=>t.nodeId===e);if(!r)return null;let i={nodeId:e,metadata:r,value:n.inputs[e],setValue:t=>n.setInput(e,t),state:n.inputStates.get(e),pickFile:async()=>{await n.pickFileForInput(e)}};return v(Y.Provider,{value:i,children:typeof t==`function`?t(i):t})}function Ee({children:e}){let t=X(),n=t.value,r=n?.status===`success`,i=r?n?.data?.name??null:null,a=r?n?.data?.size??null:null;return v(_,{children:e({value:t.value,hasFile:r,fileName:i,fileSize:a,progress:t.state?.progress??0,status:t.state?.status??`idle`,pickFile:t.pickFile,clear:()=>t.setValue(void 0)})})}function De({children:e}){let t=X(),n=t.value,r=n?.status===`success`,i=typeof t.value==`string`&&t.value.length>0;return v(_,{children:e({value:t.value,hasFile:r,isUrl:i,fileName:r?n?.data?.name??null:null,fileSize:r?n?.data?.size??null:null,fileUri:r?n?.data?.uri??null:null,clear:()=>t.setValue(void 0)})})}function Oe({children:e}){let t=J();return v(_,{children:e({progress:t.state.progress,bytesUploaded:t.state.bytesUploaded,totalBytes:t.state.totalBytes,status:t.state.status})})}function ke({children:e}){let t=J();return v(_,{children:e({status:t.state.status,currentNodeName:t.state.currentNodeName,currentNodeType:t.state.currentNodeType,error:t.state.error,jobId:t.state.jobId,flowStarted:t.state.flowStarted,flowOutputs:t.state.flowOutputs})})}function Ae({children:e}){let t=J();return v(_,{children:e({error:t.state.error,hasError:t.state.status===`error`,message:t.state.error?.message??null,reset:t.reset})})}function je({children:e,disabled:t}){let n=J(),r={submit:n.execute,isDisabled:t||n.isActive||Object.keys(n.inputs).length===0,isSubmitting:n.isActive};return v(_,{children:typeof e==`function`?e(r):e})}function Me({children:e}){let t=J(),n={cancel:t.abort,isDisabled:!t.isActive};return v(_,{children:typeof e==`function`?e(n):e})}function Ne({children:e}){let t=J(),n={reset:t.reset,isDisabled:t.isActive};return v(_,{children:typeof e==`function`?e(n):e})}function Pe({children:e}){let t=J();return v(_,{children:e({isUploading:t.isActive,progress:t.state.progress,status:t.state.status,pickAndUpload:t.pickAndUpload,abort:t.abort})})}const Fe=Object.assign(Ce,{Inputs:we,Input:Object.assign(Te,{FilePicker:Ee,Preview:De}),Progress:Oe,Status:ke,Error:Ae,Submit:je,Cancel:Me,Reset:Ne,QuickUpload:Pe});function Ie({options:t,label:n=`Select from Gallery`,children:r,onSuccess:i,onError:a,onCancel:o,showProgress:u=!0}){let{state:p,selectAndUpload:m}=M(t),h=async()=>{try{await m()}catch(e){e instanceof Error&&(e.message.includes(`cancelled`)||e.message.includes(`aborted`)?o?.():a?.(e))}},g=p.items.some(e=>e.status===`uploading`),_=p.items.length>0,b=_&&p.items.every(e=>e.status!==`uploading`&&e.status!==`idle`);return e.useEffect(()=>{if(b){let e=p.items.filter(e=>e.status===`success`).map(e=>e.result);e.length>0&&i?.(e)}},[b,p.items,i]),e.useEffect(()=>{let e=p.items.filter(e=>e.status===`error`)[0]?.error;e&&a?.(e)},[p.items,a]),y(f,{style:Z.container,children:[y(l,{style:[Z.button,g&&Z.buttonDisabled],onPress:h,disabled:g,children:[g&&v(s,{size:`small`,color:`#FFFFFF`,style:Z.spinner}),y(d,{style:Z.buttonText,children:[r||n,_&&` (${p.items.length})`]})]}),_&&y(f,{style:Z.statsContainer,children:[y(d,{style:Z.statsText,children:[`Progress: `,p.items.filter(e=>e.status===`success`).length,`/`,p.items.length,` uploaded`]}),y(d,{style:Z.statsText,children:[`Overall: `,p.totalProgress,`%`]})]}),u&&_&&v(c,{scrollEnabled:!1,data:p.items,renderItem:({item:e})=>v(f,{style:Z.itemContainer,children:v(U,{state:{status:e.status,progress:e.progress,bytesUploaded:e.bytesUploaded,totalBytes:e.totalBytes,error:e.error,result:e.result},label:e.file.data.name})},e.id),keyExtractor:e=>e.id,style:Z.listContainer,contentContainerStyle:Z.listContent,ItemSeparatorComponent:()=>v(f,{style:Z.separator})})]})}const Z=u.create({container:{gap:8},button:{flexDirection:`row`,alignItems:`center`,justifyContent:`center`,paddingVertical:12,paddingHorizontal:16,backgroundColor:`#34C759`,borderRadius:8,gap:8},buttonDisabled:{opacity:.6},buttonText:{fontSize:16,fontWeight:`600`,color:`#FFFFFF`},spinner:{marginRight:4},statsContainer:{paddingVertical:8,paddingHorizontal:12,backgroundColor:`#f5f5f5`,borderRadius:4,gap:4},statsText:{fontSize:12,color:`#666666`},listContainer:{maxHeight:400},listContent:{gap:8},itemContainer:{paddingHorizontal:0},separator:{height:4}});function Le({items:e,onRemove:t,onItemPress:n,showRemoveButton:r=!0}){return e.length===0?v(f,{style:Q.emptyContainer,children:v(d,{style:Q.emptyText,children:`No uploads`})}):y(f,{style:Q.container,children:[y(f,{style:Q.headerRow,children:[y(d,{style:Q.headerText,children:[`Uploads (`,e.length,`)`]}),y(d,{style:Q.headerSubtext,children:[e.filter(e=>e.progress.state===`success`).length,` complete`]})]}),v(c,{scrollEnabled:!1,data:e,renderItem:({item:e})=>y(l,{style:[Q.itemContainer,{borderLeftColor:Re(e.progress.state)}],onPress:()=>n?.(e),children:[y(f,{style:Q.itemContent,children:[e.file.status===`success`&&y(f,{style:Q.itemHeader,children:[v(d,{style:Q.fileName,numberOfLines:1,children:e.file.data.name}),v(d,{style:Q.fileSize,children:ze(e.file.data.size)})]}),e.file.status===`error`&&v(d,{style:Q.errorText,children:e.progress.error?.message}),v(f,{style:Q.progressWrapper,children:v(U,{state:{status:e.progress.state===`pending`?`idle`:e.progress.state===`cancelled`?`aborted`:e.progress.state,progress:e.progress.progress,bytesUploaded:e.progress.uploadedBytes,totalBytes:e.progress.totalBytes,error:e.progress.error||null,result:e.result??null}})})]}),r&&e.progress.state!==`uploading`&&e.progress.state!==`pending`&&v(l,{style:Q.removeButton,onPress:()=>t?.(e.id),hitSlop:{top:8,right:8,bottom:8,left:8},children:v(d,{style:Q.removeButtonText,children:`✕`})})]}),keyExtractor:e=>e.id,ItemSeparatorComponent:()=>v(f,{style:Q.separator}),contentContainerStyle:Q.listContent})]})}function Re(e){switch(e){case`success`:return`#34C759`;case`error`:case`cancelled`:return`#FF3B30`;case`uploading`:case`pending`:return`#007AFF`;default:return`#999999`}}function ze(e){if(e===0)return`0 B`;let t=1024,n=[`B`,`KB`,`MB`,`GB`],r=Math.floor(Math.log(e)/Math.log(t));return`${Math.round(e/t**r*10)/10} ${n[r]}`}const Q=u.create({container:{gap:8},headerRow:{flexDirection:`row`,justifyContent:`space-between`,alignItems:`center`,paddingHorizontal:12,paddingVertical:8,backgroundColor:`#f9f9f9`,borderRadius:4},headerText:{fontSize:16,fontWeight:`600`,color:`#333333`},errorText:{fontSize:14,color:`#FF3B30`},headerSubtext:{fontSize:14,color:`#666666`},listContent:{gap:8},itemContainer:{flexDirection:`row`,alignItems:`center`,paddingVertical:8,paddingHorizontal:12,borderLeftWidth:4,backgroundColor:`#f5f5f5`,borderRadius:4,gap:8},itemContent:{flex:1,gap:6},itemHeader:{flexDirection:`row`,justifyContent:`space-between`,alignItems:`center`},fileName:{fontSize:14,fontWeight:`500`,color:`#333333`,flex:1},fileSize:{fontSize:12,color:`#999999`,marginLeft:8},progressWrapper:{marginTop:2},removeButton:{width:32,height:32,justifyContent:`center`,alignItems:`center`,borderRadius:16,backgroundColor:`#FFE5E5`},removeButtonText:{fontSize:16,fontWeight:`600`,color:`#FF3B30`},separator:{height:4},emptyContainer:{paddingVertical:24,paddingHorizontal:12,backgroundColor:`#f5f5f5`,borderRadius:4,alignItems:`center`,justifyContent:`center`},emptyText:{fontSize:14,color:`#999999`,fontStyle:`italic`}}),Be=t(null);function $(){let e=r(Be);if(!e)throw Error(`useUploadContext must be used within an <Upload> component. Wrap your component tree with <Upload>`);return e}const Ve=t(null);function He(){let e=r(Ve);if(!e)throw Error(`useUploadItemContext must be used within an <Upload.Item> component. Wrap your component with <Upload.Item id="...">`);return e}function Ue({multiple:e=!1,maxConcurrent:t=3,autoStart:r=!0,metadata:i,onSuccess:a,onError:o,onComplete:s,children:c}){let{fileSystemProvider:l}=S(),u=j({maxConcurrent:t,metadata:i,onSuccess:a,onError:o}),d=n(()=>{let{items:e}=u.state;if(e.length>0&&e.every(e=>e.status===`success`||e.status===`error`||e.status===`aborted`)&&s){let t=e.filter(e=>e.status===`success`).length,n=e.filter(e=>e.status===`error`||e.status===`aborted`).length;s({successful:t,failed:n,total:e.length})}},[u.state,s]),f=n(t=>{e||u.clear();let n=u.addFiles(t);r&&n.length>0&&u.startUploads(n).then(d)},[e,r,u,d]),p=n(async()=>{if(!l?.pickDocument)throw Error(`File picker not available`);let e=await l.pickDocument();return e.status===`success`?(f([e]),e):null},[l,f]),m=n(async()=>{if(!l?.pickImage)throw Error(`Image picker not available`);let t=await l.pickImage({allowMultiple:e});return t.status===`success`?(f([t]),t):null},[l,f,e]),h=n(async()=>{if(!l?.pickCamera)throw Error(`Camera not available`);let e=await l.pickCamera();return e.status===`success`?(f([e]),e):null},[l,f]),g={mode:e?`multi`:`single`,state:u.state,autoStart:r,addFiles:u.addFiles,removeItem:u.removeItem,startAll:async e=>{await u.startUploads(e),d()},abortItem:u.abortItem,retryItem:u.retryItem,clear:u.clear,handleFilesReceived:f,pickFile:p,pickImage:m,takePhoto:h};return v(Be.Provider,{value:g,children:typeof c==`function`?c(g):c})}function We({children:e}){let t=$();return v(_,{children:e({pick:n(async()=>{await t.pickFile()},[t]),isLoading:t.state.activeCount>0})})}function Ge({children:e}){let t=$();return v(_,{children:e({pick:n(async()=>{await t.pickImage()},[t]),isLoading:t.state.activeCount>0})})}function Ke({children:e}){let t=$();return v(_,{children:e({take:n(async()=>{await t.takePhoto()},[t]),isLoading:t.state.activeCount>0})})}function qe({children:e}){let t=$();return v(_,{children:e({items:t.state.items,hasItems:t.state.items.length>0,isEmpty:t.state.items.length===0})})}function Je({id:e,children:t}){let n=$(),r=n.state.items.find(t=>t.id===e);if(!r)return null;let i={id:e,file:r.file,state:{status:r.status,progress:r.progress,bytesUploaded:r.bytesUploaded,totalBytes:r.totalBytes,error:r.error,result:r.result},abort:()=>n.abortItem(e),retry:()=>n.retryItem(e),remove:()=>n.removeItem(e)};return v(Ve.Provider,{value:i,children:typeof t==`function`?t(i):t})}function Ye({children:e}){let t=$();return v(_,{children:e({progress:t.state.totalProgress,bytesUploaded:t.state.totalUploaded,totalBytes:t.state.totalBytes,isUploading:t.state.activeCount>0})})}function Xe({children:e}){let{state:t}=$(),n=`idle`;return t.activeCount>0?n=`uploading`:t.items.length>0&&t.items.every(e=>e.status===`success`||e.status===`error`||e.status===`aborted`)&&(n=t.failedCount>0?`error`:`success`),v(_,{children:e({status:n,isIdle:n===`idle`,isUploading:t.activeCount>0,isSuccess:t.completedCount>0&&t.failedCount===0&&t.activeCount===0,isError:t.failedCount>0,total:t.items.length,successful:t.completedCount,failed:t.failedCount,active:t.activeCount})})}function Ze({children:e}){let t=$(),n=t.state.items.filter(e=>e.status===`error`||e.status===`aborted`);return v(_,{children:e({hasError:n.length>0,failedCount:n.length,failedItems:n,clear:t.clear})})}function Qe({children:e}){let t=$();return v(_,{children:e({cancel:n(()=>{for(let e of t.state.items.filter(e=>e.status===`uploading`))t.abortItem(e.id)},[t]),disabled:t.state.activeCount===0})})}function $e({children:e}){let t=$();return v(_,{children:e({retry:n(async()=>{let e=t.state.items.filter(e=>e.status===`error`||e.status===`aborted`);for(let n of e)await t.retryItem(n.id)},[t]),disabled:t.state.failedCount===0})})}function et({children:e}){return v(_,{children:e({reset:$().clear})})}function tt({children:e}){let t=$(),r=t.state.items.filter(e=>e.status===`idle`).length;return v(_,{children:e({start:n(async()=>{await t.startAll()},[t]),disabled:t.state.activeCount>0||r===0})})}const nt=Object.assign(Ue,{FilePicker:We,GalleryPicker:Ge,CameraPicker:Ke,Items:qe,Item:Je,Progress:Ye,Status:Xe,Error:Ze,Cancel:Qe,Retry:$e,Reset:et,StartAll:tt});export{xe as CameraUploadButton,Se as FileUploadButton,Fe as Flow,te as FlowManagerProvider,Ie as GalleryUploadButton,I as PermissionStatus,F as PermissionType,nt as Upload,Le as UploadList,U as UploadProgress,b as UploadistaContext,N as formatFileSize,ge as getDirectoryFromUri,oe as getFileExtension,V as getFileNameFromUri,se as getFileNameWithoutExtension,P as getMimeTypeFromFileName,be as getMimeTypeFromUri,pe as getPermissionStatus,fe as hasPermissions,_e as isContentUri,ue as isDocumentFile,ae as isFileSizeValid,ie as isFileTypeAllowed,ve as isFileUri,ce as isImageFile,le as isVideoFile,ye as normalizeUri,me as openAppSettings,he as pathToUri,L as requestCameraPermission,de as requestPermissions,R as requestPhotoLibraryPermission,z as requestStorageReadPermission,B as requestStorageWritePermission,H as uriToPath,T as useCameraUpload,E as useFileUpload,k as useFlow,J as useFlowContext,X as useFlowInputContext,O as useFlowManagerContext,M as useGalleryUpload,j as useMultiUpload,$ as useUploadContext,He as useUploadItemContext,re as useUploadMetrics,S as useUploadistaContext};
|
|
1
|
+
import e,{createContext as t,useCallback as n,useContext as r,useEffect as i,useRef as a,useState as o}from"react";import{ActivityIndicator as s,FlatList as c,Pressable as l,StyleSheet as u,Text as d,View as f}from"react-native";import{FlowManager as p,UploadManager as m}from"@uploadista/client-core";import{EventType as h}from"@uploadista/core/flow";import{UploadEventType as g}from"@uploadista/core/types";import{Fragment as _,jsx as v,jsxs as y}from"react/jsx-runtime";const b=t(void 0);function x(e,t){let n=e instanceof ArrayBuffer?new Uint8Array(e):e;return new Blob([n],t)}function S(){let e=r(b);if(!e)throw Error(`useUploadistaClient must be used within an UploadistaProvider`);return e}const C={status:`idle`,progress:0,bytesUploaded:0,totalBytes:null,error:null,result:null};function w(e={}){let{client:t,fileSystemProvider:r}=S(),[s,c]=o(C),l=a(null),u=a(null);return i(()=>(l.current=new m(async(e,n)=>{let i=e;if(i.status===`success`){let e=x(await r.readFile(i.data.uri),{type:i.data.mimeType||`application/octet-stream`});return t.upload(e,n)}return Promise.resolve({abort:()=>{}})},{onStateChange:c,onProgress:e.onProgress,onChunkComplete:e.onChunkComplete,onSuccess:e.onSuccess,onError:e.onError,onAbort:e.onAbort},{metadata:e.metadata,uploadLengthDeferred:e.uploadLengthDeferred,uploadSize:e.uploadSize,onShouldRetry:e.onShouldRetry}),()=>{l.current?.cleanup()}),[t,r,e]),{state:s,upload:n(async e=>{u.current=e,await l.current?.upload(e)},[]),abort:n(()=>{l.current?.abort()},[]),reset:n(()=>{l.current?.reset(),u.current=null},[]),retry:n(()=>{u.current&&l.current?.canRetry()&&l.current.retry()},[]),isUploading:s.status===`uploading`,canRetry:l.current?.canRetry()??!1,metrics:{getInsights:()=>t.getChunkingInsights(),exportMetrics:()=>t.exportMetrics(),getNetworkMetrics:()=>t.getNetworkMetrics(),getNetworkCondition:()=>t.getNetworkCondition(),resetMetrics:()=>t.resetMetrics()}}}function T(e){let{fileSystemProvider:t}=S(),r=w({metadata:e?.metadata,onSuccess:e?.onSuccess,onError:e?.onError,onProgress:e?.onProgress}),i=n(async()=>{try{let n=await t.pickCamera(e?.cameraOptions);await r.upload(n)}catch(e){console.error(`Camera capture error:`,e)}},[t,e?.cameraOptions,r]);return{...r,captureAndUpload:i}}function E(e){let{fileSystemProvider:t}=S(),r=w({metadata:e?.metadata,onSuccess:e?.onSuccess,onError:e?.onError,onProgress:e?.onProgress}),i=n(async()=>{try{let n=await t.pickDocument({allowedTypes:e?.allowedTypes});await r.upload(n)}catch(e){throw console.error(`File selection error:`,e),e}},[t,e?.allowedTypes,r]);return{...r,pickAndUpload:i}}function D(e){let t=e;return t.eventType===h.FlowStart||t.eventType===h.FlowEnd||t.eventType===h.FlowError||t.eventType===h.NodeStart||t.eventType===h.NodeEnd||t.eventType===h.NodePause||t.eventType===h.NodeResume||t.eventType===h.NodeError}const O=t(void 0);function ee({children:e}){let{client:t,subscribeToEvents:r}=S(),o=a(new Map);i(()=>r(e=>{if(D(e)){for(let t of o.current.values())t.manager.handleFlowEvent(e);return}if(`type`in e&&e.type===g.UPLOAD_PROGRESS&&`data`in e)for(let t of o.current.values())t.manager.handleUploadProgress(e.data.id,e.data.progress,e.data.total)}),[r]);let s=n((e,n,r)=>{let i=o.current.get(e);if(i)return i.refCount++,i.manager;let a=new p(t.uploadWithFlow,n,r,t.multiInputFlowUpload);return o.current.set(e,{manager:a,refCount:1,flowId:e}),a},[t]),c=n(e=>{let t=o.current.get(e);t&&(t.refCount--,t.refCount<=0&&(t.manager.cleanup(),o.current.delete(e)))},[]);return v(O.Provider,{value:{getManager:s,releaseManager:c},children:e})}function k(){let e=r(O);if(e===void 0)throw Error(`useFlowManagerContext must be used within a FlowManagerProvider. Make sure to wrap your component tree with <FlowManagerProvider>.`);return e}const te={status:`idle`,progress:0,bytesUploaded:0,totalBytes:null,error:null,jobId:null,flowStarted:!1,currentNodeName:null,currentNodeType:null,flowOutputs:null,pausedAtNodeId:null};function A(e){let{client:t,fileSystemProvider:r}=S(),{getManager:s,releaseManager:c}=k(),[l,u]=o(te),[d,f]=o(null),[p,m]=o(!1),[h,g]=o({}),[_,v]=o(new Map),y=a(null),b=a(null),C=a(e);i(()=>{C.current=e}),i(()=>{(async()=>{m(!0);try{let{flow:n}=await t.getFlow(e.flowId);f(n.nodes.filter(e=>e.type===`input`).map(e=>({nodeId:e.id,nodeName:e.name,nodeDescription:e.description,inputTypeId:e.inputTypeId,required:!0})))}catch(e){console.error(`Failed to discover flow inputs:`,e)}finally{m(!1)}})()},[t,e.flowId]),i(()=>{let t=e.flowId;y.current=s(t,{onStateChange:e=>{u(e)},onProgress:(e,t,n)=>{if(C.current.onProgress){let e=n?Math.round(t/n*100):0;C.current.onProgress(e,t,n)}},onChunkComplete:(e,t,n)=>{C.current.onChunkComplete?.(e,t,n)},onFlowComplete:e=>{C.current.onFlowComplete?.(e)},onSuccess:e=>{C.current.onSuccess?.(e)},onError:e=>{C.current.onError?.(e)},onAbort:()=>{}},{flowConfig:{flowId:e.flowId,storageId:e.storageId,outputNodeId:e.outputNodeId,metadata:e.metadata},onChunkComplete:e.onChunkComplete,onSuccess:e.onSuccess,onError:e.onError});let n=setInterval(()=>{if(y.current){let e=y.current.getInputStates();e.size>0&&v(new Map(e))}},100);return()=>{clearInterval(n),c(t),y.current=null}},[e.flowId,e.storageId,e.outputNodeId,s,c]);let w=n((e,t)=>{g(n=>({...n,[e]:t}))},[]),T=n(async e=>{if(e.status===`cancelled`)return null;if(e.status===`error`)throw e.error;return x(await r.readFile(e.data.uri),{type:e.data.mimeType||`application/octet-stream`})},[r]),E=n(async()=>{if(!y.current)throw Error(`FlowManager not initialized`);if(Object.keys(h).length===0)throw Error(`No inputs provided. Use setInput() to provide inputs before calling execute()`);b.current={...h};let e={};for(let[t,n]of Object.entries(h))if(n&&typeof n==`object`&&`status`in n&&(n.status===`success`||n.status===`cancelled`||n.status===`error`)){let r=await T(n);r&&(e[t]=r)}else e[t]=n;if(Object.keys(e).length===0)throw Error(`No valid inputs after processing. All files may have been cancelled.`);await y.current.executeFlow(e)},[h,T]),D=n(async t=>{if(t.status!==`cancelled`){if(t.status===`error`){e.onError?.(t.error);return}if(!y.current)throw Error(`FlowManager not initialized`);if(d&&d.length>0){let e=d[0];e&&(b.current={[e.nodeId]:t})}try{let e=x(await r.readFile(t.data.uri),{type:t.data.mimeType||`application/octet-stream`});if(d&&d.length>0){let n=d[0];if(!n)throw Error(`No input nodes found`);g({[n.nodeId]:t}),await y.current.executeFlow({[n.nodeId]:e})}else await y.current.upload(e)}catch(t){e.onError?.(t)}}},[d,r,e]),O=n(async()=>{await y.current?.abort()},[]),ee=n(async()=>{await y.current?.pause()},[]),A=n(async()=>{await y.current?.resume()},[]),j=n(()=>{y.current?.reset(),g({}),v(new Map),b.current=null},[]),M=n(()=>{b.current&&(l.status===`error`||l.status===`aborted`)&&(g(b.current),E())},[E,l.status]),N=l.status===`uploading`||l.status===`processing`,P=l.status===`uploading`,F=l.status===`processing`,I=l.status===`paused`;return{state:l,inputMetadata:d,inputStates:_,inputs:h,setInput:w,execute:E,upload:D,abort:O,pause:ee,resume:A,reset:j,retry:M,isActive:N,isUploadingFile:P,isProcessing:F,isDiscoveringInputs:p,canRetry:(l.status===`error`||l.status===`aborted`)&&b.current!==null,isPaused:I}}const j={items:[],totalProgress:0,totalUploaded:0,totalBytes:0,activeCount:0,completedCount:0,failedCount:0};function M(e={}){let{client:t}=S(),[r,i]=o(j),s=a(new Map),c=a(0),l=a([]),u=n(()=>`upload-${Date.now()}-${c.current++}`,[]),d=n(e=>{let t=e.reduce((e,t)=>e+t.totalBytes,0),n=e.reduce((e,t)=>e+t.bytesUploaded,0),r=t>0?Math.round(n/t*100):0,a=e.filter(e=>e.status===`uploading`).length,o=e.filter(e=>e.status===`success`).length,s=e.filter(e=>e.status===`error`).length;l.current=e,i(i=>({...i,items:e,totalProgress:r,totalUploaded:n,totalBytes:t,activeCount:a,completedCount:o,failedCount:s}))},[]),f=n(e=>{let t=e.filter(e=>e.status===`success`).map(e=>({id:u(),file:e,status:`idle`,progress:0,bytesUploaded:0,totalBytes:e.data.size,error:null,result:null})),n=[...l.current,...t];return l.current=n,i(e=>{let t=n.reduce((e,t)=>e+t.totalBytes,0);return{...e,items:n,totalBytes:t}}),t.map(e=>e.id)},[u]),p=n(async n=>{try{console.log(`Uploading item:`,n.file.data.name),d(l.current.map(e=>e.id===n.id?{...e,status:`uploading`}:e));let r=await(await fetch(n.file.data.uri)).blob(),i=r;if(n.file.data.mimeType){let e={type:n.file.data.mimeType,lastModified:Date.now()};i=new Blob([r],e)}console.log(`Uploading input:`,i);let a=await t.upload(i,{metadata:e.metadata,onProgress:(e,t,r)=>{let i=r?Math.round(t/r*100):0;d(l.current.map(e=>e.id===n.id?{...e,progress:i,bytesUploaded:t,totalBytes:r||e.totalBytes}:e))},onSuccess:t=>{d(l.current.map(e=>e.id===n.id?{...e,status:`success`,progress:100,result:t,bytesUploaded:t.size||e.totalBytes}:e)),e.onSuccess?.(t),s.current.delete(n.id)},onError:t=>{d(l.current.map(e=>e.id===n.id?{...e,status:`error`,error:t}:e)),e.onError?.(t),s.current.delete(n.id)}});s.current.set(n.id,a)}catch(t){console.error(`Error uploading item:`,t),d(l.current.map(e=>e.id===n.id?{...e,status:`error`,error:t}:e)),e.onError?.(t),s.current.delete(n.id)}},[t,e,d]),m=n(async t=>{let n=e.maxConcurrent||3,r=t?l.current.filter(e=>t.includes(e.id)&&e.status===`idle`):l.current.filter(e=>e.status===`idle`);console.log(`Items to upload:`,r.length,r);for(let e=0;e<r.length;e+=n){let t=r.slice(e,e+n);await Promise.all(t.map(e=>p(e)))}},[e.maxConcurrent,p]),h=n(e=>{let t=s.current.get(e);t&&(t.abort(),s.current.delete(e)),d(l.current.filter(t=>t.id!==e))},[d]),g=n(e=>{let t=s.current.get(e);t&&(t.abort(),s.current.delete(e)),d(l.current.map(t=>t.id===e?{...t,status:`aborted`}:t))},[d]),_=n(()=>{s.current.forEach(e=>{e.abort()}),s.current.clear(),l.current=[],i(j)},[]);return{state:r,addFiles:f,startUploads:m,removeItem:h,abortItem:g,retryItem:n(async e=>{let t=l.current.find(t=>t.id===e);if(t&&(t.status===`error`||t.status===`aborted`)){d(l.current.map(t=>t.id===e?{...t,status:`idle`,progress:0,bytesUploaded:0,error:null}:t));let t=l.current.find(t=>t.id===e);t&&await p(t)}},[p,d]),clear:_}}function N(e){let{fileSystemProvider:t}=S(),r=M({maxConcurrent:3,metadata:e?.metadata,onSuccess:e?.onSuccess,onError:e?.onError}),i=n(async()=>{let n;if(n=e?.mediaType===`video`?await t.pickVideo({allowMultiple:e?.allowMultiple??!0}):(e?.mediaType,await t.pickImage({allowMultiple:e?.allowMultiple??!0})),n.status===`cancelled`)return[];if(n.status===`error`)return console.error(`Gallery selection error:`,n.error),e?.onError?.(n.error),[];let i=r.addFiles([n]);return await r.startUploads(i),i},[t,e?.allowMultiple,e?.mediaType,e?.onError,r]);return{...r,selectAndUpload:i}}function P(){let e=a(null),t=a(0),r=a(0),[i,s]=o({totalBytes:0,durationMs:0,avgSpeed:0,peakSpeed:0,retries:0});return{metrics:i,start:n(()=>{e.current=Date.now(),t.current=0,r.current=0},[]),update:n((t,n,i=0)=>{if(!e.current)return;let a=Date.now()-e.current,o=a>0?t/a*1e3:0;o>r.current&&(r.current=o),s({totalBytes:t,durationMs:a,avgSpeed:a>0?t/a*1e3:0,peakSpeed:r.current,retries:i})},[]),end:n(()=>{let t=i;return e.current=null,t},[i]),reset:n(()=>{e.current=null,t.current=0,r.current=0,s({totalBytes:0,durationMs:0,avgSpeed:0,peakSpeed:0,retries:0})},[])}}function F(e){if(e===0)return`0 Bytes`;let t=1024,n=[`Bytes`,`KB`,`MB`,`GB`],r=Math.floor(Math.log(e)/Math.log(t));return`${Math.round(e/t**r*100)/100} ${n[r]}`}function I(e){return{".jpg":`image/jpeg`,".jpeg":`image/jpeg`,".png":`image/png`,".gif":`image/gif`,".bmp":`image/bmp`,".webp":`image/webp`,".svg":`image/svg+xml`,".mp4":`video/mp4`,".avi":`video/x-msvideo`,".mov":`video/quicktime`,".wmv":`video/x-ms-wmv`,".flv":`video/x-flv`,".mkv":`video/x-matroska`,".webm":`video/webm`,".mp3":`audio/mpeg`,".wav":`audio/wav`,".aac":`audio/aac`,".flac":`audio/flac`,".m4a":`audio/mp4`,".pdf":`application/pdf`,".doc":`application/msword`,".docx":`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,".xls":`application/vnd.ms-excel`,".xlsx":`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,".ppt":`application/vnd.ms-powerpoint`,".pptx":`application/vnd.openxmlformats-officedocument.presentationml.presentation`,".txt":`text/plain`,".csv":`text/csv`,".json":`application/json`,".xml":`application/xml`,".zip":`application/zip`}[e.toLowerCase().slice(e.lastIndexOf(`.`))]||`application/octet-stream`}function ne(e,t){if(!t||t.length===0)return!0;let n=I(e);return t.some(e=>{if(e.endsWith(`/*`)){let[t]=e.split(`/`);return n.startsWith(`${t}/`)}return e===n})}function re(e,t,n){return!(t!==void 0&&e>t||n!==void 0&&e<n)}function ie(e){let t=e.lastIndexOf(`.`);return t===-1?``:e.slice(t+1).toLowerCase()}function ae(e){let t=e.lastIndexOf(`.`);return t===-1?e:e.slice(0,t)}function oe(e){let t=[`.jpg`,`.jpeg`,`.png`,`.gif`,`.bmp`,`.webp`,`.svg`],n=e.toLowerCase().slice(e.lastIndexOf(`.`));return t.includes(n)}function se(e){let t=[`.mp4`,`.avi`,`.mov`,`.wmv`,`.flv`,`.mkv`,`.webm`],n=e.toLowerCase().slice(e.lastIndexOf(`.`));return t.includes(n)}function ce(e){let t=[`.pdf`,`.doc`,`.docx`,`.xls`,`.xlsx`,`.ppt`,`.pptx`,`.txt`,`.csv`],n=e.toLowerCase().slice(e.lastIndexOf(`.`));return t.includes(n)}let L=function(e){return e.CAMERA=`CAMERA`,e.PHOTO_LIBRARY=`PHOTO_LIBRARY`,e.WRITE_STORAGE=`WRITE_STORAGE`,e.READ_STORAGE=`READ_STORAGE`,e}({}),R=function(e){return e.GRANTED=`granted`,e.DENIED=`denied`,e.NOT_DETERMINED=`not_determined`,e.RESTRICTED=`restricted`,e}({});async function z(){try{return console.log(`Camera permission requested (handled by file system provider)`),!0}catch(e){return console.error(`Failed to request camera permission:`,e),!1}}async function B(){try{return console.log(`Photo library permission requested (handled by file system provider)`),!0}catch(e){return console.error(`Failed to request photo library permission:`,e),!1}}async function V(){try{return console.log(`Storage read permission requested (handled by file system provider)`),!0}catch(e){return console.error(`Failed to request storage read permission:`,e),!1}}async function H(){try{return console.log(`Storage write permission requested (handled by file system provider)`),!0}catch(e){return console.error(`Failed to request storage write permission:`,e),!1}}async function le(e){try{return(await Promise.all(e.map(async e=>{switch(e){case L.CAMERA:return z();case L.PHOTO_LIBRARY:return B();case L.READ_STORAGE:return V();case L.WRITE_STORAGE:return H();default:return!1}}))).every(e=>e)}catch(e){return console.error(`Failed to request permissions:`,e),!1}}async function ue(e){try{return!0}catch(e){return console.error(`Failed to check permissions:`,e),!1}}async function de(e){try{return R.GRANTED}catch(e){return console.error(`Failed to get permission status:`,e),R.DENIED}}function fe(){try{console.log(`Opening app settings (requires react-native-app-settings or platform implementation)`)}catch(e){console.error(`Failed to open app settings:`,e)}}function pe(e){try{if(e.startsWith(`file://`))return e.replace(`file://`,``).split(`/`).pop()||`file`;if(e.startsWith(`content://`)){let t=e.split(`/`);return t[t.length-1]||`file`}let t=e.split(`/`);return t[t.length-1]||`file`}catch{return`file`}}function me(e){return e.startsWith(`file://`)||e.startsWith(`content://`)?e:`file://${e}`}function he(e){return e.startsWith(`file://`)?e.replace(`file://`,``):(e.startsWith(`content://`),e)}function ge(e){try{let t=he(e).split(`/`);return t.pop(),t.join(`/`)}catch{return``}}function _e(e){return e.startsWith(`content://`)}function ve(e){return e.startsWith(`file://`)}function ye(e){return e.replace(/([^:]\/)\/+/g,`$1`)}function be(e){let t=pe(e);return{".jpg":`image/jpeg`,".jpeg":`image/jpeg`,".png":`image/png`,".gif":`image/gif`,".bmp":`image/bmp`,".webp":`image/webp`,".mp4":`video/mp4`,".mov":`video/quicktime`,".avi":`video/x-msvideo`,".mp3":`audio/mpeg`,".wav":`audio/wav`,".aac":`audio/aac`,".pdf":`application/pdf`,".txt":`text/plain`,".json":`application/json`}[t.toLowerCase().slice(t.lastIndexOf(`.`))]||`application/octet-stream`}function U({state:e,label:t}){let n=()=>{switch(e.status){case`uploading`:return`#007AFF`;case`success`:return`#34C759`;case`error`:case`aborted`:return`#FF3B30`;default:return`#999999`}};return y(f,{style:[W.wrapper,{borderLeftColor:n()}],children:[e.status===`uploading`&&v(s,{size:`small`,color:n(),style:W.spinner}),(()=>{switch(e.status){case`idle`:return v(f,{style:W.container,children:v(d,{style:W.label,children:t||`Ready to upload`})});case`uploading`:return y(f,{style:W.container,children:[y(f,{style:W.headerRow,children:[v(d,{style:W.label,children:t||`Uploading`}),y(d,{style:W.percentage,children:[e.progress,`%`]})]}),v(f,{style:W.progressBarContainer,children:v(f,{style:[W.progressBar,{width:`${e.progress}%`,backgroundColor:n()}]})}),v(f,{style:W.detailsRow,children:y(d,{style:W.detail,children:[F(e.bytesUploaded),` /`,` `,F(e.totalBytes||0)]})})]});case`success`:return y(f,{style:W.container,children:[y(f,{style:W.headerRow,children:[v(d,{style:[W.label,{color:n()}],children:t||`Upload complete`}),v(d,{style:[W.percentage,{color:n()}],children:`✓`})]}),v(d,{style:[W.detail,{color:n()}],children:F(e.totalBytes||0)})]});case`error`:return y(f,{style:W.container,children:[y(f,{style:W.headerRow,children:[v(d,{style:[W.label,{color:n()}],children:t||`Upload failed`}),v(d,{style:[W.percentage,{color:n()}],children:`✕`})]}),e.error&&v(d,{style:[W.detail,{color:n()}],children:e.error.message})]});case`aborted`:return v(f,{style:W.container,children:v(d,{style:[W.label,{color:n()}],children:t||`Upload cancelled`})});default:return null}})()]})}const W=u.create({wrapper:{flexDirection:`row`,alignItems:`flex-start`,paddingVertical:8,paddingHorizontal:12,borderLeftWidth:4,backgroundColor:`#f5f5f5`,borderRadius:4,gap:8},spinner:{marginTop:4},container:{flex:1,gap:4},headerRow:{flexDirection:`row`,justifyContent:`space-between`,alignItems:`center`},label:{fontSize:14,fontWeight:`600`,color:`#333333`,flex:1},percentage:{fontSize:14,fontWeight:`600`,color:`#007AFF`,minWidth:36,textAlign:`right`},progressBarContainer:{height:4,backgroundColor:`#e0e0e0`,borderRadius:2,overflow:`hidden`},progressBar:{height:`100%`,borderRadius:2},detailsRow:{flexDirection:`row`,justifyContent:`space-between`,alignItems:`center`},detail:{fontSize:12,color:`#666666`}});function xe({options:e,label:t=`Take Photo`,children:n,onSuccess:r,onError:a,onCancel:o,showProgress:c=!0}){let{state:u,captureAndUpload:p}=T(e),m=async()=>{try{await p()}catch(e){e instanceof Error&&(e.message.includes(`cancelled`)||e.message.includes(`aborted`)?o?.():a?.(e))}},h=u.status===`uploading`,g=h||u.status===`aborted`;return i(()=>{u.status===`success`&&u.result&&r?.(u.result)},[u.status,u.result,r]),i(()=>{u.status===`error`&&u.error&&a?.(u.error)},[u.status,u.error,a]),y(f,{style:G.container,children:[y(l,{style:[G.button,g&&G.buttonDisabled],onPress:m,disabled:g,children:[h&&v(s,{size:`small`,color:`#FFFFFF`,style:G.spinner}),v(d,{style:G.buttonText,children:n||t})]}),c&&u.status!==`idle`&&v(f,{style:G.progressContainer,children:v(U,{state:u,label:`Camera upload`})})]})}const G=u.create({container:{gap:8},button:{flexDirection:`row`,alignItems:`center`,justifyContent:`center`,paddingVertical:12,paddingHorizontal:16,backgroundColor:`#007AFF`,borderRadius:8,gap:8},buttonDisabled:{opacity:.6},buttonText:{fontSize:16,fontWeight:`600`,color:`#FFFFFF`},spinner:{marginRight:4},progressContainer:{marginTop:4}});function Se({options:e,label:t=`Choose File`,children:n,onSuccess:r,onError:a,onCancel:o,showProgress:c=!0}){let{state:u,pickAndUpload:p}=E(e),m=async()=>{try{await p()}catch(e){e instanceof Error&&(e.message.includes(`cancelled`)||e.message.includes(`aborted`)?o?.():a?.(e))}},h=u.status===`uploading`,g=h||u.status===`aborted`;return i(()=>{u.status===`success`&&u.result&&r?.(u.result)},[u.status,u.result,r]),i(()=>{u.status===`error`&&u.error&&a?.(u.error)},[u.status,u.error,a]),y(f,{style:K.container,children:[y(l,{style:[K.button,g&&K.buttonDisabled],onPress:m,disabled:g,children:[h&&v(s,{size:`small`,color:`#FFFFFF`,style:K.spinner}),v(d,{style:K.buttonText,children:n||t})]}),c&&u.status!==`idle`&&v(f,{style:K.progressContainer,children:v(U,{state:u,label:`File upload`})})]})}const K=u.create({container:{gap:8},button:{flexDirection:`row`,alignItems:`center`,justifyContent:`center`,paddingVertical:12,paddingHorizontal:16,backgroundColor:`#FF9500`,borderRadius:8,gap:8},buttonDisabled:{opacity:.6},buttonText:{fontSize:16,fontWeight:`600`,color:`#FFFFFF`},spinner:{marginRight:4},progressContainer:{marginTop:4}}),q=t(null);function J(){let e=r(q);if(!e)throw Error(`useFlowContext must be used within a <Flow> component. Wrap your component tree with <Flow flowId="..." storageId="...">`);return e}const Y=t(null);function X(){let e=r(Y);if(!e)throw Error(`useFlowInputContext must be used within a <Flow.Input> component. Wrap your component with <Flow.Input nodeId="...">`);return e}function Ce({flowId:e,storageId:t,outputNodeId:r,metadata:i,onSuccess:a,onError:o,onProgress:s,onFlowComplete:c,children:l}){let{fileSystemProvider:u}=S(),d=A({flowId:e,storageId:t,outputNodeId:r,metadata:i,onSuccess:a,onError:o,onProgress:s,onFlowComplete:c}),f=n(async e=>{if(!u?.pickDocument)throw Error(`File picker not available`);let t=await u.pickDocument();t.status===`success`&&d.setInput(e,t)},[u,d]),p=n(async()=>{if(!u?.pickDocument)throw Error(`File picker not available`);let e=await u.pickDocument();e.status===`success`&&await d.upload(e)},[u,d]),m={state:d.state,inputMetadata:d.inputMetadata,inputs:d.inputs,inputStates:d.inputStates,setInput:d.setInput,execute:d.execute,upload:d.upload,abort:d.abort,pause:d.pause,reset:d.reset,isActive:d.isActive,isUploadingFile:d.isUploadingFile,isProcessing:d.isProcessing,isDiscoveringInputs:d.isDiscoveringInputs,isPaused:d.isPaused,pickFileForInput:f,pickAndUpload:p},h={...m,submit:d.execute,cancel:d.abort};return v(q.Provider,{value:m,children:typeof l==`function`?l(h):l})}function we({children:e}){let t=J();return v(_,{children:e({inputs:t.inputMetadata??[],isLoading:t.isDiscoveringInputs})})}function Te({nodeId:e,children:t}){let n=J(),r=n.inputMetadata?.find(t=>t.nodeId===e);if(!r)return null;let i={nodeId:e,metadata:r,value:n.inputs[e],setValue:t=>n.setInput(e,t),state:n.inputStates.get(e),pickFile:async()=>{await n.pickFileForInput(e)}};return v(Y.Provider,{value:i,children:typeof t==`function`?t(i):t})}function Ee({children:e}){let t=X(),n=t.value,r=n?.status===`success`,i=r?n?.data?.name??null:null,a=r?n?.data?.size??null:null;return v(_,{children:e({value:t.value,hasFile:r,fileName:i,fileSize:a,progress:t.state?.progress??0,status:t.state?.status??`idle`,pickFile:t.pickFile,clear:()=>t.setValue(void 0)})})}function De({children:e}){let t=X(),n=t.value,r=n?.status===`success`,i=typeof t.value==`string`&&t.value.length>0;return v(_,{children:e({value:t.value,hasFile:r,isUrl:i,fileName:r?n?.data?.name??null:null,fileSize:r?n?.data?.size??null:null,fileUri:r?n?.data?.uri??null:null,clear:()=>t.setValue(void 0)})})}function Oe({children:e}){let t=J();return v(_,{children:e({progress:t.state.progress,bytesUploaded:t.state.bytesUploaded,totalBytes:t.state.totalBytes,status:t.state.status})})}function ke({children:e}){let t=J();return v(_,{children:e({status:t.state.status,currentNodeName:t.state.currentNodeName,currentNodeType:t.state.currentNodeType,error:t.state.error,jobId:t.state.jobId,flowStarted:t.state.flowStarted,flowOutputs:t.state.flowOutputs})})}function Ae({children:e}){let t=J();return v(_,{children:e({error:t.state.error,hasError:t.state.status===`error`,message:t.state.error?.message??null,reset:t.reset})})}function je({children:e,disabled:t}){let n=J(),r={submit:n.execute,isDisabled:t||n.isActive||Object.keys(n.inputs).length===0,isSubmitting:n.isActive};return v(_,{children:typeof e==`function`?e(r):e})}function Me({children:e}){let t=J(),n={cancel:t.abort,isDisabled:!t.isActive};return v(_,{children:typeof e==`function`?e(n):e})}function Ne({children:e}){let t=J(),n={reset:t.reset,isDisabled:t.isActive};return v(_,{children:typeof e==`function`?e(n):e})}function Pe({children:e}){let t=J(),n={pause:t.pause,isDisabled:!t.isActive||t.isPaused,isPaused:t.isPaused};return v(_,{children:typeof e==`function`?e(n):e})}function Fe({children:e}){let t=J();return v(_,{children:e({isUploading:t.isActive,progress:t.state.progress,status:t.state.status,pickAndUpload:t.pickAndUpload,abort:t.abort})})}const Ie=Object.assign(Ce,{Inputs:we,Input:Object.assign(Te,{FilePicker:Ee,Preview:De}),Progress:Oe,Status:ke,Error:Ae,Submit:je,Cancel:Me,Pause:Pe,Reset:Ne,QuickUpload:Fe});function Le({options:t,label:n=`Select from Gallery`,children:r,onSuccess:i,onError:a,onCancel:o,showProgress:u=!0}){let{state:p,selectAndUpload:m}=N(t),h=async()=>{try{await m()}catch(e){e instanceof Error&&(e.message.includes(`cancelled`)||e.message.includes(`aborted`)?o?.():a?.(e))}},g=p.items.some(e=>e.status===`uploading`),_=p.items.length>0,b=_&&p.items.every(e=>e.status!==`uploading`&&e.status!==`idle`);return e.useEffect(()=>{if(b){let e=p.items.filter(e=>e.status===`success`).map(e=>e.result);e.length>0&&i?.(e)}},[b,p.items,i]),e.useEffect(()=>{let e=p.items.filter(e=>e.status===`error`)[0]?.error;e&&a?.(e)},[p.items,a]),y(f,{style:Z.container,children:[y(l,{style:[Z.button,g&&Z.buttonDisabled],onPress:h,disabled:g,children:[g&&v(s,{size:`small`,color:`#FFFFFF`,style:Z.spinner}),y(d,{style:Z.buttonText,children:[r||n,_&&` (${p.items.length})`]})]}),_&&y(f,{style:Z.statsContainer,children:[y(d,{style:Z.statsText,children:[`Progress: `,p.items.filter(e=>e.status===`success`).length,`/`,p.items.length,` uploaded`]}),y(d,{style:Z.statsText,children:[`Overall: `,p.totalProgress,`%`]})]}),u&&_&&v(c,{scrollEnabled:!1,data:p.items,renderItem:({item:e})=>v(f,{style:Z.itemContainer,children:v(U,{state:{status:e.status,progress:e.progress,bytesUploaded:e.bytesUploaded,totalBytes:e.totalBytes,error:e.error,result:e.result},label:e.file.data.name})},e.id),keyExtractor:e=>e.id,style:Z.listContainer,contentContainerStyle:Z.listContent,ItemSeparatorComponent:()=>v(f,{style:Z.separator})})]})}const Z=u.create({container:{gap:8},button:{flexDirection:`row`,alignItems:`center`,justifyContent:`center`,paddingVertical:12,paddingHorizontal:16,backgroundColor:`#34C759`,borderRadius:8,gap:8},buttonDisabled:{opacity:.6},buttonText:{fontSize:16,fontWeight:`600`,color:`#FFFFFF`},spinner:{marginRight:4},statsContainer:{paddingVertical:8,paddingHorizontal:12,backgroundColor:`#f5f5f5`,borderRadius:4,gap:4},statsText:{fontSize:12,color:`#666666`},listContainer:{maxHeight:400},listContent:{gap:8},itemContainer:{paddingHorizontal:0},separator:{height:4}});function Re({items:e,onRemove:t,onItemPress:n,showRemoveButton:r=!0}){return e.length===0?v(f,{style:Q.emptyContainer,children:v(d,{style:Q.emptyText,children:`No uploads`})}):y(f,{style:Q.container,children:[y(f,{style:Q.headerRow,children:[y(d,{style:Q.headerText,children:[`Uploads (`,e.length,`)`]}),y(d,{style:Q.headerSubtext,children:[e.filter(e=>e.progress.state===`success`).length,` complete`]})]}),v(c,{scrollEnabled:!1,data:e,renderItem:({item:e})=>y(l,{style:[Q.itemContainer,{borderLeftColor:ze(e.progress.state)}],onPress:()=>n?.(e),children:[y(f,{style:Q.itemContent,children:[e.file.status===`success`&&y(f,{style:Q.itemHeader,children:[v(d,{style:Q.fileName,numberOfLines:1,children:e.file.data.name}),v(d,{style:Q.fileSize,children:Be(e.file.data.size)})]}),e.file.status===`error`&&v(d,{style:Q.errorText,children:e.progress.error?.message}),v(f,{style:Q.progressWrapper,children:v(U,{state:{status:e.progress.state===`pending`?`idle`:e.progress.state===`cancelled`?`aborted`:e.progress.state,progress:e.progress.progress,bytesUploaded:e.progress.uploadedBytes,totalBytes:e.progress.totalBytes,error:e.progress.error||null,result:e.result??null}})})]}),r&&e.progress.state!==`uploading`&&e.progress.state!==`pending`&&v(l,{style:Q.removeButton,onPress:()=>t?.(e.id),hitSlop:{top:8,right:8,bottom:8,left:8},children:v(d,{style:Q.removeButtonText,children:`✕`})})]}),keyExtractor:e=>e.id,ItemSeparatorComponent:()=>v(f,{style:Q.separator}),contentContainerStyle:Q.listContent})]})}function ze(e){switch(e){case`success`:return`#34C759`;case`error`:case`cancelled`:return`#FF3B30`;case`uploading`:case`pending`:return`#007AFF`;default:return`#999999`}}function Be(e){if(e===0)return`0 B`;let t=1024,n=[`B`,`KB`,`MB`,`GB`],r=Math.floor(Math.log(e)/Math.log(t));return`${Math.round(e/t**r*10)/10} ${n[r]}`}const Q=u.create({container:{gap:8},headerRow:{flexDirection:`row`,justifyContent:`space-between`,alignItems:`center`,paddingHorizontal:12,paddingVertical:8,backgroundColor:`#f9f9f9`,borderRadius:4},headerText:{fontSize:16,fontWeight:`600`,color:`#333333`},errorText:{fontSize:14,color:`#FF3B30`},headerSubtext:{fontSize:14,color:`#666666`},listContent:{gap:8},itemContainer:{flexDirection:`row`,alignItems:`center`,paddingVertical:8,paddingHorizontal:12,borderLeftWidth:4,backgroundColor:`#f5f5f5`,borderRadius:4,gap:8},itemContent:{flex:1,gap:6},itemHeader:{flexDirection:`row`,justifyContent:`space-between`,alignItems:`center`},fileName:{fontSize:14,fontWeight:`500`,color:`#333333`,flex:1},fileSize:{fontSize:12,color:`#999999`,marginLeft:8},progressWrapper:{marginTop:2},removeButton:{width:32,height:32,justifyContent:`center`,alignItems:`center`,borderRadius:16,backgroundColor:`#FFE5E5`},removeButtonText:{fontSize:16,fontWeight:`600`,color:`#FF3B30`},separator:{height:4},emptyContainer:{paddingVertical:24,paddingHorizontal:12,backgroundColor:`#f5f5f5`,borderRadius:4,alignItems:`center`,justifyContent:`center`},emptyText:{fontSize:14,color:`#999999`,fontStyle:`italic`}}),Ve=t(null);function $(){let e=r(Ve);if(!e)throw Error(`useUploadContext must be used within an <Upload> component. Wrap your component tree with <Upload>`);return e}const He=t(null);function Ue(){let e=r(He);if(!e)throw Error(`useUploadItemContext must be used within an <Upload.Item> component. Wrap your component with <Upload.Item id="...">`);return e}function We({multiple:e=!1,maxConcurrent:t=3,autoStart:r=!0,metadata:i,onSuccess:a,onError:o,onComplete:s,children:c}){let{fileSystemProvider:l}=S(),u=M({maxConcurrent:t,metadata:i,onSuccess:a,onError:o}),d=n(()=>{let{items:e}=u.state;if(e.length>0&&e.every(e=>e.status===`success`||e.status===`error`||e.status===`aborted`)&&s){let t=e.filter(e=>e.status===`success`).length,n=e.filter(e=>e.status===`error`||e.status===`aborted`).length;s({successful:t,failed:n,total:e.length})}},[u.state,s]),f=n(t=>{e||u.clear();let n=u.addFiles(t);r&&n.length>0&&u.startUploads(n).then(d)},[e,r,u,d]),p=n(async()=>{if(!l?.pickDocument)throw Error(`File picker not available`);let e=await l.pickDocument();return e.status===`success`?(f([e]),e):null},[l,f]),m=n(async()=>{if(!l?.pickImage)throw Error(`Image picker not available`);let t=await l.pickImage({allowMultiple:e});return t.status===`success`?(f([t]),t):null},[l,f,e]),h=n(async()=>{if(!l?.pickCamera)throw Error(`Camera not available`);let e=await l.pickCamera();return e.status===`success`?(f([e]),e):null},[l,f]),g={mode:e?`multi`:`single`,state:u.state,autoStart:r,addFiles:u.addFiles,removeItem:u.removeItem,startAll:async e=>{await u.startUploads(e),d()},abortItem:u.abortItem,retryItem:u.retryItem,clear:u.clear,handleFilesReceived:f,pickFile:p,pickImage:m,takePhoto:h};return v(Ve.Provider,{value:g,children:typeof c==`function`?c(g):c})}function Ge({children:e}){let t=$();return v(_,{children:e({pick:n(async()=>{await t.pickFile()},[t]),isLoading:t.state.activeCount>0})})}function Ke({children:e}){let t=$();return v(_,{children:e({pick:n(async()=>{await t.pickImage()},[t]),isLoading:t.state.activeCount>0})})}function qe({children:e}){let t=$();return v(_,{children:e({take:n(async()=>{await t.takePhoto()},[t]),isLoading:t.state.activeCount>0})})}function Je({children:e}){let t=$();return v(_,{children:e({items:t.state.items,hasItems:t.state.items.length>0,isEmpty:t.state.items.length===0})})}function Ye({id:e,children:t}){let n=$(),r=n.state.items.find(t=>t.id===e);if(!r)return null;let i={id:e,file:r.file,state:{status:r.status,progress:r.progress,bytesUploaded:r.bytesUploaded,totalBytes:r.totalBytes,error:r.error,result:r.result},abort:()=>n.abortItem(e),retry:()=>n.retryItem(e),remove:()=>n.removeItem(e)};return v(He.Provider,{value:i,children:typeof t==`function`?t(i):t})}function Xe({children:e}){let t=$();return v(_,{children:e({progress:t.state.totalProgress,bytesUploaded:t.state.totalUploaded,totalBytes:t.state.totalBytes,isUploading:t.state.activeCount>0})})}function Ze({children:e}){let{state:t}=$(),n=`idle`;return t.activeCount>0?n=`uploading`:t.items.length>0&&t.items.every(e=>e.status===`success`||e.status===`error`||e.status===`aborted`)&&(n=t.failedCount>0?`error`:`success`),v(_,{children:e({status:n,isIdle:n===`idle`,isUploading:t.activeCount>0,isSuccess:t.completedCount>0&&t.failedCount===0&&t.activeCount===0,isError:t.failedCount>0,total:t.items.length,successful:t.completedCount,failed:t.failedCount,active:t.activeCount})})}function Qe({children:e}){let t=$(),n=t.state.items.filter(e=>e.status===`error`||e.status===`aborted`);return v(_,{children:e({hasError:n.length>0,failedCount:n.length,failedItems:n,clear:t.clear})})}function $e({children:e}){let t=$();return v(_,{children:e({cancel:n(()=>{for(let e of t.state.items.filter(e=>e.status===`uploading`))t.abortItem(e.id)},[t]),disabled:t.state.activeCount===0})})}function et({children:e}){let t=$();return v(_,{children:e({retry:n(async()=>{let e=t.state.items.filter(e=>e.status===`error`||e.status===`aborted`);for(let n of e)await t.retryItem(n.id)},[t]),disabled:t.state.failedCount===0})})}function tt({children:e}){return v(_,{children:e({reset:$().clear})})}function nt({children:e}){let t=$(),r=t.state.items.filter(e=>e.status===`idle`).length;return v(_,{children:e({start:n(async()=>{await t.startAll()},[t]),disabled:t.state.activeCount>0||r===0})})}const rt=Object.assign(We,{FilePicker:Ge,GalleryPicker:Ke,CameraPicker:qe,Items:Je,Item:Ye,Progress:Xe,Status:Ze,Error:Qe,Cancel:$e,Retry:et,Reset:tt,StartAll:nt});export{xe as CameraUploadButton,Se as FileUploadButton,Ie as Flow,ee as FlowManagerProvider,Le as GalleryUploadButton,R as PermissionStatus,L as PermissionType,rt as Upload,Re as UploadList,U as UploadProgress,b as UploadistaContext,F as formatFileSize,ge as getDirectoryFromUri,ie as getFileExtension,pe as getFileNameFromUri,ae as getFileNameWithoutExtension,I as getMimeTypeFromFileName,be as getMimeTypeFromUri,de as getPermissionStatus,ue as hasPermissions,_e as isContentUri,ce as isDocumentFile,re as isFileSizeValid,ne as isFileTypeAllowed,ve as isFileUri,oe as isImageFile,se as isVideoFile,ye as normalizeUri,fe as openAppSettings,me as pathToUri,z as requestCameraPermission,le as requestPermissions,B as requestPhotoLibraryPermission,V as requestStorageReadPermission,H as requestStorageWritePermission,he as uriToPath,T as useCameraUpload,E as useFileUpload,A as useFlow,J as useFlowContext,X as useFlowInputContext,k as useFlowManagerContext,N as useGalleryUpload,M as useMultiUpload,$ as useUploadContext,Ue as useUploadItemContext,P as useUploadMetrics,S as useUploadistaContext};
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|