@uploadista/react 0.0.17 → 0.0.18-beta.1
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/components/index.d.mts +2 -2
- package/dist/components/index.mjs +1 -1
- package/dist/hooks/index.d.mts +1 -1
- package/dist/hooks/index.mjs +1 -1
- package/dist/index.d.mts +4 -4
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/{upload-zone-Bbqr8oWe.mjs → upload-zone-BjWHuP7p.mjs} +2 -2
- package/dist/upload-zone-BjWHuP7p.mjs.map +1 -0
- package/dist/{uploadista-provider-BeHP_vze.d.mts → uploadista-provider-CM48PPSp.d.mts} +2 -2
- package/dist/{uploadista-provider-BeHP_vze.d.mts.map → uploadista-provider-CM48PPSp.d.mts.map} +1 -1
- package/dist/use-upload-metrics-Df90wIos.mjs +2 -0
- package/dist/use-upload-metrics-Df90wIos.mjs.map +1 -0
- package/dist/{use-uploadista-client-CQi9j8yN.d.mts → use-uploadista-client-m9nF-irM.d.mts} +3 -3
- package/dist/use-uploadista-client-m9nF-irM.d.mts.map +1 -0
- package/package.json +5 -5
- package/src/components/flow-input.tsx +5 -5
- package/src/hooks/use-flow.ts +3 -3
- package/dist/upload-zone-Bbqr8oWe.mjs.map +0 -1
- package/dist/use-upload-metrics-OAofTcgA.mjs +0 -2
- package/dist/use-upload-metrics-OAofTcgA.mjs.map +0 -1
- package/dist/use-uploadista-client-CQi9j8yN.d.mts.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"use-upload-metrics-Df90wIos.mjs","names":["initialState: FlowUploadState","initialState","initialState: FlowUploadState","initialMetrics: UploadMetrics","estimatedTimeRemaining: number | null","newMetrics: UploadMetrics","fileMetric: FileUploadMetrics"],"sources":["../src/hooks/event-utils.ts","../src/hooks/use-uploadista-events.ts","../src/hooks/use-flow-events.ts","../src/hooks/use-upload-events.ts","../src/hooks/use-flow.ts","../src/hooks/use-flow-execution.ts","../src/hooks/use-upload-metrics.ts"],"sourcesContent":["import type { UploadistaEvent } from \"@uploadista/client-browser\";\nimport { EventType, type FlowEvent } from \"@uploadista/core/flow\";\nimport { UploadEventType, type UploadEvent } from \"@uploadista/core/types\";\n\n/**\n * Type guard to check if an event is a flow event\n */\nexport function isFlowEvent(event: UploadistaEvent): event is FlowEvent {\n if (!(\"eventType\" in event)) return false;\n const e = event as { eventType: unknown };\n return (\n e.eventType === EventType.JobStart ||\n e.eventType === EventType.JobEnd ||\n e.eventType === EventType.FlowStart ||\n e.eventType === EventType.FlowEnd ||\n e.eventType === EventType.FlowError ||\n e.eventType === EventType.FlowPause ||\n e.eventType === EventType.FlowCancel ||\n e.eventType === EventType.NodeStart ||\n e.eventType === EventType.NodeEnd ||\n e.eventType === EventType.NodePause ||\n e.eventType === EventType.NodeResume ||\n e.eventType === EventType.NodeError ||\n e.eventType === EventType.NodeStream ||\n e.eventType === EventType.NodeResponse\n );\n}\n\n/**\n * Type guard to check if an event is an upload event\n */\nexport function isUploadEvent(event: UploadistaEvent): event is UploadEvent {\n if (!(\"type\" in event)) return false;\n const e = event as { type: unknown };\n return (\n e.type === UploadEventType.UPLOAD_STARTED ||\n e.type === UploadEventType.UPLOAD_PROGRESS ||\n e.type === UploadEventType.UPLOAD_COMPLETE ||\n e.type === UploadEventType.UPLOAD_FAILED ||\n e.type === UploadEventType.UPLOAD_VALIDATION_SUCCESS ||\n e.type === UploadEventType.UPLOAD_VALIDATION_FAILED ||\n e.type === UploadEventType.UPLOAD_VALIDATION_WARNING\n );\n}\n","import type { UploadistaEvent } from \"@uploadista/client-core\";\nimport { useEffect } from \"react\";\nimport { useUploadistaContext } from \"../components/uploadista-provider\";\n\n/**\n * Simple hook that subscribes to all Uploadista events (both flow and upload events).\n *\n * This is a low-level hook that provides access to all events. For more structured\n * event handling, consider using `useFlowEvents` or `useUploadEvents` instead.\n *\n * Must be used within UploadistaProvider.\n *\n * @param callback - Function called for every event emitted by the Uploadista client\n *\n * @example\n * ```tsx\n * import { useUploadistaEvents, isFlowEvent, isUploadEvent } from '@uploadista/react';\n *\n * function MyComponent() {\n * useUploadistaEvents((event) => {\n * if (isFlowEvent(event)) {\n * console.log('Flow event:', event.eventType);\n * } else if (isUploadEvent(event)) {\n * console.log('Upload event:', event.type);\n * }\n * });\n *\n * return <div>Listening to all events...</div>;\n * }\n * ```\n */\nexport function useUploadistaEvents(\n callback: (event: UploadistaEvent) => void,\n): void {\n const { subscribeToEvents } = useUploadistaContext();\n\n useEffect(() => {\n const unsubscribe = subscribeToEvents(callback);\n return unsubscribe;\n }, [subscribeToEvents, callback]);\n}\n","import type {\n FlowEventFlowCancel,\n FlowEventFlowEnd,\n FlowEventFlowError,\n FlowEventFlowPause,\n FlowEventFlowStart,\n FlowEventJobEnd,\n FlowEventJobStart,\n FlowEventNodeEnd,\n FlowEventNodeError,\n FlowEventNodePause,\n FlowEventNodeResume,\n FlowEventNodeStart,\n} from \"@uploadista/core/flow\";\nimport { EventType } from \"@uploadista/core/flow\";\nimport { useEffect } from \"react\";\nimport { useUploadistaContext } from \"../components/uploadista-provider\";\nimport { isFlowEvent } from \"./event-utils\";\n\n/**\n * Options for handling flow execution events.\n *\n * All callbacks are optional - only provide handlers for events you care about.\n */\nexport interface UseFlowEventsOptions {\n /** Called when a job starts execution */\n onJobStart?: (event: FlowEventJobStart) => void;\n /** Called when a job completes (success or failure) */\n onJobEnd?: (event: FlowEventJobEnd) => void;\n /** Called when a flow begins execution */\n onFlowStart?: (event: FlowEventFlowStart) => void;\n /** Called when a flow completes successfully */\n onFlowEnd?: (event: FlowEventFlowEnd) => void;\n /** Called when a flow encounters an error */\n onFlowError?: (event: FlowEventFlowError) => void;\n /** Called when a flow is paused by user request */\n onFlowPause?: (event: FlowEventFlowPause) => void;\n /** Called when a flow is cancelled by user request */\n onFlowCancel?: (event: FlowEventFlowCancel) => void;\n /** Called when a node starts processing */\n onNodeStart?: (event: FlowEventNodeStart) => void;\n /** Called when a node completes successfully */\n onNodeEnd?: (event: FlowEventNodeEnd) => void;\n /** Called when a node pauses (waiting for additional data) */\n onNodePause?: (event: FlowEventNodePause) => void;\n /** Called when a paused node resumes execution */\n onNodeResume?: (event: FlowEventNodeResume) => void;\n /** Called when a node encounters an error */\n onNodeError?: (event: FlowEventNodeError) => void;\n}\n\n/**\n * Structured hook for handling flow execution events with type-safe callbacks.\n *\n * This hook provides a clean API for listening to specific flow events without\n * needing to manually filter events or use type guards.\n *\n * Must be used within UploadistaProvider.\n *\n * @param options - Object with optional callbacks for each flow event type\n *\n * @example\n * ```tsx\n * import { useFlowEvents } from '@uploadista/react';\n *\n * function FlowMonitor() {\n * useFlowEvents({\n * onFlowStart: (event) => {\n * console.log('Flow started:', event.flowId);\n * },\n * onNodeStart: (event) => {\n * console.log('Node started:', event.nodeName);\n * },\n * onNodeEnd: (event) => {\n * console.log('Node completed:', event.nodeName, event.result);\n * },\n * onFlowEnd: (event) => {\n * console.log('Flow completed with outputs:', event.outputs);\n * },\n * onFlowError: (event) => {\n * console.error('Flow failed:', event.error);\n * },\n * });\n *\n * return <div>Monitoring flow execution...</div>;\n * }\n * ```\n */\nexport function useFlowEvents(options: UseFlowEventsOptions): void {\n const { subscribeToEvents } = useUploadistaContext();\n\n useEffect(() => {\n const unsubscribe = subscribeToEvents((event) => {\n // Only handle flow events\n if (!isFlowEvent(event)) return;\n\n // Route to appropriate callback based on event type\n switch (event.eventType) {\n case EventType.JobStart:\n options.onJobStart?.(event);\n break;\n case EventType.JobEnd:\n options.onJobEnd?.(event);\n break;\n case EventType.FlowStart:\n options.onFlowStart?.(event);\n break;\n case EventType.FlowEnd:\n options.onFlowEnd?.(event);\n break;\n case EventType.FlowError:\n options.onFlowError?.(event);\n break;\n case EventType.FlowPause:\n options.onFlowPause?.(event);\n break;\n case EventType.FlowCancel:\n options.onFlowCancel?.(event);\n break;\n case EventType.NodeStart:\n options.onNodeStart?.(event);\n break;\n case EventType.NodeEnd:\n options.onNodeEnd?.(event);\n break;\n case EventType.NodePause:\n options.onNodePause?.(event);\n break;\n case EventType.NodeResume:\n options.onNodeResume?.(event);\n break;\n case EventType.NodeError:\n options.onNodeError?.(event);\n break;\n }\n });\n\n return unsubscribe;\n }, [subscribeToEvents, options]);\n}\n","import { UploadEventType, type UploadEvent } from \"@uploadista/core/types\";\nimport { useEffect } from \"react\";\nimport { useUploadistaContext } from \"../components/uploadista-provider\";\nimport { isUploadEvent } from \"./event-utils\";\n\n/**\n * Upload progress event data\n */\nexport interface UploadProgressEventData {\n id: string;\n progress: number;\n total: number;\n flow?: {\n flowId: string;\n nodeId: string;\n jobId: string;\n };\n}\n\n/**\n * Upload started/complete event data (contains full UploadFile)\n */\nexport interface UploadFileEventData {\n // This will contain the full UploadFile schema\n [key: string]: unknown;\n flow?: {\n flowId: string;\n nodeId: string;\n jobId: string;\n };\n}\n\n/**\n * Upload failed event data\n */\nexport interface UploadFailedEventData {\n id: string;\n error: string;\n flow?: {\n flowId: string;\n nodeId: string;\n jobId: string;\n };\n}\n\n/**\n * Upload validation success event data\n */\nexport interface UploadValidationSuccessEventData {\n id: string;\n validationType: \"checksum\" | \"mimetype\";\n algorithm?: string;\n flow?: {\n flowId: string;\n nodeId: string;\n jobId: string;\n };\n}\n\n/**\n * Upload validation failed event data\n */\nexport interface UploadValidationFailedEventData {\n id: string;\n reason: string;\n expected: string;\n actual: string;\n flow?: {\n flowId: string;\n nodeId: string;\n jobId: string;\n };\n}\n\n/**\n * Upload validation warning event data\n */\nexport interface UploadValidationWarningEventData {\n id: string;\n message: string;\n flow?: {\n flowId: string;\n nodeId: string;\n jobId: string;\n };\n}\n\n/**\n * Options for handling upload events.\n *\n * All callbacks are optional - only provide handlers for events you care about.\n */\nexport interface UseUploadEventsOptions {\n /** Called when an upload starts */\n onUploadStarted?: (data: UploadFileEventData) => void;\n /** Called with upload progress updates */\n onUploadProgress?: (data: UploadProgressEventData) => void;\n /** Called when an upload completes successfully */\n onUploadComplete?: (data: UploadFileEventData) => void;\n /** Called when an upload fails */\n onUploadFailed?: (data: UploadFailedEventData) => void;\n /** Called when upload validation succeeds */\n onUploadValidationSuccess?: (data: UploadValidationSuccessEventData) => void;\n /** Called when upload validation fails */\n onUploadValidationFailed?: (data: UploadValidationFailedEventData) => void;\n /** Called when upload validation produces a warning */\n onUploadValidationWarning?: (data: UploadValidationWarningEventData) => void;\n}\n\n/**\n * Structured hook for handling upload events with type-safe callbacks.\n *\n * This hook provides a clean API for listening to specific upload events without\n * needing to manually filter events or use type guards.\n *\n * Must be used within UploadistaProvider.\n *\n * @param options - Object with optional callbacks for each upload event type\n *\n * @example\n * ```tsx\n * import { useUploadEvents } from '@uploadista/react';\n *\n * function UploadMonitor() {\n * useUploadEvents({\n * onUploadStarted: (data) => {\n * console.log('Upload started:', data.id);\n * },\n * onUploadProgress: (data) => {\n * const percent = (data.progress / data.total) * 100;\n * console.log(`Upload progress: ${percent}%`);\n * },\n * onUploadComplete: (data) => {\n * console.log('Upload completed:', data);\n * },\n * onUploadFailed: (data) => {\n * console.error('Upload failed:', data.error);\n * },\n * });\n *\n * return <div>Monitoring uploads...</div>;\n * }\n * ```\n */\nexport function useUploadEvents(options: UseUploadEventsOptions): void {\n const { subscribeToEvents } = useUploadistaContext();\n\n useEffect(() => {\n const unsubscribe = subscribeToEvents((event) => {\n // Only handle upload events\n if (!isUploadEvent(event)) return;\n\n // Route to appropriate callback based on event type\n // Note: flow context is at the top level of the event, not inside data\n const flowContext = \"flow\" in event ? event.flow : undefined;\n\n switch (event.type) {\n case UploadEventType.UPLOAD_STARTED:\n options.onUploadStarted?.({\n ...(event.data as unknown as Omit<UploadFileEventData, \"flow\">),\n flow: flowContext,\n });\n break;\n case UploadEventType.UPLOAD_PROGRESS:\n options.onUploadProgress?.({\n ...(event.data as unknown as Omit<\n UploadProgressEventData,\n \"flow\"\n >),\n flow: flowContext,\n });\n break;\n case UploadEventType.UPLOAD_COMPLETE:\n options.onUploadComplete?.({\n ...(event.data as unknown as Omit<UploadFileEventData, \"flow\">),\n flow: flowContext,\n });\n break;\n case UploadEventType.UPLOAD_FAILED:\n options.onUploadFailed?.({\n ...(event.data as unknown as Omit<UploadFailedEventData, \"flow\">),\n flow: flowContext,\n });\n break;\n case UploadEventType.UPLOAD_VALIDATION_SUCCESS:\n options.onUploadValidationSuccess?.({\n ...(event.data as unknown as Omit<\n UploadValidationSuccessEventData,\n \"flow\"\n >),\n flow: flowContext,\n });\n break;\n case UploadEventType.UPLOAD_VALIDATION_FAILED:\n options.onUploadValidationFailed?.({\n ...(event.data as unknown as Omit<\n UploadValidationFailedEventData,\n \"flow\"\n >),\n flow: flowContext,\n });\n break;\n case UploadEventType.UPLOAD_VALIDATION_WARNING:\n options.onUploadValidationWarning?.({\n ...(event.data as unknown as Omit<\n UploadValidationWarningEventData,\n \"flow\"\n >),\n flow: flowContext,\n });\n break;\n }\n });\n\n return unsubscribe;\n }, [subscribeToEvents, options]);\n}\n","import type { FlowUploadOptions } from \"@uploadista/client-browser\";\nimport type {\n FlowManager,\n FlowUploadState,\n FlowUploadStatus,\n InputExecutionState,\n} from \"@uploadista/client-core\";\nimport type { TypedOutput } from \"@uploadista/core/flow\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport { useUploadistaContext } from \"../components/uploadista-provider\";\nimport { useFlowManagerContext } from \"../contexts/flow-manager-context\";\n\n// Re-export types from core for convenience\nexport type { FlowUploadState, FlowUploadStatus, InputExecutionState };\n\n/**\n * Input metadata discovered from the flow\n */\nexport interface FlowInputMetadata {\n /** Input node ID */\n nodeId: string;\n /** Human-readable node name */\n nodeName: string;\n /** Node description explaining what input is needed */\n nodeDescription: string;\n /** Input type ID from inputTypeRegistry - describes how clients interact with this node */\n inputTypeId?: string;\n /** Whether this input is required */\n required: boolean;\n}\n\n/**\n * Return value from the useFlow hook with upload control methods and state.\n *\n * @property state - Complete flow upload state with progress and outputs\n * @property inputMetadata - Metadata about discovered input nodes (null until discovered)\n * @property inputStates - Per-input execution state for multi-input flows\n * @property inputs - Current input values set via setInput()\n * @property setInput - Set an input value for a specific node (for progressive provision)\n * @property execute - Execute the flow with current inputs (auto-detects types)\n * @property upload - Convenience method for single-file upload (same as execute with one file input)\n * @property abort - Cancel the current upload and flow execution\n * @property pause - Pause the current upload\n * @property reset - Reset state to idle (clears all data)\n * @property isUploading - True when upload or processing is active\n * @property isUploadingFile - True only during file upload phase\n * @property isProcessing - True only during flow processing phase\n * @property isDiscoveringInputs - True while discovering flow inputs\n */\nexport interface UseFlowReturn {\n /**\n * Current upload state\n */\n state: FlowUploadState;\n\n /**\n * Discovered input nodes metadata (null until discovery completes)\n */\n inputMetadata: FlowInputMetadata[] | null;\n\n /**\n * Per-input execution state for multi-input flows\n */\n inputStates: ReadonlyMap<string, InputExecutionState>;\n\n /**\n * Current inputs set via setInput()\n */\n inputs: Record<string, unknown>;\n\n /**\n * Set an input value for a specific node.\n * For progressive input provision before calling execute().\n *\n * @param nodeId - The input node ID\n * @param value - The input value (File, URL string, or structured data)\n */\n setInput: (nodeId: string, value: unknown) => void;\n\n /**\n * Execute the flow with current inputs.\n * Automatically detects input types and routes appropriately.\n * For single input, uses standard upload path.\n * For multiple inputs, requires multiInputUploadFn.\n */\n execute: () => Promise<void>;\n\n /**\n * Upload a single file through the flow (convenience method).\n * Equivalent to setInput(firstNodeId, file) + execute().\n *\n * @param file - File or Blob to upload\n */\n upload: (file: File | Blob) => Promise<void>;\n\n /**\n * Abort the current upload\n */\n abort: () => void;\n\n /**\n * Pause the current upload\n */\n pause: () => void;\n\n /**\n * Reset the upload state and clear all inputs\n */\n reset: () => void;\n\n /**\n * Whether an upload or flow execution is in progress (uploading OR processing)\n */\n isUploading: boolean;\n\n /**\n * Whether the file is currently being uploaded (chunks being sent)\n */\n isUploadingFile: boolean;\n\n /**\n * Whether the flow is currently processing (after upload completes)\n */\n isProcessing: boolean;\n\n /**\n * Whether the hook is discovering flow inputs\n */\n isDiscoveringInputs: boolean;\n}\n\nconst initialState: FlowUploadState = {\n status: \"idle\",\n progress: 0,\n bytesUploaded: 0,\n totalBytes: null,\n error: null,\n jobId: null,\n flowStarted: false,\n currentNodeName: null,\n currentNodeType: null,\n flowOutputs: null,\n};\n\n/**\n * React hook for executing flows with single or multiple inputs.\n * Automatically discovers input nodes and detects input types (File, URL, structured data).\n * Supports progressive input provision via setInput() and execute().\n *\n * This is the unified flow hook that replaces useFlowUpload for advanced use cases.\n * It provides:\n * - Auto-discovery of flow input nodes\n * - Automatic input type detection (file → upload, string → URL, object → data)\n * - Progressive input provision via setInput()\n * - Multi-input support with parallel coordination\n * - Per-input state tracking\n *\n * Must be used within FlowManagerProvider (which must be within UploadistaProvider).\n * Flow events are automatically routed by the provider to the appropriate manager.\n *\n * @param options - Flow upload configuration including flow ID and event handlers\n * @returns Flow upload state and control methods\n *\n * @example\n * ```tsx\n * // Single file upload (simple case)\n * function SingleFileUploader() {\n * const flow = useFlow({\n * flowConfig: {\n * flowId: \"image-optimization\",\n * storageId: \"s3-images\",\n * },\n * onSuccess: (outputs) => {\n * console.log(\"Flow outputs:\", outputs);\n * },\n * });\n *\n * return (\n * <div>\n * <input\n * type=\"file\"\n * onChange={(e) => {\n * const file = e.target.files?.[0];\n * if (file) flow.upload(file);\n * }}\n * />\n * {flow.isUploading && <div>Progress: {flow.state.progress}%</div>}\n * </div>\n * );\n * }\n *\n * // Multi-input with progressive provision\n * function MultiInputFlow() {\n * const flow = useFlow({\n * flowConfig: {\n * flowId: \"multi-source-processing\",\n * storageId: \"default\",\n * },\n * });\n *\n * return (\n * <div>\n * {flow.inputMetadata?.map((input) => (\n * <div key={input.nodeId}>\n * <label>{input.nodeId}</label>\n * {input.nodeType === \"streaming-input-v1\" ? (\n * <input\n * type=\"file\"\n * onChange={(e) => {\n * const file = e.target.files?.[0];\n * if (file) flow.setInput(input.nodeId, file);\n * }}\n * />\n * ) : (\n * <input\n * type=\"url\"\n * onChange={(e) => flow.setInput(input.nodeId, e.target.value)}\n * />\n * )}\n * </div>\n * ))}\n * <button onClick={flow.execute} disabled={flow.isUploading}>\n * Execute Flow\n * </button>\n *\n * {flow.isUploading && (\n * <div>\n * {Array.from(flow.inputStates.values()).map((inputState) => (\n * <div key={inputState.nodeId}>\n * {inputState.nodeId}: {inputState.status} ({inputState.progress}%)\n * </div>\n * ))}\n * </div>\n * )}\n * </div>\n * );\n * }\n * ```\n *\n * @see {@link useFlowUpload} for a simpler file-only upload hook\n */\nexport function useFlow(options: FlowUploadOptions): UseFlowReturn {\n const { client } = useUploadistaContext();\n const { getManager, releaseManager } = useFlowManagerContext();\n const [state, setState] = useState<FlowUploadState>(initialState);\n const [inputMetadata, setInputMetadata] = useState<\n FlowInputMetadata[] | null\n >(null);\n const [isDiscoveringInputs, setIsDiscoveringInputs] = useState(false);\n const [inputs, setInputs] = useState<Record<string, unknown>>({});\n const [inputStates, setInputStates] = useState<\n ReadonlyMap<string, InputExecutionState>\n >(new Map());\n const managerRef = useRef<FlowManager<unknown> | null>(null);\n\n // Store callbacks in refs so they can be updated without recreating the manager\n const callbacksRef = useRef(options);\n\n // Update refs on every render to capture latest callbacks\n useEffect(() => {\n callbacksRef.current = options;\n });\n\n // Auto-discover flow inputs on mount\n useEffect(() => {\n const discoverInputs = async () => {\n setIsDiscoveringInputs(true);\n try {\n const { flow } = await client.getFlow(options.flowConfig.flowId);\n\n // Find all input nodes\n const inputNodes = flow.nodes.filter((node) => node.type === \"input\");\n\n console.log(\"inputNodes\", inputNodes);\n\n const metadata: FlowInputMetadata[] = inputNodes.map((node) => ({\n nodeId: node.id,\n nodeName: node.name,\n nodeDescription: node.description,\n inputTypeId: node.inputTypeId,\n // TODO: Add required field to node schema to determine if input is required\n required: true,\n }));\n\n setInputMetadata(metadata);\n } catch (error) {\n console.error(\"Failed to discover flow inputs:\", error);\n } finally {\n setIsDiscoveringInputs(false);\n }\n };\n\n discoverInputs();\n }, [client, options.flowConfig.flowId]);\n\n // Get or create manager from context when component mounts\n useEffect(() => {\n const flowId = options.flowConfig.flowId;\n\n // Create stable callback wrappers that call the latest callbacks via refs\n const stableCallbacks = {\n onStateChange: (newState: FlowUploadState) => {\n setState(newState);\n },\n onProgress: (\n uploadId: string,\n bytesUploaded: number,\n totalBytes: number | null,\n ) => {\n callbacksRef.current.onProgress?.(uploadId, bytesUploaded, totalBytes);\n },\n onChunkComplete: (\n chunkSize: number,\n bytesAccepted: number,\n bytesTotal: number | null,\n ) => {\n callbacksRef.current.onChunkComplete?.(\n chunkSize,\n bytesAccepted,\n bytesTotal,\n );\n },\n onFlowComplete: (outputs: TypedOutput[]) => {\n callbacksRef.current.onFlowComplete?.(outputs);\n },\n onSuccess: (outputs: TypedOutput[]) => {\n callbacksRef.current.onSuccess?.(outputs);\n },\n onError: (error: Error) => {\n callbacksRef.current.onError?.(error);\n },\n onAbort: () => {\n callbacksRef.current.onAbort?.();\n },\n };\n\n // Get manager from context (creates if doesn't exist, increments ref count)\n managerRef.current = getManager(flowId, stableCallbacks, options);\n\n // Set up interval to poll input states for multi-input flows\n const pollInterval = setInterval(() => {\n if (managerRef.current) {\n const states = managerRef.current.getInputStates();\n if (states.size > 0) {\n setInputStates(new Map(states));\n }\n }\n }, 100); // Poll every 100ms\n\n // Release manager when component unmounts or flowId changes\n return () => {\n clearInterval(pollInterval);\n releaseManager(flowId);\n managerRef.current = null;\n };\n }, [\n options.flowConfig.flowId,\n options.flowConfig.storageId,\n options.flowConfig.outputNodeId,\n getManager,\n releaseManager,\n ]);\n\n // Set an input value\n const setInput = useCallback((nodeId: string, value: unknown) => {\n setInputs((prev) => ({ ...prev, [nodeId]: value }));\n }, []);\n\n // Execute flow with current inputs\n const execute = useCallback(async () => {\n if (!managerRef.current) {\n throw new Error(\"FlowManager not initialized\");\n }\n\n if (Object.keys(inputs).length === 0) {\n throw new Error(\n \"No inputs provided. Use setInput() to provide inputs before calling execute()\",\n );\n }\n\n await managerRef.current.executeFlow(inputs);\n }, [inputs]);\n\n // Convenience method for single file upload\n const upload = useCallback(\n async (file: File | Blob) => {\n if (!managerRef.current) {\n throw new Error(\"FlowManager not initialized\");\n }\n\n // If we have input metadata, use the first input node\n // Otherwise, let the manager discover it\n if (inputMetadata && inputMetadata.length > 0) {\n const firstInputNode = inputMetadata[0];\n if (!firstInputNode) {\n throw new Error(\"No input nodes found\");\n }\n setInputs({ [firstInputNode.nodeId]: file });\n await managerRef.current.executeFlow({ [firstInputNode.nodeId]: file });\n } else {\n // Fall back to direct upload (manager will handle discovery)\n await managerRef.current.upload(file);\n }\n },\n [inputMetadata],\n );\n\n const abort = useCallback(() => {\n managerRef.current?.abort();\n }, []);\n\n const pause = useCallback(() => {\n managerRef.current?.pause();\n }, []);\n\n const reset = useCallback(() => {\n managerRef.current?.reset();\n setInputs({});\n setInputStates(new Map());\n }, []);\n\n // Derive computed values from state (reactive to state changes)\n const isUploading =\n state.status === \"uploading\" || state.status === \"processing\";\n const isUploadingFile = state.status === \"uploading\";\n const isProcessing = state.status === \"processing\";\n\n return {\n state,\n inputMetadata,\n inputStates,\n inputs,\n setInput,\n execute,\n upload,\n abort,\n pause,\n reset,\n isUploading,\n isUploadingFile,\n isProcessing,\n isDiscoveringInputs,\n };\n}\n","/**\n * Generic React hook for flexible flow execution with arbitrary input types.\n *\n * This hook provides a flexible interface for executing flows with different input types:\n * - File/Blob: Traditional chunked file upload\n * - string (URL): Direct file fetch from external URL\n * - object: Structured data for custom input nodes\n *\n * The hook uses an inputBuilder pattern to transform trigger data into flow inputs,\n * enabling dynamic input preparation and validation before flow execution.\n *\n * @module hooks/use-flow-execution\n *\n * @example\n * ```tsx\n * // URL-based flow execution\n * function UrlImageProcessor() {\n * const execution = useFlowExecution<string>({\n * flowConfig: {\n * flowId: \"image-optimize\",\n * storageId: \"s3\"\n * },\n * inputBuilder: async (url) => {\n * // Find the input node\n * const { inputNodes, single } = await client.findInputNode(\"image-optimize\");\n * if (!single) throw new Error(\"Expected single input node\");\n *\n * return {\n * [inputNodes[0].id]: {\n * operation: \"url\",\n * url,\n * metadata: { source: \"external\" }\n * }\n * };\n * },\n * onSuccess: (outputs) => console.log(\"Done:\", outputs)\n * });\n *\n * return (\n * <button onClick={() => execution.execute(\"https://example.com/image.jpg\")}>\n * Process URL\n * </button>\n * );\n * }\n * ```\n */\n\nimport type { FlowUploadOptions } from \"@uploadista/client-browser\";\nimport type {\n FlowInputs,\n FlowManager,\n FlowUploadState,\n FlowUploadStatus,\n} from \"@uploadista/client-core\";\nimport type { TypedOutput } from \"@uploadista/core/flow\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport { useUploadistaContext } from \"../components/uploadista-provider\";\nimport { useFlowManagerContext } from \"../contexts/flow-manager-context\";\n\n// Re-export types for convenience\nexport type { FlowUploadState, FlowUploadStatus };\n\n/**\n * Input builder function that transforms trigger data into flow inputs.\n *\n * The builder receives the trigger data passed to execute() and returns\n * a FlowInputs object mapping node IDs to their input data.\n *\n * @template TTrigger - The type of data passed to execute()\n * @param trigger - The trigger data (e.g., File, URL string, structured data)\n * @returns Promise resolving to FlowInputs mapping or the mapping directly\n *\n * @example\n * ```typescript\n * // File upload builder\n * const fileBuilder: InputBuilder<File> = async (file) => ({\n * \"input-node\": {\n * operation: \"init\",\n * storageId: \"s3\",\n * metadata: { originalName: file.name, size: file.size }\n * }\n * });\n *\n * // URL fetch builder\n * const urlBuilder: InputBuilder<string> = (url) => ({\n * \"input-node\": {\n * operation: \"url\",\n * url,\n * metadata: { source: \"external\" }\n * }\n * });\n * ```\n */\nexport type InputBuilder<TTrigger = unknown> = (\n trigger: TTrigger,\n) => Promise<FlowInputs> | FlowInputs;\n\n/**\n * Options for the useFlowExecution hook.\n *\n * @template TTrigger - The type of trigger data passed to execute()\n * @template TOutput - The expected output type from the flow\n *\n * @property flowConfig - Flow configuration (flowId, storageId, etc.)\n * @property inputBuilder - Function to build flow inputs from trigger data\n * @property onJobStart - Called when flow job is created\n * @property onProgress - Called during upload progress (if applicable)\n * @property onChunkComplete - Called when upload chunk completes (if applicable)\n * @property onSuccess - Called with typed outputs when flow succeeds\n * @property onFlowComplete - Called with all outputs when flow completes\n * @property onError - Called when execution fails\n * @property onAbort - Called when execution is aborted\n * @property onShouldRetry - Custom retry logic (if applicable)\n */\nexport interface UseFlowExecutionOptions<\n TTrigger = unknown,\n TOutput = TypedOutput[],\n> {\n /**\n * Flow configuration\n */\n flowConfig: FlowUploadOptions[\"flowConfig\"];\n\n /**\n * Function to build flow inputs from trigger data.\n * Can be async to perform validation, API calls, etc.\n */\n inputBuilder: InputBuilder<TTrigger>;\n\n /**\n * Called when the flow job starts\n */\n onJobStart?: (jobId: string) => void;\n\n /**\n * Called during upload progress (for file uploads)\n */\n onProgress?: (\n uploadId: string,\n bytesUploaded: number,\n totalBytes: number | null,\n ) => void;\n\n /**\n * Called when an upload chunk completes (for file uploads)\n */\n onChunkComplete?: (\n chunkSize: number,\n bytesAccepted: number,\n bytesTotal: number | null,\n ) => void;\n\n /**\n * Called when flow execution succeeds with final outputs\n */\n onSuccess?: (outputs: TOutput) => void;\n\n /**\n * Called when flow completes (alternative to onSuccess)\n */\n onFlowComplete?: (outputs: TypedOutput[]) => void;\n\n /**\n * Called when execution fails\n */\n onError?: (error: Error) => void;\n\n /**\n * Called when execution is aborted\n */\n onAbort?: () => void;\n\n /**\n * Custom retry logic (for file uploads)\n */\n onShouldRetry?: (error: Error, retryAttempt: number) => boolean;\n}\n\n/**\n * Return value from useFlowExecution hook.\n *\n * @template TTrigger - The type of trigger data passed to execute()\n *\n * @property state - Current execution state with progress and outputs\n * @property execute - Function to trigger flow execution\n * @property abort - Cancel the current execution\n * @property pause - Pause the current execution (for file uploads)\n * @property reset - Reset state to idle\n * @property isExecuting - True when execution is active\n * @property isUploadingFile - True during file upload phase\n * @property isProcessing - True during flow processing phase\n */\nexport interface UseFlowExecutionReturn<TTrigger = unknown> {\n /**\n * Current execution state\n */\n state: FlowUploadState;\n\n /**\n * Execute the flow with trigger data\n */\n execute: (trigger: TTrigger) => Promise<void>;\n\n /**\n * Abort the current execution\n */\n abort: () => void;\n\n /**\n * Pause the current execution (if supported by input type)\n */\n pause: () => void;\n\n /**\n * Reset the execution state\n */\n reset: () => void;\n\n /**\n * Whether execution is active (uploading OR processing)\n */\n isExecuting: boolean;\n\n /**\n * Whether file upload is in progress\n */\n isUploadingFile: boolean;\n\n /**\n * Whether flow processing is in progress\n */\n isProcessing: boolean;\n}\n\nconst initialState: FlowUploadState = {\n status: \"idle\",\n progress: 0,\n bytesUploaded: 0,\n totalBytes: null,\n error: null,\n jobId: null,\n flowStarted: false,\n currentNodeName: null,\n currentNodeType: null,\n flowOutputs: null,\n};\n\n/**\n * Generic React hook for flexible flow execution.\n *\n * Provides a flexible interface for executing flows with arbitrary input types\n * through an inputBuilder pattern. The builder transforms trigger data into\n * flow inputs, enabling support for files, URLs, structured data, and more.\n *\n * Must be used within FlowManagerProvider (which must be within UploadistaProvider).\n *\n * @template TTrigger - The type of trigger data passed to execute()\n * @template TOutput - The expected output type from the flow\n *\n * @param options - Flow execution configuration with inputBuilder\n * @returns Execution state and control methods\n *\n * @example\n * ```tsx\n * // URL-based image processing\n * const urlExecution = useFlowExecution<string>({\n * flowConfig: { flowId: \"optimize\", storageId: \"s3\" },\n * inputBuilder: async (url) => {\n * const { inputNodes } = await client.findInputNode(\"optimize\");\n * return {\n * [inputNodes[0].id]: {\n * operation: \"url\",\n * url,\n * metadata: { source: \"external\" }\n * }\n * };\n * },\n * onSuccess: (outputs) => console.log(\"Processed:\", outputs)\n * });\n *\n * // Execute with URL\n * await urlExecution.execute(\"https://example.com/image.jpg\");\n *\n * // File upload (traditional pattern)\n * const fileExecution = useFlowExecution<File>({\n * flowConfig: { flowId: \"optimize\", storageId: \"s3\" },\n * inputBuilder: async (file) => {\n * const { inputNodes } = await client.findInputNode(\"optimize\");\n * return {\n * [inputNodes[0].id]: {\n * operation: \"init\",\n * storageId: \"s3\",\n * metadata: {\n * originalName: file.name,\n * mimeType: file.type,\n * size: file.size\n * }\n * }\n * };\n * }\n * });\n *\n * // Execute with file\n * await fileExecution.execute(myFile);\n * ```\n */\nexport function useFlowExecution<TTrigger = unknown, TOutput = TypedOutput[]>(\n options: UseFlowExecutionOptions<TTrigger, TOutput>,\n): UseFlowExecutionReturn<TTrigger> {\n const { client } = useUploadistaContext();\n const { getManager, releaseManager } = useFlowManagerContext();\n const [state, setState] = useState<FlowUploadState>(initialState);\n const managerRef = useRef<FlowManager<unknown> | null>(null);\n\n // Store callbacks and inputBuilder in refs for stable access\n const callbacksRef = useRef(options);\n const inputBuilderRef = useRef(options.inputBuilder);\n\n // Update refs when options change\n useEffect(() => {\n callbacksRef.current = options;\n inputBuilderRef.current = options.inputBuilder;\n });\n\n // Get or create manager from context\n useEffect(() => {\n const flowId = options.flowConfig.flowId;\n\n // Create stable callback wrappers\n const stableCallbacks = {\n onStateChange: setState,\n onProgress: (\n uploadId: string,\n bytesUploaded: number,\n totalBytes: number | null,\n ) => {\n callbacksRef.current.onProgress?.(uploadId, bytesUploaded, totalBytes);\n },\n onChunkComplete: (\n chunkSize: number,\n bytesAccepted: number,\n bytesTotal: number | null,\n ) => {\n callbacksRef.current.onChunkComplete?.(\n chunkSize,\n bytesAccepted,\n bytesTotal,\n );\n },\n onFlowComplete: (outputs: TypedOutput[]) => {\n callbacksRef.current.onFlowComplete?.(outputs);\n },\n onSuccess: (outputs: TypedOutput[]) => {\n callbacksRef.current.onSuccess?.(outputs as TOutput);\n },\n onError: (error: Error) => {\n callbacksRef.current.onError?.(error);\n },\n onAbort: () => {\n callbacksRef.current.onAbort?.();\n },\n };\n\n // Get or create manager for this flow\n const manager = getManager(flowId, stableCallbacks, {\n flowConfig: options.flowConfig,\n });\n managerRef.current = manager;\n\n return () => {\n if (managerRef.current) {\n releaseManager(flowId);\n managerRef.current = null;\n }\n };\n }, [options.flowConfig.flowId, getManager, releaseManager, options]);\n\n /**\n * Execute the flow with trigger data.\n * Calls inputBuilder to transform trigger into flow inputs.\n */\n const execute = useCallback(async (trigger: TTrigger) => {\n try {\n // Build flow inputs from trigger data\n const flowInputs = await inputBuilderRef.current(trigger);\n\n // For now, we need to determine if this is a file upload or URL operation\n // by inspecting the flowInputs structure\n const firstInputNodeId = Object.keys(flowInputs)[0];\n if (!firstInputNodeId) {\n throw new Error(\"flowInputs must contain at least one input node\");\n }\n const firstInput = flowInputs[firstInputNodeId];\n\n // Type guard: check if this is an init operation (file upload)\n const isFileUpload =\n typeof firstInput === \"object\" &&\n firstInput !== null &&\n \"operation\" in firstInput &&\n firstInput.operation === \"init\";\n\n if (isFileUpload) {\n // File upload path: use the standard upload mechanism\n // This requires the trigger to be a File/Blob\n if (managerRef.current) {\n await managerRef.current.upload(trigger as unknown);\n }\n } else {\n // Non-file path (URL, structured data, etc.)\n // Skip chunked upload and execute flow directly with provided inputs\n setState((prev) => ({\n ...prev,\n status: \"processing\",\n flowStarted: true,\n }));\n\n // Execute flow with the built inputs\n const result = await client.executeFlowWithInputs(\n options.flowConfig.flowId,\n flowInputs,\n {\n storageId: options.flowConfig.storageId,\n onJobStart: (jobId: string) => {\n setState((prev) => ({\n ...prev,\n jobId,\n }));\n callbacksRef.current.onJobStart?.(jobId);\n },\n },\n );\n\n // If job was created successfully, the FlowManager will handle\n // flow events via WebSocket and update state accordingly\n if (result.job?.id) {\n // State updates will come from flow events\n // Manager will receive FlowEnd event and update state to \"success\"\n } else {\n // No job created - treat as immediate completion\n setState((prev) => ({\n ...prev,\n status: \"success\",\n progress: 100,\n flowStarted: true,\n }));\n }\n }\n } catch (error) {\n // Handle inputBuilder errors\n const err = error instanceof Error ? error : new Error(String(error));\n setState((prev) => ({\n ...prev,\n status: \"error\",\n error: err,\n }));\n callbacksRef.current.onError?.(err);\n }\n }, []);\n\n /**\n * Abort the current execution\n */\n const abort = useCallback(() => {\n if (managerRef.current) {\n managerRef.current.abort();\n }\n }, []);\n\n /**\n * Pause the current execution\n */\n const pause = useCallback(() => {\n if (managerRef.current) {\n managerRef.current.pause();\n }\n }, []);\n\n /**\n * Reset the execution state\n */\n const reset = useCallback(() => {\n if (managerRef.current) {\n const flowId = options.flowConfig.flowId;\n managerRef.current.reset();\n managerRef.current.cleanup();\n releaseManager(flowId);\n managerRef.current = null;\n }\n setState(initialState);\n }, [options.flowConfig.flowId, releaseManager]);\n\n return {\n state,\n execute,\n abort,\n pause,\n reset,\n isExecuting: state.status === \"uploading\" || state.status === \"processing\",\n isUploadingFile: state.status === \"uploading\",\n isProcessing: state.status === \"processing\",\n };\n}\n","import type {\n ChunkMetrics,\n PerformanceInsights,\n UploadSessionMetrics,\n} from \"@uploadista/client-core\";\nimport React, { useCallback, useRef, useState } from \"react\";\nimport { useUploadistaContext } from \"../components/uploadista-provider\";\n\nexport type Timeout = ReturnType<typeof setInterval>;\n\nexport interface UploadMetrics {\n /**\n * Total bytes uploaded across all files\n */\n totalBytesUploaded: number;\n\n /**\n * Total bytes to upload across all files\n */\n totalBytes: number;\n\n /**\n * Overall upload speed in bytes per second\n */\n averageSpeed: number;\n\n /**\n * Current upload speed in bytes per second\n */\n currentSpeed: number;\n\n /**\n * Estimated time remaining in milliseconds\n */\n estimatedTimeRemaining: number | null;\n\n /**\n * Total number of files being tracked\n */\n totalFiles: number;\n\n /**\n * Number of files completed\n */\n completedFiles: number;\n\n /**\n * Number of files currently uploading\n */\n activeUploads: number;\n\n /**\n * Overall progress as percentage (0-100)\n */\n progress: number;\n\n /**\n * Peak upload speed achieved\n */\n peakSpeed: number;\n\n /**\n * Start time of the first upload\n */\n startTime: number | null;\n\n /**\n * End time of the last completed upload\n */\n endTime: number | null;\n\n /**\n * Total duration of all uploads\n */\n totalDuration: number | null;\n\n /**\n * Detailed performance insights from the upload client\n */\n insights: PerformanceInsights;\n\n /**\n * Session metrics for completed uploads\n */\n sessionMetrics: Partial<UploadSessionMetrics>[];\n\n /**\n * Detailed chunk metrics from recent uploads\n */\n chunkMetrics: ChunkMetrics[];\n}\n\nexport interface FileUploadMetrics {\n id: string;\n filename: string;\n size: number;\n bytesUploaded: number;\n progress: number;\n speed: number;\n startTime: number;\n endTime: number | null;\n duration: number | null;\n isComplete: boolean;\n}\n\nexport interface UseUploadMetricsOptions {\n /**\n * Interval for calculating current speed (in milliseconds)\n */\n speedCalculationInterval?: number;\n\n /**\n * Number of speed samples to keep for average calculation\n */\n speedSampleSize?: number;\n\n /**\n * Called when metrics are updated\n */\n onMetricsUpdate?: (metrics: UploadMetrics) => void;\n\n /**\n * Called when a file upload starts\n */\n onFileStart?: (fileMetrics: FileUploadMetrics) => void;\n\n /**\n * Called when a file upload progresses\n */\n onFileProgress?: (fileMetrics: FileUploadMetrics) => void;\n\n /**\n * Called when a file upload completes\n */\n onFileComplete?: (fileMetrics: FileUploadMetrics) => void;\n}\n\nexport interface UseUploadMetricsReturn {\n /**\n * Current overall metrics\n */\n metrics: UploadMetrics;\n\n /**\n * Individual file metrics\n */\n fileMetrics: FileUploadMetrics[];\n\n /**\n * Start tracking a new file upload\n */\n startFileUpload: (id: string, filename: string, size: number) => void;\n\n /**\n * Update progress for a file upload\n */\n updateFileProgress: (id: string, bytesUploaded: number) => void;\n\n /**\n * Mark a file upload as complete\n */\n completeFileUpload: (id: string) => void;\n\n /**\n * Remove a file from tracking\n */\n removeFile: (id: string) => void;\n\n /**\n * Reset all metrics\n */\n reset: () => void;\n\n /**\n * Get metrics for a specific file\n */\n getFileMetrics: (id: string) => FileUploadMetrics | undefined;\n\n /**\n * Export metrics as JSON\n */\n exportMetrics: () => {\n overall: UploadMetrics;\n files: FileUploadMetrics[];\n exportTime: number;\n };\n}\n\nconst initialMetrics: UploadMetrics = {\n totalBytesUploaded: 0,\n totalBytes: 0,\n averageSpeed: 0,\n currentSpeed: 0,\n estimatedTimeRemaining: null,\n totalFiles: 0,\n completedFiles: 0,\n activeUploads: 0,\n progress: 0,\n peakSpeed: 0,\n startTime: null,\n endTime: null,\n totalDuration: null,\n insights: {\n overallEfficiency: 0,\n chunkingEffectiveness: 0,\n networkStability: 0,\n recommendations: [],\n optimalChunkSizeRange: { min: 256 * 1024, max: 2 * 1024 * 1024 },\n },\n sessionMetrics: [],\n chunkMetrics: [],\n};\n\n/**\n * React hook for tracking detailed upload metrics and performance statistics.\n * Provides comprehensive monitoring of upload progress, speed, and timing data.\n *\n * @param options - Configuration and event handlers\n * @returns Upload metrics state and control methods\n *\n * @example\n * ```tsx\n * const uploadMetrics = useUploadMetrics({\n * speedCalculationInterval: 1000, // Update speed every second\n * speedSampleSize: 10, // Keep last 10 speed samples for average\n * onMetricsUpdate: (metrics) => {\n * console.log(`Overall progress: ${metrics.progress}%`);\n * console.log(`Speed: ${(metrics.currentSpeed / 1024).toFixed(1)} KB/s`);\n * console.log(`ETA: ${metrics.estimatedTimeRemaining}ms`);\n * },\n * onFileComplete: (fileMetrics) => {\n * console.log(`${fileMetrics.filename} completed in ${fileMetrics.duration}ms`);\n * },\n * });\n *\n * // Start tracking a file\n * const handleFileStart = (file: File) => {\n * uploadMetrics.startFileUpload(file.name, file.name, file.size);\n * };\n *\n * // Update progress during upload\n * const handleProgress = (fileId: string, bytesUploaded: number) => {\n * uploadMetrics.updateFileProgress(fileId, bytesUploaded);\n * };\n *\n * // Display metrics\n * return (\n * <div>\n * <div>Overall Progress: {uploadMetrics.metrics.progress}%</div>\n * <div>Speed: {(uploadMetrics.metrics.currentSpeed / 1024).toFixed(1)} KB/s</div>\n * <div>Files: {uploadMetrics.metrics.completedFiles}/{uploadMetrics.metrics.totalFiles}</div>\n *\n * {uploadMetrics.metrics.estimatedTimeRemaining && (\n * <div>ETA: {Math.round(uploadMetrics.metrics.estimatedTimeRemaining / 1000)}s</div>\n * )}\n *\n * {uploadMetrics.fileMetrics.map((file) => (\n * <div key={file.id}>\n * {file.filename}: {file.progress}% ({(file.speed / 1024).toFixed(1)} KB/s)\n * </div>\n * ))}\n * </div>\n * );\n * ```\n */\nexport function useUploadMetrics(\n options: UseUploadMetricsOptions = {},\n): UseUploadMetricsReturn {\n const {\n speedCalculationInterval = 1000,\n speedSampleSize = 10,\n onMetricsUpdate,\n onFileStart,\n onFileProgress,\n onFileComplete,\n } = options;\n\n const uploadClient = useUploadistaContext();\n\n const [metrics, setMetrics] = useState<UploadMetrics>(initialMetrics);\n const [fileMetrics, setFileMetrics] = useState<FileUploadMetrics[]>([]);\n\n const speedSamplesRef = useRef<Array<{ time: number; bytes: number }>>([]);\n const lastUpdateRef = useRef<number>(0);\n const intervalRef = useRef<Timeout | null>(null);\n\n const calculateSpeed = useCallback(\n (currentTime: number, totalBytesUploaded: number) => {\n const sample = { time: currentTime, bytes: totalBytesUploaded };\n speedSamplesRef.current.push(sample);\n\n // Keep only recent samples\n if (speedSamplesRef.current.length > speedSampleSize) {\n speedSamplesRef.current = speedSamplesRef.current.slice(\n -speedSampleSize,\n );\n }\n\n // Calculate current speed (bytes per second)\n let currentSpeed = 0;\n if (speedSamplesRef.current.length >= 2) {\n const recent =\n speedSamplesRef.current[speedSamplesRef.current.length - 1];\n const previous =\n speedSamplesRef.current[speedSamplesRef.current.length - 2];\n if (recent && previous) {\n const timeDiff = (recent.time - previous.time) / 1000; // Convert to seconds\n const bytesDiff = recent.bytes - previous.bytes;\n currentSpeed = timeDiff > 0 ? bytesDiff / timeDiff : 0;\n }\n }\n\n // Calculate average speed\n let averageSpeed = 0;\n if (speedSamplesRef.current.length >= 2) {\n const first = speedSamplesRef.current[0];\n const last =\n speedSamplesRef.current[speedSamplesRef.current.length - 1];\n if (first && last) {\n const totalTime = (last.time - first.time) / 1000; // Convert to seconds\n const totalBytes = last.bytes - first.bytes;\n averageSpeed = totalTime > 0 ? totalBytes / totalTime : 0;\n }\n }\n\n return { currentSpeed, averageSpeed };\n },\n [speedSampleSize],\n );\n\n const updateMetrics = useCallback(() => {\n const now = Date.now();\n\n // Calculate totals from file metrics\n const totalBytes = fileMetrics.reduce((sum, file) => sum + file.size, 0);\n const totalBytesUploaded = fileMetrics.reduce(\n (sum, file) => sum + file.bytesUploaded,\n 0,\n );\n const completedFiles = fileMetrics.filter((file) => file.isComplete).length;\n const activeUploads = fileMetrics.filter(\n (file) => !file.isComplete && file.bytesUploaded > 0,\n ).length;\n\n // Calculate speeds\n const { currentSpeed, averageSpeed } = calculateSpeed(\n now,\n totalBytesUploaded,\n );\n\n // Calculate progress\n const progress =\n totalBytes > 0 ? Math.round((totalBytesUploaded / totalBytes) * 100) : 0;\n\n // Calculate estimated time remaining\n let estimatedTimeRemaining: number | null = null;\n if (currentSpeed > 0) {\n const remainingBytes = totalBytes - totalBytesUploaded;\n estimatedTimeRemaining = (remainingBytes / currentSpeed) * 1000; // Convert to milliseconds\n }\n\n // Find start and end times\n const activeTimes = fileMetrics.filter((file) => file.startTime > 0);\n const startTime =\n activeTimes.length > 0\n ? Math.min(...activeTimes.map((file) => file.startTime))\n : null;\n\n const completedTimes = fileMetrics.filter((file) => file.endTime !== null);\n const endTime =\n completedTimes.length > 0 && completedFiles === fileMetrics.length\n ? Math.max(\n ...completedTimes\n .map((file) => file.endTime)\n .filter((time) => time !== null),\n )\n : null;\n\n const totalDuration = startTime && endTime ? endTime - startTime : null;\n\n const newMetrics: UploadMetrics = {\n totalBytesUploaded,\n totalBytes,\n averageSpeed,\n currentSpeed,\n estimatedTimeRemaining,\n totalFiles: fileMetrics.length,\n completedFiles,\n activeUploads,\n progress,\n peakSpeed: Math.max(metrics.peakSpeed, currentSpeed),\n startTime,\n endTime,\n totalDuration,\n insights: uploadClient.client.getChunkingInsights(),\n sessionMetrics: [uploadClient.client.exportMetrics().session],\n chunkMetrics: uploadClient.client.exportMetrics().chunks,\n };\n\n setMetrics(newMetrics);\n onMetricsUpdate?.(newMetrics);\n }, [\n fileMetrics,\n metrics.peakSpeed,\n calculateSpeed,\n onMetricsUpdate,\n uploadClient.client,\n ]);\n\n // Set up periodic speed calculations\n const setupSpeedCalculation = useCallback(() => {\n if (intervalRef.current) {\n clearInterval(intervalRef.current);\n }\n\n intervalRef.current = setInterval(() => {\n if (\n fileMetrics.some((file) => !file.isComplete && file.bytesUploaded > 0)\n ) {\n updateMetrics();\n }\n }, speedCalculationInterval);\n\n return () => {\n if (intervalRef.current) {\n clearInterval(intervalRef.current);\n intervalRef.current = null;\n }\n };\n }, [speedCalculationInterval, updateMetrics, fileMetrics]);\n\n const startFileUpload = useCallback(\n (id: string, filename: string, size: number) => {\n const now = Date.now();\n\n const fileMetric: FileUploadMetrics = {\n id,\n filename,\n size,\n bytesUploaded: 0,\n progress: 0,\n speed: 0,\n startTime: now,\n endTime: null,\n duration: null,\n isComplete: false,\n };\n\n setFileMetrics((prev) => {\n const existing = prev.find((file) => file.id === id);\n if (existing) {\n return prev.map((file) => (file.id === id ? fileMetric : file));\n }\n return [...prev, fileMetric];\n });\n\n onFileStart?.(fileMetric);\n\n // Start speed calculation if this is the first active upload\n if (fileMetrics.filter((file) => !file.isComplete).length === 0) {\n setupSpeedCalculation();\n }\n },\n [fileMetrics, onFileStart, setupSpeedCalculation],\n );\n\n const updateFileProgress = useCallback(\n (id: string, bytesUploaded: number) => {\n const now = Date.now();\n\n setFileMetrics((prev) =>\n prev.map((file) => {\n if (file.id !== id) return file;\n\n const timeDiff = (now - file.startTime) / 1000; // seconds\n const speed = timeDiff > 0 ? bytesUploaded / timeDiff : 0;\n const progress =\n file.size > 0 ? Math.round((bytesUploaded / file.size) * 100) : 0;\n\n const updatedFile = {\n ...file,\n bytesUploaded,\n progress,\n speed,\n };\n\n onFileProgress?.(updatedFile);\n return updatedFile;\n }),\n );\n\n // Trigger metrics update\n setTimeout(updateMetrics, 0);\n },\n [onFileProgress, updateMetrics],\n );\n\n const completeFileUpload = useCallback(\n (id: string) => {\n const now = Date.now();\n\n setFileMetrics((prev) =>\n prev.map((file) => {\n if (file.id !== id) return file;\n\n const duration = now - file.startTime;\n const speed = duration > 0 ? (file.size / duration) * 1000 : 0; // bytes per second\n\n const completedFile = {\n ...file,\n bytesUploaded: file.size,\n progress: 100,\n speed,\n endTime: now,\n duration,\n isComplete: true,\n };\n\n onFileComplete?.(completedFile);\n return completedFile;\n }),\n );\n\n // Trigger metrics update\n setTimeout(updateMetrics, 0);\n },\n [onFileComplete, updateMetrics],\n );\n\n const removeFile = useCallback(\n (id: string) => {\n setFileMetrics((prev) => prev.filter((file) => file.id !== id));\n setTimeout(updateMetrics, 0);\n },\n [updateMetrics],\n );\n\n const reset = useCallback(() => {\n if (intervalRef.current) {\n clearInterval(intervalRef.current);\n intervalRef.current = null;\n }\n\n setMetrics(initialMetrics);\n setFileMetrics([]);\n speedSamplesRef.current = [];\n lastUpdateRef.current = 0;\n }, []);\n\n const getFileMetrics = useCallback(\n (id: string) => {\n return fileMetrics.find((file) => file.id === id);\n },\n [fileMetrics],\n );\n\n const exportMetrics = useCallback(() => {\n return {\n overall: metrics,\n files: fileMetrics,\n exportTime: Date.now(),\n };\n }, [metrics, fileMetrics]);\n\n // Cleanup on unmount\n React.useEffect(() => {\n return () => {\n if (intervalRef.current) {\n clearInterval(intervalRef.current);\n }\n };\n }, []);\n\n return {\n metrics,\n fileMetrics,\n startFileUpload,\n updateFileProgress,\n completeFileUpload,\n removeFile,\n reset,\n getFileMetrics,\n exportMetrics,\n };\n}\n"],"mappings":"gPAOA,SAAgB,EAAY,EAA4C,CACtE,GAAI,EAAE,cAAe,GAAQ,MAAO,GACpC,IAAM,EAAI,EACV,OACE,EAAE,YAAc,EAAU,UAC1B,EAAE,YAAc,EAAU,QAC1B,EAAE,YAAc,EAAU,WAC1B,EAAE,YAAc,EAAU,SAC1B,EAAE,YAAc,EAAU,WAC1B,EAAE,YAAc,EAAU,WAC1B,EAAE,YAAc,EAAU,YAC1B,EAAE,YAAc,EAAU,WAC1B,EAAE,YAAc,EAAU,SAC1B,EAAE,YAAc,EAAU,WAC1B,EAAE,YAAc,EAAU,YAC1B,EAAE,YAAc,EAAU,WAC1B,EAAE,YAAc,EAAU,YAC1B,EAAE,YAAc,EAAU,aAO9B,SAAgB,EAAc,EAA8C,CAC1E,GAAI,EAAE,SAAU,GAAQ,MAAO,GAC/B,IAAM,EAAI,EACV,OACE,EAAE,OAAS,EAAgB,gBAC3B,EAAE,OAAS,EAAgB,iBAC3B,EAAE,O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V,QACA,QAAS,EACT,WACA,WAAY,GACb,CAGD,OADA,IAAiB,EAAc,CACxB,GACP,CACH,CAGD,WAAW,EAAe,EAAE,EAE9B,CAAC,EAAgB,EAAc,CAChC,CAEK,EAAa,EAChB,GAAe,CACd,EAAgB,GAAS,EAAK,OAAQ,GAAS,EAAK,KAAO,EAAG,CAAC,CAC/D,WAAW,EAAe,EAAE,EAE9B,CAAC,EAAc,CAChB,CAEK,EAAQ,MAAkB,CAC9B,AAEE,EAAY,WADZ,cAAc,EAAY,QAAQ,CACZ,MAGxB,EAAW,EAAe,CAC1B,EAAe,EAAE,CAAC,CAClB,EAAgB,QAAU,EAAE,CAC5B,EAAc,QAAU,GACvB,EAAE,CAAC,CAEA,EAAiB,EACpB,GACQ,EAAY,KAAM,GAAS,EAAK,KAAO,EAAG,CAEnD,CAAC,EAAY,CACd,CAEK,EAAgB,OACb,CACL,QAAS,EACT,MAAO,EACP,WAAY,KAAK,KAAK,CACvB,EACA,CAAC,EAAS,EAAY,CAAC,CAW1B,OARA,EAAM,kBACS,CACP,EAAY,SACd,cAAc,EAAY,QAAQ,EAGrC,EAAE,CAAC,CAEC,CACL,UACA,cACA,kBACA,qBACA,qBACA,aACA,QACA,iBACA,gBACD"}
|
|
@@ -14,8 +14,8 @@ interface FlowInputMetadata {
|
|
|
14
14
|
nodeName: string;
|
|
15
15
|
/** Node description explaining what input is needed */
|
|
16
16
|
nodeDescription: string;
|
|
17
|
-
/** Input node
|
|
18
|
-
|
|
17
|
+
/** Input type ID from inputTypeRegistry - describes how clients interact with this node */
|
|
18
|
+
inputTypeId?: string;
|
|
19
19
|
/** Whether this input is required */
|
|
20
20
|
required: boolean;
|
|
21
21
|
}
|
|
@@ -912,4 +912,4 @@ interface UseUploadistaClientReturn {
|
|
|
912
912
|
declare function useUploadistaClient(options: UseUploadistaClientOptions): UseUploadistaClientReturn;
|
|
913
913
|
//#endregion
|
|
914
914
|
export { InputExecutionState as C, FlowInputMetadata as S, useFlow as T, useFlowUpload as _, MultiUploadState as a, UseDragDropReturn as b, useMultiUpload as c, UseUploadOptions as d, UseUploadReturn as f, UseFlowUploadReturn as g, FlowUploadStatus as h, MultiUploadOptions as i, UploadState as l, FlowUploadState as m, UseUploadistaClientReturn as n, UploadItem as o, useUpload as p, useUploadistaClient as r, UseMultiUploadReturn as s, UseUploadistaClientOptions as t, UploadStatus as u, DragDropOptions as v, UseFlowReturn as w, useDragDrop as x, DragDropState as y };
|
|
915
|
-
//# sourceMappingURL=use-uploadista-client-
|
|
915
|
+
//# sourceMappingURL=use-uploadista-client-m9nF-irM.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"use-uploadista-client-m9nF-irM.d.mts","names":[],"sources":["../src/hooks/use-flow.ts","../src/hooks/use-drag-drop.ts","../src/hooks/use-flow-upload.ts","../src/hooks/use-upload.ts","../src/hooks/use-multi-upload.ts","../src/hooks/use-uploadista-client.ts"],"sourcesContent":[],"mappings":";;;;;;;;AAkBA;AA+BiB,UA/BA,iBAAA,CA+Ba;EAIrB;EAKQ,MAAA,EAAA,MAAA;EAKkB;EAApB,QAAA,EAAA,MAAA;EAKL;EAiBO,eAAA,EAAA,MAAA;EAQA;EAAO,WAAA,CAAA,EAAA,MAAA;EAAS;EAAO,QAAA,EAAA,OAAA;AAoJxC;;;;AC/OA;AA0CA;AAsBA;;;;;;;;;;AA0GA;;;UD3HiB,aAAA;EExBA;;;EASO,KAAA,EFmBf,iBEnBe;EAAS;;AAkKjC;iBF1IiB;;;AG5CjB;EAIa,WAAA,EH6CE,WG7CF,CAAA,MAAA,EH6CsB,mBG7CtB,CAAA;EA2CU;;;EAqBQ,MAAA,EHdrB,MGcqB,CAAA,MAAA,EAAA,OAAA,CAAA;EAGd;;;;;AA0FjB;;;;ACxKA;AAMA;;;;EAyB2B,OAAA,EAAA,GAAA,GJ+CV,OI/CU,CAAA,IAAA,CAAA;EAAoB;;;;;;EAxBjC,MAAA,EAAA,CAAA,IAAA,EJ+EG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A;EAIW;;;EAKQ,QAAA,EAAA,CAAA,KAAA,ED8EhB,kBC9EgB,EAAA,EAAA,GAAA,IAAA;EAkEpB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;6BD8Da,iBAAiB;;;;WAKnC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAgEK,cAAA,WACL,qBACR;;;;;;;AJhOH;AA+BA;;;;;;;;;;AA4CwC,UKxEvB,0BAAA,SAAmC,uBLwEZ,CAAA;EAoJxB;;;YKxNJ;AJvBZ;AA0CA;AAsBA;;;;;AAa0B,UI7CT,yBAAA,CJ6CS;EAUc;;;EAYZ,MAAA,EI/DlB,UJ+DkB,CAAA,OI/DA,sBJ+DA,CAAA;EAuEZ;;;UIjIN;AHlBV;;;;;;AA2KA;;;;ACtLA;;;;;;AAuEA;;;;;AA0FA;;;;ACxKA;AAMA;;;;;;;;;;;;AA0CA;AAoDA;;;;;;;;AAqIA;;;;AC3NA;AAaA;;;;;AA2EA;;;;;;;iBAAgB,mBAAA,UACL,6BACR"}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@uploadista/react",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.0.
|
|
4
|
+
"version": "0.0.18-beta.1",
|
|
5
5
|
"description": "React client for Uploadista",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"author": "Uploadista",
|
|
@@ -22,16 +22,16 @@
|
|
|
22
22
|
"dependencies": {
|
|
23
23
|
"react": "19.2.0",
|
|
24
24
|
"react-dom": "19.2.0",
|
|
25
|
-
"@uploadista/core": "0.0.
|
|
26
|
-
"@uploadista/client-
|
|
27
|
-
"@uploadista/client-
|
|
25
|
+
"@uploadista/core": "0.0.18-beta.1",
|
|
26
|
+
"@uploadista/client-browser": "0.0.18-beta.1",
|
|
27
|
+
"@uploadista/client-core": "0.0.18-beta.1"
|
|
28
28
|
},
|
|
29
29
|
"devDependencies": {
|
|
30
30
|
"@types/react": "19.2.7",
|
|
31
31
|
"@types/react-dom": "19.2.3",
|
|
32
32
|
"tsdown": "0.16.6",
|
|
33
33
|
"vitest": "4.0.13",
|
|
34
|
-
"@uploadista/typescript-config": "0.0.
|
|
34
|
+
"@uploadista/typescript-config": "0.0.18-beta.1"
|
|
35
35
|
},
|
|
36
36
|
"scripts": {
|
|
37
37
|
"build": "tsdown",
|
|
@@ -54,12 +54,12 @@ export function FlowInput({
|
|
|
54
54
|
const isFileValue = value instanceof File;
|
|
55
55
|
const isUrlValue = typeof value === "string" && value.length > 0;
|
|
56
56
|
|
|
57
|
-
// Determine input mode based on
|
|
58
|
-
const supportsFileUpload = input.
|
|
57
|
+
// Determine input mode based on input type
|
|
58
|
+
const supportsFileUpload = input.inputTypeId === "streaming-input-v1";
|
|
59
59
|
const supportsUrl =
|
|
60
60
|
allowUrl &&
|
|
61
|
-
(input.
|
|
62
|
-
input.
|
|
61
|
+
(input.inputTypeId === "url-input-v1" ||
|
|
62
|
+
input.inputTypeId === "streaming-input-v1");
|
|
63
63
|
|
|
64
64
|
const dragDrop = useDragDrop({
|
|
65
65
|
onFilesReceived: (files) => {
|
|
@@ -94,7 +94,7 @@ export function FlowInput({
|
|
|
94
94
|
<h4 className="font-semibold text-gray-900">{input.nodeName}</h4>
|
|
95
95
|
{input.required && <span className="text-red-500 text-sm">*</span>}
|
|
96
96
|
<span className="text-xs px-2 py-1 rounded-full bg-blue-100 text-blue-700 font-medium">
|
|
97
|
-
{input.
|
|
97
|
+
{input.inputTypeId}
|
|
98
98
|
</span>
|
|
99
99
|
</div>
|
|
100
100
|
{input.nodeDescription && (
|
package/src/hooks/use-flow.ts
CHANGED
|
@@ -23,8 +23,8 @@ export interface FlowInputMetadata {
|
|
|
23
23
|
nodeName: string;
|
|
24
24
|
/** Node description explaining what input is needed */
|
|
25
25
|
nodeDescription: string;
|
|
26
|
-
/** Input node
|
|
27
|
-
|
|
26
|
+
/** Input type ID from inputTypeRegistry - describes how clients interact with this node */
|
|
27
|
+
inputTypeId?: string;
|
|
28
28
|
/** Whether this input is required */
|
|
29
29
|
required: boolean;
|
|
30
30
|
}
|
|
@@ -277,7 +277,7 @@ export function useFlow(options: FlowUploadOptions): UseFlowReturn {
|
|
|
277
277
|
nodeId: node.id,
|
|
278
278
|
nodeName: node.name,
|
|
279
279
|
nodeDescription: node.description,
|
|
280
|
-
|
|
280
|
+
inputTypeId: node.inputTypeId,
|
|
281
281
|
// TODO: Add required field to node schema to determine if input is required
|
|
282
282
|
required: true,
|
|
283
283
|
}));
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"upload-zone-Bbqr8oWe.mjs","names":["errors: string[]"],"sources":["../src/components/flow-input.tsx","../src/components/flow-upload-list.tsx","../src/components/flow-upload-zone.tsx","../src/components/upload-list.tsx","../src/components/upload-zone.tsx"],"sourcesContent":["/** biome-ignore-all lint/a11y/useSemanticElements: button is inside a div*/\n\"use client\";\n\nimport { useDragDrop } from \"../hooks/use-drag-drop\";\nimport type { FlowInputMetadata } from \"../hooks/use-flow\";\n\nexport interface FlowInputProps {\n /** Input metadata from flow discovery */\n input: FlowInputMetadata;\n /** Accepted file types (e.g., \"image/*\", \"video/*\") */\n accept?: string;\n /** Whether the input should support URL input */\n allowUrl?: boolean;\n /** Current value (File or URL string) */\n value?: File | string | null;\n /** Callback when value changes */\n onChange: (value: File | string) => void;\n /** Whether the input is disabled */\n disabled?: boolean;\n /** Additional CSS classes */\n className?: string;\n}\n\n/**\n * Input component for flow execution with file drag-and-drop and URL support.\n *\n * Features:\n * - File drag-and-drop with visual feedback\n * - URL input for remote files\n * - Displays node name and description\n * - Shows selected file/URL with size\n * - Type validation and error display\n *\n * @example\n * ```tsx\n * <FlowInput\n * input={inputMetadata}\n * accept=\"image/*\"\n * allowUrl={true}\n * value={selectedValue}\n * onChange={(value) => flow.setInput(inputMetadata.nodeId, value)}\n * />\n * ```\n */\nexport function FlowInput({\n input,\n accept = \"*\",\n allowUrl = true,\n value,\n onChange,\n disabled = false,\n className = \"\",\n}: FlowInputProps) {\n const isFileValue = value instanceof File;\n const isUrlValue = typeof value === \"string\" && value.length > 0;\n\n // Determine input mode based on node type\n const supportsFileUpload = input.nodeTypeId === \"streaming-input-v1\";\n const supportsUrl =\n allowUrl &&\n (input.nodeTypeId === \"url-input-v1\" ||\n input.nodeTypeId === \"streaming-input-v1\");\n\n const dragDrop = useDragDrop({\n onFilesReceived: (files) => {\n if (files[0]) {\n onChange(files[0]);\n }\n },\n accept: accept ? accept.split(\",\").map((type) => type.trim()) : undefined,\n multiple: false,\n });\n\n const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {\n const file = e.target.files?.[0];\n if (file) {\n onChange(file);\n }\n };\n\n const handleUrlChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n onChange(e.target.value);\n };\n\n const handleClear = () => {\n onChange(\"\");\n };\n\n return (\n <div className={`space-y-3 ${className}`}>\n {/* Header */}\n <div>\n <div className=\"flex items-center gap-2 mb-1\">\n <h4 className=\"font-semibold text-gray-900\">{input.nodeName}</h4>\n {input.required && <span className=\"text-red-500 text-sm\">*</span>}\n <span className=\"text-xs px-2 py-1 rounded-full bg-blue-100 text-blue-700 font-medium\">\n {input.nodeTypeId}\n </span>\n </div>\n {input.nodeDescription && (\n <p className=\"text-sm text-gray-600\">{input.nodeDescription}</p>\n )}\n </div>\n\n {/* File Upload Area */}\n {supportsFileUpload && (\n <div\n role=\"button\"\n tabIndex={disabled ? -1 : 0}\n {...dragDrop.dragHandlers}\n onClick={() => !disabled && dragDrop.openFilePicker()}\n onKeyDown={(e) => {\n if ((e.key === \"Enter\" || e.key === \" \") && !disabled) {\n e.preventDefault();\n dragDrop.openFilePicker();\n }\n }}\n className={`\n relative border-2 border-dashed rounded-xl p-6 text-center cursor-pointer transition-all\n ${\n dragDrop.state.isDragging\n ? \"border-indigo-500 bg-indigo-50\"\n : \"border-gray-300 bg-gray-50 hover:border-indigo-400 hover:bg-indigo-50/50\"\n }\n ${disabled ? \"opacity-50 cursor-not-allowed\" : \"\"}\n `}\n >\n {dragDrop.state.isDragging ? (\n <div className=\"flex flex-col items-center gap-2\">\n <svg\n className=\"w-8 h-8 text-indigo-600\"\n fill=\"none\"\n viewBox=\"0 0 24 24\"\n stroke=\"currentColor\"\n >\n <title>Drop file</title>\n <path\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n strokeWidth={2}\n d=\"M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12\"\n />\n </svg>\n <p className=\"text-sm font-medium text-indigo-600\">\n Drop file here\n </p>\n </div>\n ) : isFileValue ? (\n <div className=\"flex items-center justify-between\">\n <div className=\"flex items-center gap-3\">\n <svg\n className=\"w-5 h-5 text-green-500\"\n fill=\"currentColor\"\n viewBox=\"0 0 20 20\"\n aria-hidden=\"true\"\n >\n <path\n fillRule=\"evenodd\"\n d=\"M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z\"\n clipRule=\"evenodd\"\n />\n </svg>\n <div className=\"text-left\">\n <p className=\"text-sm font-medium text-gray-900\">\n {value.name}\n </p>\n <p className=\"text-xs text-gray-500\">\n {(value.size / 1024).toFixed(1)} KB\n </p>\n </div>\n </div>\n <button\n type=\"button\"\n onClick={(e) => {\n e.stopPropagation();\n handleClear();\n }}\n className=\"px-3 py-1 text-sm text-red-600 hover:text-red-700 hover:bg-red-50 rounded-lg transition-colors\"\n >\n Remove\n </button>\n </div>\n ) : (\n <div className=\"flex flex-col items-center gap-2\">\n <svg\n className=\"w-8 h-8 text-gray-400\"\n fill=\"none\"\n viewBox=\"0 0 24 24\"\n stroke=\"currentColor\"\n >\n <title>Upload file</title>\n <path\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n strokeWidth={2}\n d=\"M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12\"\n />\n </svg>\n <div>\n <p className=\"text-sm font-medium text-gray-700\">\n Drag and drop a file here, or click to select\n </p>\n <p className=\"text-xs text-gray-500 mt-1\">Accepted: {accept}</p>\n </div>\n </div>\n )}\n <input {...dragDrop.inputProps} />\n </div>\n )}\n\n {/* Drag & Drop Errors */}\n {dragDrop.state.errors.length > 0 && (\n <div className=\"bg-red-50 border border-red-200 rounded-lg p-3\">\n {dragDrop.state.errors.map((error, index) => (\n <p key={index} className=\"text-sm text-red-700\">\n {error}\n </p>\n ))}\n </div>\n )}\n\n {/* URL Input */}\n {supportsUrl && supportsFileUpload && (\n <div className=\"flex items-center gap-3\">\n <div className=\"flex-1 border-t border-gray-300\" />\n <span className=\"text-xs font-medium text-gray-500 uppercase\">\n Or\n </span>\n <div className=\"flex-1 border-t border-gray-300\" />\n </div>\n )}\n\n {supportsUrl && (\n <div className=\"space-y-2\">\n {!supportsFileUpload && (\n <label\n htmlFor={`url-${input.nodeId}`}\n className=\"block text-sm font-medium text-gray-700\"\n >\n URL\n </label>\n )}\n <div className=\"relative\">\n <input\n id={`url-${input.nodeId}`}\n type=\"url\"\n value={isUrlValue ? value : \"\"}\n onChange={handleUrlChange}\n disabled={disabled}\n placeholder=\"https://example.com/file.jpg\"\n className=\"block w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 disabled:opacity-50 disabled:cursor-not-allowed text-sm\"\n />\n {isUrlValue && (\n <button\n type=\"button\"\n onClick={handleClear}\n disabled={disabled}\n className=\"absolute right-2 top-1/2 -translate-y-1/2 p-1 text-gray-400 hover:text-gray-600 rounded-lg hover:bg-gray-100 transition-colors\"\n aria-label=\"Clear URL\"\n >\n <svg\n className=\"w-4 h-4\"\n fill=\"none\"\n viewBox=\"0 0 24 24\"\n stroke=\"currentColor\"\n >\n <title>Clear</title>\n <path\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n strokeWidth={2}\n d=\"M6 18L18 6M6 6l12 12\"\n />\n </svg>\n </button>\n )}\n </div>\n {isUrlValue && (\n <div className=\"flex items-center gap-2 text-xs text-gray-600\">\n <svg\n className=\"w-4 h-4 text-blue-500\"\n fill=\"currentColor\"\n viewBox=\"0 0 20 20\"\n aria-hidden=\"true\"\n >\n <path\n fillRule=\"evenodd\"\n d=\"M12.586 4.586a2 2 0 112.828 2.828l-3 3a2 2 0 01-2.828 0 1 1 0 00-1.414 1.414 4 4 0 005.656 0l3-3a4 4 0 00-5.656-5.656l-1.5 1.5a1 1 0 101.414 1.414l1.5-1.5zm-5 5a2 2 0 012.828 0 1 1 0 101.414-1.414 4 4 0 00-5.656 0l-3 3a4 4 0 105.656 5.656l1.5-1.5a1 1 0 10-1.414-1.414l-1.5 1.5a2 2 0 11-2.828-2.828l3-3z\"\n clipRule=\"evenodd\"\n />\n </svg>\n <span className=\"truncate\">{value}</span>\n </div>\n )}\n </div>\n )}\n </div>\n );\n}\n","import type {\n BrowserUploadInput,\n FlowUploadConfig,\n FlowUploadItem,\n MultiFlowUploadOptions,\n} from \"@uploadista/client-browser\";\nimport type { ReactNode } from \"react\";\nimport { useMultiFlowUpload } from \"../hooks/use-multi-flow-upload\";\n\n/**\n * Render props passed to the FlowUploadList children function.\n * Provides access to upload items, aggregate statistics, and control methods.\n *\n * @property items - All flow upload items in the queue\n * @property totalProgress - Average progress across all uploads (0-100)\n * @property activeUploads - Count of currently uploading items\n * @property completedUploads - Count of successfully completed uploads\n * @property failedUploads - Count of failed uploads\n * @property isUploading - True when any uploads are in progress\n * @property addFiles - Add new files to the upload queue\n * @property removeFile - Remove a specific file from the queue\n * @property startUpload - Begin uploading all pending files\n * @property abortUpload - Cancel a specific active upload\n * @property abortAll - Cancel all active uploads\n * @property clear - Remove all items from the queue\n * @property retryUpload - Retry a specific failed upload\n */\nexport interface FlowUploadListRenderProps {\n /**\n * List of upload items\n */\n items: FlowUploadItem<BrowserUploadInput>[];\n\n /**\n * Total progress across all uploads\n */\n totalProgress: number;\n\n /**\n * Number of active uploads\n */\n activeUploads: number;\n\n /**\n * Number of completed uploads\n */\n completedUploads: number;\n\n /**\n * Number of failed uploads\n */\n failedUploads: number;\n\n /**\n * Whether any uploads are in progress\n */\n isUploading: boolean;\n\n /**\n * Add files to the upload queue\n */\n addFiles: (files: File[] | FileList) => void;\n\n /**\n * Remove a file from the queue\n */\n removeFile: (id: string) => void;\n\n /**\n * Start uploading all pending files\n */\n startUpload: () => void;\n\n /**\n * Abort a specific upload\n */\n abortUpload: (id: string) => void;\n\n /**\n * Abort all uploads\n */\n abortAll: () => void;\n\n /**\n * Clear all items\n */\n clear: () => void;\n\n /**\n * Retry a failed upload\n */\n retryUpload: (id: string) => void;\n}\n\n/**\n * Props for the FlowUploadList component.\n *\n * @property flowConfig - Flow execution configuration (flowId, storageId, etc.)\n * @property options - Multi-flow upload options (callbacks, concurrency, etc.)\n * @property children - Render function receiving flow upload list state\n */\nexport interface FlowUploadListProps {\n /**\n * Flow configuration\n */\n flowConfig: FlowUploadConfig;\n\n /**\n * Multi-upload options\n */\n options?: Omit<MultiFlowUploadOptions<BrowserUploadInput>, \"flowConfig\">;\n\n /**\n * Render function for the upload list\n */\n children: (props: FlowUploadListRenderProps) => ReactNode;\n}\n\n/**\n * Headless flow upload list component for managing batch file uploads through a flow.\n * Uses render props pattern to provide complete control over the UI while handling\n * concurrent uploads and flow processing.\n *\n * Each file is uploaded and processed independently through the specified flow,\n * with automatic queue management and concurrency control.\n *\n * Must be used within an UploadistaProvider.\n *\n * @param props - Flow upload list configuration and render prop\n * @returns Rendered flow upload list using the provided render prop\n *\n * @example\n * ```tsx\n * // Batch image processing with custom UI\n * <FlowUploadList\n * flowConfig={{\n * flowId: \"image-batch-processing\",\n * storageId: \"s3-images\",\n * outputNodeId: \"optimized\",\n * }}\n * options={{\n * maxConcurrent: 3,\n * onItemSuccess: (item) => {\n * console.log(`${item.file.name} processed successfully`);\n * },\n * onComplete: (items) => {\n * const successful = items.filter(i => i.status === 'success');\n * console.log(`Batch complete: ${successful.length}/${items.length} successful`);\n * },\n * }}\n * >\n * {({\n * items,\n * totalProgress,\n * activeUploads,\n * completedUploads,\n * failedUploads,\n * addFiles,\n * startUpload,\n * abortUpload,\n * retryUpload,\n * clear,\n * }) => (\n * <div>\n * <input\n * type=\"file\"\n * multiple\n * accept=\"image/*\"\n * onChange={(e) => {\n * if (e.target.files) {\n * addFiles(e.target.files);\n * startUpload();\n * }\n * }}\n * />\n *\n * <div style={{ marginTop: '1rem' }}>\n * <h3>Upload Progress</h3>\n * <div>Overall: {totalProgress}%</div>\n * <div>\n * Active: {activeUploads}, Completed: {completedUploads}, Failed: {failedUploads}\n * </div>\n * <button onClick={clear}>Clear All</button>\n * </div>\n *\n * <ul style={{ listStyle: 'none', padding: 0 }}>\n * {items.map((item) => (\n * <li key={item.id} style={{\n * padding: '1rem',\n * border: '1px solid #ccc',\n * marginBottom: '0.5rem'\n * }}>\n * <div>{item.file instanceof File ? item.file.name : 'File'}</div>\n * <div>Status: {item.status}</div>\n *\n * {item.status === \"uploading\" && (\n * <div>\n * <progress value={item.progress} max={100} style={{ width: '100%' }} />\n * <div>{item.progress}%</div>\n * <button onClick={() => abortUpload(item.id)}>Cancel</button>\n * </div>\n * )}\n *\n * {item.status === \"error\" && (\n * <div>\n * <div style={{ color: 'red' }}>{item.error?.message}</div>\n * <button onClick={() => retryUpload(item.id)}>Retry</button>\n * </div>\n * )}\n *\n * {item.status === \"success\" && (\n * <div style={{ color: 'green' }}>✓ Complete</div>\n * )}\n * </li>\n * ))}\n * </ul>\n * </div>\n * )}\n * </FlowUploadList>\n * ```\n *\n * @see {@link SimpleFlowUploadList} for a pre-styled version\n * @see {@link useMultiFlowUpload} for the underlying hook\n */\nexport function FlowUploadList({\n flowConfig,\n options,\n children,\n}: FlowUploadListProps) {\n const multiUpload = useMultiFlowUpload({\n ...options,\n flowConfig,\n });\n\n return (\n <>\n {children({\n items: multiUpload.state.items,\n totalProgress: multiUpload.state.totalProgress,\n activeUploads: multiUpload.state.activeUploads,\n completedUploads: multiUpload.state.completedUploads,\n failedUploads: multiUpload.state.failedUploads,\n isUploading: multiUpload.isUploading,\n addFiles: multiUpload.addFiles,\n removeFile: multiUpload.removeFile,\n startUpload: multiUpload.startUpload,\n abortUpload: multiUpload.abortUpload,\n abortAll: multiUpload.abortAll,\n clear: multiUpload.clear,\n retryUpload: multiUpload.retryUpload,\n })}\n </>\n );\n}\n\n/**\n * Props for the SimpleFlowUploadListItem component.\n *\n * @property item - The flow upload item to display\n * @property onAbort - Called when the abort button is clicked\n * @property onRetry - Called when the retry button is clicked\n * @property onRemove - Called when the remove button is clicked\n */\nexport interface SimpleFlowUploadListItemProps {\n /**\n * Upload item\n */\n item: FlowUploadItem<BrowserUploadInput>;\n\n /**\n * Abort the upload\n */\n onAbort: () => void;\n\n /**\n * Retry the upload\n */\n onRetry: () => void;\n\n /**\n * Remove the item\n */\n onRemove: () => void;\n}\n\n/**\n * Pre-styled flow upload list item component with status indicators.\n * Displays file name, upload progress, status, and contextual action buttons.\n *\n * Features:\n * - Status-specific icons and colors\n * - Progress bar with percentage and byte count\n * - Error message display\n * - Contextual action buttons (cancel, retry, remove)\n *\n * @param props - Upload item and callback functions\n * @returns Styled flow upload list item component\n *\n * @example\n * ```tsx\n * <SimpleFlowUploadListItem\n * item={uploadItem}\n * onAbort={() => console.log('Abort')}\n * onRetry={() => console.log('Retry')}\n * onRemove={() => console.log('Remove')}\n * />\n * ```\n */\nexport function SimpleFlowUploadListItem({\n item,\n onAbort,\n onRetry,\n onRemove,\n}: SimpleFlowUploadListItemProps) {\n const getStatusIcon = () => {\n switch (item.status) {\n case \"success\":\n return \"✓\";\n case \"error\":\n return \"✗\";\n case \"uploading\":\n return \"⟳\";\n case \"aborted\":\n return \"⊘\";\n default:\n return \"○\";\n }\n };\n\n const getStatusColor = () => {\n switch (item.status) {\n case \"success\":\n return \"green\";\n case \"error\":\n return \"red\";\n case \"uploading\":\n return \"blue\";\n case \"aborted\":\n return \"gray\";\n default:\n return \"black\";\n }\n };\n\n return (\n <div\n style={{\n display: \"flex\",\n alignItems: \"center\",\n gap: \"12px\",\n padding: \"8px\",\n borderBottom: \"1px solid #eee\",\n }}\n >\n <span style={{ color: getStatusColor(), fontSize: \"18px\" }}>\n {getStatusIcon()}\n </span>\n\n <div style={{ flex: 1, minWidth: 0 }}>\n <div\n style={{\n fontSize: \"14px\",\n fontWeight: 500,\n overflow: \"hidden\",\n textOverflow: \"ellipsis\",\n whiteSpace: \"nowrap\",\n }}\n >\n {item.file instanceof File ? item.file.name : \"Upload\"}\n </div>\n\n {item.status === \"uploading\" && (\n <div style={{ marginTop: \"4px\" }}>\n <progress\n value={item.progress}\n max={100}\n style={{ width: \"100%\", height: \"4px\" }}\n />\n <div style={{ fontSize: \"12px\", color: \"#666\", marginTop: \"2px\" }}>\n {item.progress}% • {Math.round(item.bytesUploaded / 1024)} KB /{\" \"}\n {Math.round(item.totalBytes / 1024)} KB\n </div>\n </div>\n )}\n\n {item.status === \"error\" && (\n <div style={{ fontSize: \"12px\", color: \"red\", marginTop: \"2px\" }}>\n {item.error?.message || \"Upload failed\"}\n </div>\n )}\n\n {item.status === \"success\" && (\n <div style={{ fontSize: \"12px\", color: \"green\", marginTop: \"2px\" }}>\n Upload complete\n </div>\n )}\n </div>\n\n <div style={{ display: \"flex\", gap: \"8px\" }}>\n {item.status === \"uploading\" && (\n <button\n type=\"button\"\n onClick={onAbort}\n style={{\n padding: \"4px 8px\",\n fontSize: \"12px\",\n borderRadius: \"4px\",\n border: \"1px solid #ccc\",\n backgroundColor: \"#fff\",\n cursor: \"pointer\",\n }}\n >\n Cancel\n </button>\n )}\n\n {item.status === \"error\" && (\n <button\n type=\"button\"\n onClick={onRetry}\n style={{\n padding: \"4px 8px\",\n fontSize: \"12px\",\n borderRadius: \"4px\",\n border: \"1px solid #ccc\",\n backgroundColor: \"#fff\",\n cursor: \"pointer\",\n }}\n >\n Retry\n </button>\n )}\n\n {(item.status === \"pending\" ||\n item.status === \"error\" ||\n item.status === \"aborted\") && (\n <button\n type=\"button\"\n onClick={onRemove}\n style={{\n padding: \"4px 8px\",\n fontSize: \"12px\",\n borderRadius: \"4px\",\n border: \"1px solid #ccc\",\n backgroundColor: \"#fff\",\n cursor: \"pointer\",\n }}\n >\n Remove\n </button>\n )}\n </div>\n </div>\n );\n}\n\n/**\n * Props for the SimpleFlowUploadList component.\n *\n * @property flowConfig - Flow execution configuration\n * @property options - Multi-flow upload options (callbacks, concurrency)\n * @property className - CSS class name for the container\n * @property showFileInput - Whether to display the file input (default: true)\n * @property accept - Accepted file types for the file input\n */\nexport interface SimpleFlowUploadListProps {\n /**\n * Flow configuration\n */\n flowConfig: FlowUploadConfig;\n\n /**\n * Multi-upload options\n */\n options?: Omit<MultiFlowUploadOptions<BrowserUploadInput>, \"flowConfig\">;\n\n /**\n * CSS class for the container\n */\n className?: string;\n\n /**\n * Show file input\n */\n showFileInput?: boolean;\n\n /**\n * File input accept attribute\n */\n accept?: string;\n}\n\n/**\n * Simple pre-styled flow upload list component with built-in UI.\n * Provides a ready-to-use interface for batch file uploads with flow processing.\n *\n * Features:\n * - Built-in file input\n * - Overall progress display\n * - Individual item progress tracking\n * - Status indicators and action buttons\n * - Automatic upload start on file selection\n *\n * @param props - Flow upload list configuration with styling options\n * @returns Styled flow upload list component\n *\n * @example\n * ```tsx\n * // Basic batch image upload\n * <SimpleFlowUploadList\n * flowConfig={{\n * flowId: \"image-batch-processing\",\n * storageId: \"s3-images\",\n * }}\n * options={{\n * maxConcurrent: 3,\n * onItemSuccess: (item) => {\n * console.log(`${item.file.name} processed`);\n * },\n * onComplete: (items) => {\n * console.log(\"Batch complete:\", items.length);\n * },\n * }}\n * accept=\"image/*\"\n * className=\"my-upload-list\"\n * />\n *\n * // Without file input (add files programmatically)\n * <SimpleFlowUploadList\n * flowConfig={{\n * flowId: \"document-processing\",\n * storageId: \"docs\",\n * }}\n * showFileInput={false}\n * options={{\n * maxConcurrent: 2,\n * }}\n * />\n * ```\n *\n * @see {@link FlowUploadList} for the headless version with full control\n */\nexport function SimpleFlowUploadList({\n flowConfig,\n options,\n className = \"\",\n showFileInput = true,\n accept,\n}: SimpleFlowUploadListProps) {\n return (\n <FlowUploadList flowConfig={flowConfig} options={options}>\n {({\n items,\n addFiles,\n startUpload,\n abortUpload,\n retryUpload,\n removeFile,\n totalProgress,\n }) => (\n <div className={className}>\n {showFileInput && (\n <div style={{ marginBottom: \"16px\" }}>\n <input\n type=\"file\"\n multiple\n accept={accept}\n onChange={(e) => {\n if (e.target.files) {\n addFiles(e.target.files);\n startUpload();\n }\n }}\n style={{\n padding: \"8px\",\n border: \"1px solid #ccc\",\n borderRadius: \"4px\",\n }}\n />\n </div>\n )}\n\n {items.length > 0 && (\n <div>\n <div\n style={{ marginBottom: \"8px\", fontSize: \"14px\", color: \"#666\" }}\n >\n Total Progress: {totalProgress}%\n </div>\n\n <div\n style={{\n border: \"1px solid #eee\",\n borderRadius: \"8px\",\n overflow: \"hidden\",\n }}\n >\n {items.map((item) => (\n <SimpleFlowUploadListItem\n key={item.id}\n item={item}\n onAbort={() => abortUpload(item.id)}\n onRetry={() => retryUpload(item.id)}\n onRemove={() => removeFile(item.id)}\n />\n ))}\n </div>\n </div>\n )}\n </div>\n )}\n </FlowUploadList>\n );\n}\n","import type {\n FlowUploadConfig,\n FlowUploadOptions,\n} from \"@uploadista/client-browser\";\nimport type { ReactNode } from \"react\";\nimport { type UseDragDropReturn, useDragDrop } from \"../hooks/use-drag-drop\";\nimport {\n type UseFlowUploadReturn,\n useFlowUpload,\n} from \"../hooks/use-flow-upload\";\n\n/**\n * Render props passed to the FlowUploadZone children function.\n * Provides access to flow upload state, drag-drop handlers, and helper functions.\n *\n * @property dragDrop - Complete drag-and-drop state and handlers\n * @property flowUpload - Flow upload hook with upload state and controls\n * @property isActive - True when dragging over zone\n * @property openFilePicker - Programmatically open file selection dialog\n * @property getRootProps - Returns props to spread on the drop zone container\n * @property getInputProps - Returns props to spread on the hidden file input\n */\nexport interface FlowUploadZoneRenderProps {\n /**\n * Drag and drop state and handlers\n */\n dragDrop: UseDragDropReturn;\n\n /**\n * Flow upload functionality\n */\n flowUpload: UseFlowUploadReturn;\n\n /**\n * Whether the zone is currently active (dragging or uploading)\n */\n isActive: boolean;\n\n /**\n * Open file picker\n */\n openFilePicker: () => void;\n\n /**\n * Props to spread on the drop zone element\n */\n getRootProps: () => {\n onDragEnter: (e: React.DragEvent) => void;\n onDragOver: (e: React.DragEvent) => void;\n onDragLeave: (e: React.DragEvent) => void;\n onDrop: (e: React.DragEvent) => void;\n };\n\n /**\n * Props to spread on the file input element\n */\n getInputProps: () => React.InputHTMLAttributes<HTMLInputElement>;\n}\n\n/**\n * Props for the FlowUploadZone component.\n *\n * @property flowConfig - Flow execution configuration (flowId, storageId, etc.)\n * @property options - Flow upload options (callbacks, metadata, etc.)\n * @property accept - Accepted file types (e.g., \"image/*\", \".pdf\")\n * @property multiple - Allow multiple file selection (default: false)\n * @property children - Render function receiving flow upload zone state\n */\nexport interface FlowUploadZoneProps {\n /**\n * Flow configuration\n */\n flowConfig: FlowUploadConfig;\n\n /**\n * Upload options\n */\n options?: Omit<FlowUploadOptions, \"flowConfig\">;\n\n /**\n * Accepted file types (e.g., \"image/*\", \".pdf\", etc.)\n */\n accept?: string;\n\n /**\n * Whether to allow multiple files (uses multi-upload internally)\n */\n multiple?: boolean;\n\n /**\n * Render function for the drop zone\n */\n children: (props: FlowUploadZoneRenderProps) => ReactNode;\n}\n\n/**\n * Headless flow upload zone component with drag-and-drop support.\n * Combines drag-drop functionality with flow processing, using render props\n * for complete UI control.\n *\n * Files uploaded through this zone are automatically processed through the\n * specified flow, which can perform operations like image optimization,\n * storage saving, webhooks, etc.\n *\n * Must be used within an UploadistaProvider.\n *\n * @param props - Flow upload zone configuration and render prop\n * @returns Rendered flow upload zone using the provided render prop\n *\n * @example\n * ```tsx\n * // Image upload with flow processing\n * <FlowUploadZone\n * flowConfig={{\n * flowId: \"image-processing-flow\",\n * storageId: \"s3-images\",\n * outputNodeId: \"optimized-image\",\n * }}\n * options={{\n * onSuccess: (result) => console.log('Processed:', result),\n * onFlowComplete: (outputs) => {\n * console.log('All outputs:', outputs);\n * },\n * }}\n * accept=\"image/*\"\n * >\n * {({ dragDrop, flowUpload, getRootProps, getInputProps, openFilePicker }) => (\n * <div {...getRootProps()} style={{\n * border: dragDrop.state.isDragging ? '2px solid blue' : '2px dashed gray',\n * padding: '2rem',\n * textAlign: 'center'\n * }}>\n * <input {...getInputProps()} />\n *\n * {dragDrop.state.isDragging && (\n * <p>Drop image here...</p>\n * )}\n *\n * {!dragDrop.state.isDragging && !flowUpload.isUploading && (\n * <div>\n * <p>Drag an image or click to browse</p>\n * <button onClick={openFilePicker}>Choose File</button>\n * </div>\n * )}\n *\n * {flowUpload.isUploadingFile && (\n * <div>\n * <p>Uploading...</p>\n * <progress value={flowUpload.state.progress} max={100} />\n * <span>{flowUpload.state.progress}%</span>\n * </div>\n * )}\n *\n * {flowUpload.isProcessing && (\n * <div>\n * <p>Processing image...</p>\n * {flowUpload.state.currentNodeName && (\n * <span>Step: {flowUpload.state.currentNodeName}</span>\n * )}\n * </div>\n * )}\n *\n * {flowUpload.state.status === \"success\" && (\n * <div>\n * <p>✓ Upload complete!</p>\n * {flowUpload.state.result && (\n * <img src={flowUpload.state.result.url} alt=\"Uploaded\" />\n * )}\n * </div>\n * )}\n *\n * {flowUpload.state.status === \"error\" && (\n * <div>\n * <p>Error: {flowUpload.state.error?.message}</p>\n * <button onClick={flowUpload.reset}>Try Again</button>\n * </div>\n * )}\n *\n * {flowUpload.isUploading && (\n * <button onClick={flowUpload.abort}>Cancel</button>\n * )}\n * </div>\n * )}\n * </FlowUploadZone>\n * ```\n *\n * @see {@link SimpleFlowUploadZone} for a pre-styled version\n * @see {@link useFlowUpload} for the underlying hook\n */\nexport function FlowUploadZone({\n flowConfig,\n options,\n accept,\n multiple = false,\n children,\n}: FlowUploadZoneProps) {\n // Hook automatically subscribes to events through context\n const flowUpload = useFlowUpload({\n ...options,\n flowConfig,\n });\n\n const dragDrop = useDragDrop({\n onFilesReceived: (files: File[]) => {\n const file = files[0];\n if (file) {\n flowUpload.upload(file);\n }\n },\n accept: accept ? [accept] : undefined,\n multiple,\n });\n\n const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n const files = e.target.files;\n const file = files?.[0];\n if (file) {\n flowUpload.upload(file);\n }\n };\n\n // Determine active state\n const isActive = dragDrop.state.isDragging || dragDrop.state.isOver;\n\n return (\n <>\n {children({\n flowUpload,\n dragDrop,\n isActive,\n openFilePicker: dragDrop.openFilePicker,\n getRootProps: () => dragDrop.dragHandlers,\n getInputProps: () => ({\n ...dragDrop.inputProps,\n onChange: handleFileChange,\n }),\n })}\n </>\n );\n}\n\n/**\n * Props for the SimpleFlowUploadZone component.\n *\n * @property flowConfig - Flow execution configuration\n * @property options - Flow upload options (callbacks, metadata)\n * @property accept - Accepted file types\n * @property className - CSS class name for custom styling\n * @property dragText - Text displayed when dragging files over zone\n * @property idleText - Text displayed when zone is idle\n */\nexport interface SimpleFlowUploadZoneProps {\n /**\n * Flow configuration\n */\n flowConfig: FlowUploadConfig;\n\n /**\n * Upload options\n */\n options?: Omit<FlowUploadOptions, \"flowConfig\">;\n\n /**\n * Accepted file types\n */\n accept?: string;\n\n /**\n * CSS class for the container\n */\n className?: string;\n\n /**\n * Custom drag overlay text\n */\n dragText?: string;\n\n /**\n * Custom idle text\n */\n idleText?: string;\n}\n\n/**\n * Simple pre-styled flow upload zone component with built-in UI.\n * Provides a ready-to-use drag-and-drop interface for flow uploads.\n *\n * Features:\n * - Built-in drag-and-drop visual feedback\n * - Automatic progress display for upload and processing phases\n * - Success and error state display\n * - Cancel button during upload\n * - Customizable text labels\n *\n * @param props - Flow upload zone configuration with styling options\n * @returns Styled flow upload zone component\n *\n * @example\n * ```tsx\n * // Basic image upload with flow processing\n * <SimpleFlowUploadZone\n * flowConfig={{\n * flowId: \"image-optimization-flow\",\n * storageId: \"s3-images\",\n * }}\n * accept=\"image/*\"\n * options={{\n * onSuccess: (result) => console.log(\"Image processed:\", result),\n * onError: (error) => console.error(\"Processing failed:\", error),\n * }}\n * idleText=\"Drop an image to optimize and upload\"\n * dragText=\"Release to start processing\"\n * className=\"my-upload-zone\"\n * />\n *\n * // Document upload with custom flow\n * <SimpleFlowUploadZone\n * flowConfig={{\n * flowId: \"document-processing-flow\",\n * storageId: \"docs\",\n * outputNodeId: \"processed-doc\",\n * }}\n * accept=\".pdf,.doc,.docx\"\n * options={{\n * onFlowComplete: (outputs) => {\n * console.log('Processing outputs:', outputs);\n * },\n * }}\n * />\n * ```\n *\n * @see {@link FlowUploadZone} for the headless version with full control\n */\nexport function SimpleFlowUploadZone({\n flowConfig,\n options,\n accept,\n className = \"\",\n dragText = \"Drop files here\",\n idleText = \"Drag & drop files or click to browse\",\n}: SimpleFlowUploadZoneProps) {\n return (\n <FlowUploadZone flowConfig={flowConfig} options={options} accept={accept}>\n {({\n dragDrop,\n flowUpload,\n getRootProps,\n getInputProps,\n openFilePicker,\n }) => (\n <div\n {...getRootProps()}\n className={className}\n style={{\n border: \"2px dashed #ccc\",\n borderRadius: \"8px\",\n padding: \"32px\",\n textAlign: \"center\",\n cursor: \"pointer\",\n backgroundColor: dragDrop.state.isDragging\n ? \"#f0f0f0\"\n : \"transparent\",\n transition: \"background-color 0.2s\",\n }}\n >\n <input {...getInputProps()} />\n\n {dragDrop.state.isDragging && <p style={{ margin: 0 }}>{dragText}</p>}\n\n {!dragDrop.state.isDragging &&\n !flowUpload.isUploading &&\n flowUpload.state.status === \"idle\" && (\n <div>\n <p style={{ margin: \"0 0 16px 0\" }}>{idleText}</p>\n <button\n type=\"button\"\n onClick={(e) => {\n e.stopPropagation();\n openFilePicker();\n }}\n style={{\n padding: \"8px 16px\",\n borderRadius: \"4px\",\n border: \"1px solid #ccc\",\n backgroundColor: \"#fff\",\n cursor: \"pointer\",\n }}\n >\n Choose Files\n </button>\n </div>\n )}\n\n {flowUpload.isUploading && (\n <div>\n <progress\n value={flowUpload.state.progress}\n max={100}\n style={{ width: \"100%\", height: \"8px\" }}\n />\n <p style={{ margin: \"8px 0 0 0\" }}>\n {flowUpload.state.progress}%\n </p>\n <button\n type=\"button\"\n onClick={(e) => {\n e.stopPropagation();\n // abort() will be passed from parent\n }}\n style={{\n marginTop: \"8px\",\n padding: \"4px 12px\",\n borderRadius: \"4px\",\n border: \"1px solid #ccc\",\n backgroundColor: \"#fff\",\n cursor: \"pointer\",\n }}\n >\n Cancel\n </button>\n </div>\n )}\n\n {flowUpload.state.status === \"success\" && (\n <div>\n <p style={{ margin: 0, color: \"green\" }}>✓ Upload complete!</p>\n </div>\n )}\n\n {flowUpload.state.status === \"error\" && (\n <div>\n <p style={{ margin: 0, color: \"red\" }}>\n ✗ Error: {flowUpload.state.error?.message}\n </p>\n </div>\n )}\n </div>\n )}\n </FlowUploadZone>\n );\n}\n","import type React from \"react\";\nimport type {\n UploadItem,\n UseMultiUploadReturn,\n} from \"../hooks/use-multi-upload\";\nimport type { UploadStatus } from \"../hooks/use-upload\";\n\n/**\n * Render props passed to the UploadList children function.\n * Provides organized access to upload items, status groupings, and actions.\n *\n * @property items - All upload items (filtered and sorted if configured)\n * @property itemsByStatus - Upload items grouped by their current status\n * @property multiUpload - Complete multi-upload hook instance\n * @property actions - Helper functions for common item operations\n * @property actions.removeItem - Remove an item from the list\n * @property actions.retryItem - Retry a failed upload\n * @property actions.abortItem - Cancel an active upload\n * @property actions.startItem - Begin uploading an idle item\n */\nexport interface UploadListRenderProps {\n /**\n * All upload items\n */\n items: UploadItem[];\n\n /**\n * Items filtered by status\n */\n itemsByStatus: {\n idle: UploadItem[];\n uploading: UploadItem[];\n success: UploadItem[];\n error: UploadItem[];\n aborted: UploadItem[];\n };\n\n /**\n * Multi-upload state and controls\n */\n multiUpload: UseMultiUploadReturn;\n\n /**\n * Helper functions for item management\n */\n actions: {\n removeItem: (id: string) => void;\n retryItem: (item: UploadItem) => void;\n abortItem: (item: UploadItem) => void;\n startItem: (item: UploadItem) => void;\n };\n}\n\n/**\n * Props for the UploadList component.\n *\n * @property multiUpload - Multi-upload hook instance to display\n * @property filter - Optional function to filter which items to show\n * @property sortBy - Optional comparator function to sort items\n * @property children - Render function receiving list state and actions\n */\nexport interface UploadListProps {\n /**\n * Multi-upload instance from useMultiUpload hook\n */\n multiUpload: UseMultiUploadReturn;\n\n /**\n * Optional filter for which items to display\n */\n filter?: (item: UploadItem) => boolean;\n\n /**\n * Optional sorting function for items\n */\n sortBy?: (a: UploadItem, b: UploadItem) => number;\n\n /**\n * Render prop that receives upload list state and actions\n */\n children: (props: UploadListRenderProps) => React.ReactNode;\n}\n\n/**\n * Headless upload list component that provides flexible rendering for upload items.\n * Uses render props pattern to give full control over how upload items are displayed.\n *\n * @param props - Upload list configuration and render prop\n * @returns Rendered upload list using the provided render prop\n *\n * @example\n * ```tsx\n * // Basic upload list with progress bars\n * <UploadList multiUpload={multiUpload}>\n * {({ items, actions }) => (\n * <div>\n * <h3>Upload Queue ({items.length} files)</h3>\n * {items.map((item) => (\n * <div key={item.id} style={{\n * padding: '1rem',\n * border: '1px solid #ccc',\n * marginBottom: '0.5rem',\n * borderRadius: '4px'\n * }}>\n * <div style={{ display: 'flex', justifyContent: 'space-between' }}>\n * <span>{item.file.name}</span>\n * <span>{item.state.status}</span>\n * </div>\n *\n * {item.state.status === 'uploading' && (\n * <div>\n * <progress value={item.state.progress} max={100} />\n * <span>{item.state.progress}%</span>\n * <button onClick={() => actions.abortItem(item)}>Cancel</button>\n * </div>\n * )}\n *\n * {item.state.status === 'error' && (\n * <div>\n * <p style={{ color: 'red' }}>Error: {item.state.error?.message}</p>\n * <button onClick={() => actions.retryItem(item)}>Retry</button>\n * <button onClick={() => actions.removeItem(item.id)}>Remove</button>\n * </div>\n * )}\n *\n * {item.state.status === 'success' && (\n * <div>\n * <p style={{ color: 'green' }}>✓ Uploaded successfully</p>\n * <button onClick={() => actions.removeItem(item.id)}>Remove</button>\n * </div>\n * )}\n *\n * {item.state.status === 'idle' && (\n * <div>\n * <button onClick={() => actions.startItem(item)}>Start Upload</button>\n * <button onClick={() => actions.removeItem(item.id)}>Remove</button>\n * </div>\n * )}\n * </div>\n * ))}\n * </div>\n * )}\n * </UploadList>\n *\n * // Upload list with status filtering and sorting\n * <UploadList\n * multiUpload={multiUpload}\n * filter={(item) => item.state.status !== 'success'} // Hide successful uploads\n * sortBy={(a, b) => {\n * // Sort by status priority, then by filename\n * const statusPriority = { error: 0, uploading: 1, idle: 2, success: 3, aborted: 4 };\n * const aPriority = statusPriority[a.state.status];\n * const bPriority = statusPriority[b.state.status];\n *\n * if (aPriority !== bPriority) {\n * return aPriority - bPriority;\n * }\n *\n * return a.file.name.localeCompare(b.file.name);\n * }}\n * >\n * {({ items, itemsByStatus, multiUpload, actions }) => (\n * <div>\n * {itemsByStatus.error.length > 0 && (\n * <div>\n * <h4 style={{ color: 'red' }}>Failed Uploads ({itemsByStatus.error.length})</h4>\n * {itemsByStatus.error.map((item) => (\n * <UploadListItem key={item.id} item={item} actions={actions} />\n * ))}\n * </div>\n * )}\n *\n * {itemsByStatus.uploading.length > 0 && (\n * <div>\n * <h4>Uploading ({itemsByStatus.uploading.length})</h4>\n * {itemsByStatus.uploading.map((item) => (\n * <UploadListItem key={item.id} item={item} actions={actions} />\n * ))}\n * </div>\n * )}\n *\n * {itemsByStatus.idle.length > 0 && (\n * <div>\n * <h4>Pending ({itemsByStatus.idle.length})</h4>\n * {itemsByStatus.idle.map((item) => (\n * <UploadListItem key={item.id} item={item} actions={actions} />\n * ))}\n * </div>\n * )}\n * </div>\n * )}\n * </UploadList>\n * ```\n */\nexport function UploadList({\n multiUpload,\n filter,\n sortBy,\n children,\n}: UploadListProps) {\n // Apply filtering\n let items = multiUpload.items;\n if (filter) {\n items = items.filter(filter);\n }\n\n // Apply sorting\n if (sortBy) {\n items = [...items].sort(sortBy);\n }\n\n // Group items by status\n const itemsByStatus = {\n idle: items.filter((item) => item.state.status === \"idle\"),\n uploading: items.filter((item) => item.state.status === \"uploading\"),\n success: items.filter((item) => item.state.status === \"success\"),\n error: items.filter((item) => item.state.status === \"error\"),\n aborted: items.filter((item) => item.state.status === \"aborted\"),\n };\n\n // Create action helpers\n const actions = {\n removeItem: (id: string) => {\n multiUpload.removeItem(id);\n },\n retryItem: (_item: UploadItem) => {\n // Retry failed uploads using multiUpload method\n multiUpload.retryFailed();\n },\n abortItem: (item: UploadItem) => {\n // Remove the item to effectively abort it\n multiUpload.removeItem(item.id);\n },\n startItem: (_item: UploadItem) => {\n // Start all pending uploads\n multiUpload.startAll();\n },\n };\n\n // Create render props object\n const renderProps: UploadListRenderProps = {\n items,\n itemsByStatus,\n multiUpload,\n actions,\n };\n\n return <>{children(renderProps)}</>;\n}\n\n/**\n * Props for the SimpleUploadListItem component.\n *\n * @property item - The upload item to display\n * @property actions - Action functions from UploadList render props\n * @property className - Additional CSS class name\n * @property style - Inline styles for the item container\n * @property showDetails - Whether to display file size and upload details\n */\nexport interface SimpleUploadListItemProps {\n /**\n * The upload item to render\n */\n item: UploadItem;\n\n /**\n * Actions from UploadList render props\n */\n actions: UploadListRenderProps[\"actions\"];\n\n /**\n * Additional CSS class name\n */\n className?: string;\n\n /**\n * Inline styles\n */\n style?: React.CSSProperties;\n\n /**\n * Whether to show detailed information (file size, speed, etc.)\n */\n showDetails?: boolean;\n}\n\n/**\n * Pre-styled upload list item component with status indicators and action buttons.\n * Displays file info, progress, errors, and contextual actions based on upload status.\n *\n * Features:\n * - Status-specific color coding and icons\n * - Progress bar for active uploads\n * - Error message display\n * - File size formatting\n * - Contextual action buttons (start, cancel, retry, remove)\n *\n * @param props - Upload item and configuration\n * @returns Styled upload list item component\n *\n * @example\n * ```tsx\n * // Use with UploadList\n * <UploadList multiUpload={multiUpload}>\n * {({ items, actions }) => (\n * <div>\n * {items.map((item) => (\n * <SimpleUploadListItem\n * key={item.id}\n * item={item}\n * actions={actions}\n * showDetails={true}\n * />\n * ))}\n * </div>\n * )}\n * </UploadList>\n *\n * // Custom styling\n * <SimpleUploadListItem\n * item={uploadItem}\n * actions={actions}\n * className=\"my-upload-item\"\n * style={{ borderRadius: '12px', margin: '1rem' }}\n * showDetails={true}\n * />\n * ```\n */\nexport function SimpleUploadListItem({\n item,\n actions,\n className = \"\",\n style = {},\n showDetails = true,\n}: SimpleUploadListItemProps) {\n const getStatusColor = (status: UploadStatus) => {\n switch (status) {\n case \"idle\":\n return \"#6c757d\";\n case \"uploading\":\n return \"#007bff\";\n case \"success\":\n return \"#28a745\";\n case \"error\":\n return \"#dc3545\";\n case \"aborted\":\n return \"#6c757d\";\n default:\n return \"#6c757d\";\n }\n };\n\n const getStatusIcon = (status: UploadStatus) => {\n switch (status) {\n case \"idle\":\n return \"⏳\";\n case \"uploading\":\n return \"📤\";\n case \"success\":\n return \"✅\";\n case \"error\":\n return \"❌\";\n case \"aborted\":\n return \"⏹️\";\n default:\n return \"❓\";\n }\n };\n\n const formatFileSize = (bytes: number) => {\n if (bytes === 0) return \"0 Bytes\";\n const k = 1024;\n const sizes = [\"Bytes\", \"KB\", \"MB\", \"GB\"];\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n return `${parseFloat((bytes / k ** i).toFixed(2))} ${sizes[i]}`;\n };\n\n return (\n <div\n className={`upload-list-item upload-list-item--${item.state.status} ${className}`}\n style={{\n padding: \"12px\",\n border: \"1px solid #e0e0e0\",\n borderRadius: \"6px\",\n marginBottom: \"8px\",\n backgroundColor: \"#fff\",\n transition: \"all 0.2s ease\",\n ...style,\n }}\n >\n {/* Header with filename and status */}\n <div\n style={{\n display: \"flex\",\n justifyContent: \"space-between\",\n alignItems: \"center\",\n marginBottom: \"8px\",\n }}\n >\n <div\n style={{ display: \"flex\", alignItems: \"center\", gap: \"8px\", flex: 1 }}\n >\n <span style={{ fontSize: \"16px\" }}>\n {getStatusIcon(item.state.status)}\n </span>\n <span style={{ fontWeight: \"500\", flex: 1 }}>\n {item.file instanceof File ? item.file.name : \"File\"}\n </span>\n </div>\n <span\n style={{\n fontSize: \"12px\",\n color: getStatusColor(item.state.status),\n fontWeight: \"500\",\n textTransform: \"uppercase\",\n }}\n >\n {item.state.status}\n </span>\n </div>\n\n {/* Progress bar for uploading items */}\n {item.state.status === \"uploading\" && (\n <div style={{ marginBottom: \"8px\" }}>\n <div\n style={{\n display: \"flex\",\n justifyContent: \"space-between\",\n alignItems: \"center\",\n marginBottom: \"4px\",\n }}\n >\n <span style={{ fontSize: \"12px\", color: \"#666\" }}>\n {item.state.progress}%\n </span>\n {showDetails && item.state.totalBytes && (\n <span style={{ fontSize: \"12px\", color: \"#666\" }}>\n {formatFileSize(item.state.bytesUploaded)} /{\" \"}\n {formatFileSize(item.state.totalBytes)}\n </span>\n )}\n </div>\n <div\n style={{\n width: \"100%\",\n height: \"6px\",\n backgroundColor: \"#e0e0e0\",\n borderRadius: \"3px\",\n overflow: \"hidden\",\n }}\n >\n <div\n style={{\n width: `${item.state.progress}%`,\n height: \"100%\",\n backgroundColor: \"#007bff\",\n transition: \"width 0.2s ease\",\n }}\n />\n </div>\n </div>\n )}\n\n {/* Details section */}\n {showDetails && (\n <div style={{ fontSize: \"12px\", color: \"#666\", marginBottom: \"8px\" }}>\n {item.state.totalBytes && (\n <span>{formatFileSize(item.state.totalBytes)}</span>\n )}\n {item.state.status === \"uploading\" && item.state.progress > 0 && (\n <span> • Progress: {item.state.progress}%</span>\n )}\n {item.state.status === \"error\" && item.state.error && (\n <div style={{ color: \"#dc3545\", marginTop: \"4px\" }}>\n {item.state.error.message}\n </div>\n )}\n </div>\n )}\n\n {/* Action buttons */}\n <div style={{ display: \"flex\", gap: \"8px\", flexWrap: \"wrap\" }}>\n {item.state.status === \"idle\" && (\n <>\n <button\n type=\"button\"\n onClick={() => actions.startItem(item)}\n style={{\n padding: \"4px 8px\",\n fontSize: \"12px\",\n border: \"1px solid #007bff\",\n backgroundColor: \"#007bff\",\n color: \"white\",\n borderRadius: \"4px\",\n cursor: \"pointer\",\n }}\n >\n Start\n </button>\n <button\n type=\"button\"\n onClick={() => actions.removeItem(item.id)}\n style={{\n padding: \"4px 8px\",\n fontSize: \"12px\",\n border: \"1px solid #6c757d\",\n backgroundColor: \"transparent\",\n color: \"#6c757d\",\n borderRadius: \"4px\",\n cursor: \"pointer\",\n }}\n >\n Remove\n </button>\n </>\n )}\n\n {item.state.status === \"uploading\" && (\n <button\n type=\"button\"\n onClick={() => actions.abortItem(item)}\n style={{\n padding: \"4px 8px\",\n fontSize: \"12px\",\n border: \"1px solid #dc3545\",\n backgroundColor: \"transparent\",\n color: \"#dc3545\",\n borderRadius: \"4px\",\n cursor: \"pointer\",\n }}\n >\n Cancel\n </button>\n )}\n\n {item.state.status === \"error\" && (\n <>\n <button\n type=\"button\"\n onClick={() => actions.retryItem(item)}\n style={{\n padding: \"4px 8px\",\n fontSize: \"12px\",\n border: \"1px solid #28a745\",\n backgroundColor: \"#28a745\",\n color: \"white\",\n borderRadius: \"4px\",\n cursor: \"pointer\",\n }}\n >\n Retry\n </button>\n <button\n type=\"button\"\n onClick={() => actions.removeItem(item.id)}\n style={{\n padding: \"4px 8px\",\n fontSize: \"12px\",\n border: \"1px solid #6c757d\",\n backgroundColor: \"transparent\",\n color: \"#6c757d\",\n borderRadius: \"4px\",\n cursor: \"pointer\",\n }}\n >\n Remove\n </button>\n </>\n )}\n\n {item.state.status === \"success\" && (\n <button\n type=\"button\"\n onClick={() => actions.removeItem(item.id)}\n style={{\n padding: \"4px 8px\",\n fontSize: \"12px\",\n border: \"1px solid #6c757d\",\n backgroundColor: \"transparent\",\n color: \"#6c757d\",\n borderRadius: \"4px\",\n cursor: \"pointer\",\n }}\n >\n Remove\n </button>\n )}\n\n {item.state.status === \"aborted\" && (\n <>\n <button\n type=\"button\"\n onClick={() => actions.retryItem(item)}\n style={{\n padding: \"4px 8px\",\n fontSize: \"12px\",\n border: \"1px solid #007bff\",\n backgroundColor: \"#007bff\",\n color: \"white\",\n borderRadius: \"4px\",\n cursor: \"pointer\",\n }}\n >\n Retry\n </button>\n <button\n type=\"button\"\n onClick={() => actions.removeItem(item.id)}\n style={{\n padding: \"4px 8px\",\n fontSize: \"12px\",\n border: \"1px solid #6c757d\",\n backgroundColor: \"transparent\",\n color: \"#6c757d\",\n borderRadius: \"4px\",\n cursor: \"pointer\",\n }}\n >\n Remove\n </button>\n </>\n )}\n </div>\n </div>\n );\n}\n","/**\n * Upload Zone Components\n *\n * Enhanced error handling features:\n * - MIME type validation with detailed error messages\n * - File count validation (single vs multiple mode)\n * - Custom validation error callbacks\n * - Built-in error display in SimpleUploadZone\n * - Configurable error styling\n */\n\nimport type React from \"react\";\nimport { useCallback } from \"react\";\nimport type {\n DragDropOptions,\n UseDragDropReturn,\n} from \"../hooks/use-drag-drop\";\nimport { useDragDrop } from \"../hooks/use-drag-drop\";\nimport type {\n MultiUploadOptions,\n UseMultiUploadReturn,\n} from \"../hooks/use-multi-upload\";\nimport { useMultiUpload } from \"../hooks/use-multi-upload\";\nimport type { UseUploadOptions, UseUploadReturn } from \"../hooks/use-upload\";\nimport { useUpload } from \"../hooks/use-upload\";\n\n/**\n * Render props passed to the UploadZone children function.\n * Provides access to drag-drop state, upload controls, and helper functions.\n *\n * @property dragDrop - Complete drag-and-drop state and event handlers\n * @property upload - Single upload hook (null when multiple=true)\n * @property multiUpload - Multi-upload hook (null when multiple=false)\n * @property openFilePicker - Programmatically trigger file selection dialog\n * @property isActive - True when dragging over zone or files selected\n * @property isProcessing - True when uploads are in progress\n */\nexport interface UploadZoneRenderProps {\n /**\n * Drag and drop state and handlers\n */\n dragDrop: UseDragDropReturn;\n\n /**\n * Single upload functionality (if not using multi-upload)\n */\n upload: UseUploadReturn | null;\n\n /**\n * Multi-upload functionality (if using multi-upload)\n */\n multiUpload: UseMultiUploadReturn | null;\n\n /**\n * Helper function to open file picker\n */\n openFilePicker: () => void;\n\n /**\n * Whether the zone is currently active (dragging or uploading)\n */\n isActive: boolean;\n\n /**\n * Whether files are being processed\n */\n isProcessing: boolean;\n}\n\n/**\n * Props for the UploadZone component.\n * Combines drag-drop options with upload configuration.\n *\n * @property multiple - Enable multi-file selection and upload (default: true)\n * @property multiUploadOptions - Configuration for multi-upload mode\n * @property uploadOptions - Configuration for single-upload mode\n * @property children - Render function receiving upload zone state\n * @property onUploadStart - Called when files pass validation and upload begins\n * @property onValidationError - Called when file validation fails\n * @property accept - Accepted file types (e.g., ['image/*', '.pdf'])\n * @property maxFiles - Maximum number of files allowed\n * @property maxFileSize - Maximum file size in bytes\n * @property validator - Custom validation function\n */\nexport interface UploadZoneProps\n extends Omit<DragDropOptions, \"onFilesReceived\"> {\n /**\n * Whether to enable multi-file upload mode\n */\n multiple?: boolean;\n\n /**\n * Multi-upload specific options (only used when multiple=true)\n */\n multiUploadOptions?: MultiUploadOptions;\n\n /**\n * Single upload specific options (only used when multiple=false)\n */\n uploadOptions?: UseUploadOptions;\n\n /**\n * Render prop that receives upload zone state and handlers\n */\n children: (props: UploadZoneRenderProps) => React.ReactNode;\n\n /**\n * Called when files are processed and uploads begin\n */\n onUploadStart?: (files: File[]) => void;\n\n /**\n * Called when validation errors occur\n */\n onValidationError?: (errors: string[]) => void;\n}\n\n/**\n * Headless upload zone component that combines drag and drop functionality\n * with upload management. Uses render props pattern for maximum flexibility.\n * Includes enhanced error handling for MIME type validation and file count validation.\n *\n * @param props - Upload zone configuration and render prop\n * @returns Rendered upload zone using the provided render prop\n *\n * @example\n * ```tsx\n * // Single file upload zone with error handling\n * <UploadZone\n * multiple={false}\n * accept={['image/*']}\n * maxFileSize={5 * 1024 * 1024}\n * onValidationError={(errors) => {\n * console.error('Validation errors:', errors);\n * }}\n * uploadOptions={{\n * onSuccess: (result) => console.log('Upload complete:', result),\n * onError: (error) => console.error('Upload failed:', error),\n * }}\n * >\n * {({ dragDrop, upload, openFilePicker, isActive }) => (\n * <div {...dragDrop.dragHandlers} onClick={openFilePicker}>\n * {dragDrop.state.isDragging ? (\n * <p>Drop file here...</p>\n * ) : upload?.isUploading ? (\n * <p>Uploading... {upload.state.progress}%</p>\n * ) : (\n * <p>Drag a file here or click to select</p>\n * )}\n *\n * {dragDrop.state.errors.length > 0 && (\n * <div style={{ color: 'red' }}>\n * {dragDrop.state.errors.map((error, index) => (\n * <p key={index}>{error}</p>\n * ))}\n * </div>\n * )}\n *\n * <input {...dragDrop.inputProps} />\n * </div>\n * )}\n * </UploadZone>\n * ```\n */\nexport function UploadZone({\n children,\n multiple = true,\n multiUploadOptions = {},\n uploadOptions = {},\n onUploadStart,\n onValidationError,\n ...dragDropOptions\n}: UploadZoneProps) {\n // Always initialize both hooks, but only use the appropriate one\n const singleUpload = useUpload(uploadOptions);\n const multiUpload = useMultiUpload(multiUploadOptions);\n\n // Enhanced validation function for better error handling\n const enhancedValidator = useCallback(\n (files: File[]): string[] | null => {\n const errors: string[] = [];\n\n // Check file count based on multiple setting\n if (!multiple && files.length > 1) {\n errors.push(\n `Single file mode is enabled. Please select only one file. You selected ${files.length} files.`,\n );\n }\n\n // Enhanced MIME type validation with better error messages\n if (dragDropOptions.accept && dragDropOptions.accept.length > 0) {\n const invalidFiles = files.filter((file) => {\n return !dragDropOptions.accept?.some((acceptType) => {\n if (acceptType.startsWith(\".\")) {\n // File extension check\n return file.name.toLowerCase().endsWith(acceptType.toLowerCase());\n } else {\n // MIME type check (supports wildcards like image/*)\n if (acceptType.endsWith(\"/*\")) {\n const baseType = acceptType.slice(0, -2);\n return file.type.startsWith(baseType);\n } else {\n return file.type === acceptType;\n }\n }\n });\n });\n\n if (invalidFiles.length > 0) {\n const fileNames = invalidFiles\n .map((f) => `\"${f.name}\" (${f.type})`)\n .join(\", \");\n const acceptedTypes = dragDropOptions.accept.join(\", \");\n errors.push(\n `Invalid file type(s): ${fileNames}. Accepted types: ${acceptedTypes}.`,\n );\n }\n }\n\n return errors.length > 0 ? errors : null;\n },\n [multiple, dragDropOptions.accept],\n );\n\n // Handle file processing\n const handleFilesReceived = (files: File[]) => {\n onUploadStart?.(files);\n\n if (multiple && multiUpload) {\n // Add files to multi-upload queue\n multiUpload.addFiles(files);\n\n // Auto-start uploads if configured to do so\n // Note: This could be made configurable with an autoStart prop\n setTimeout(() => multiUpload.startAll(), 0);\n } else if (!multiple && singleUpload && files.length > 0 && files[0]) {\n // Start single file upload\n singleUpload.upload(files[0]);\n }\n };\n\n // Handle validation errors\n const handleValidationError = useCallback(\n (errors: string[]) => {\n console.error(\"Upload zone validation errors:\", errors);\n // Call the custom error handler if provided\n onValidationError?.(errors);\n },\n [onValidationError],\n );\n\n // Initialize drag and drop with enhanced validation\n const dragDrop = useDragDrop({\n ...dragDropOptions,\n multiple,\n validator: enhancedValidator,\n onFilesReceived: handleFilesReceived,\n onValidationError: handleValidationError,\n });\n\n // Determine active state\n const isActive = dragDrop.state.isDragging || dragDrop.state.isOver;\n\n // Determine processing state\n const isProcessing = multiple\n ? (multiUpload?.state.isUploading ?? false)\n : (singleUpload?.isUploading ?? false);\n\n // Create render props object\n const renderProps: UploadZoneRenderProps = {\n dragDrop,\n upload: singleUpload,\n multiUpload,\n openFilePicker: dragDrop.openFilePicker,\n isActive,\n isProcessing,\n };\n\n return <>{children(renderProps)}</>;\n}\n\n/**\n * Props for the SimpleUploadZone component with built-in styling.\n *\n * @property className - CSS class name for custom styling\n * @property style - Inline styles for the upload zone container\n * @property text - Custom text labels for different states\n * @property text.idle - Text shown when zone is idle\n * @property text.dragging - Text shown when dragging files over zone\n * @property text.uploading - Text shown during upload\n * @property errorStyle - Custom styles for validation error display\n */\nexport interface SimpleUploadZoneProps extends UploadZoneProps {\n /**\n * Additional CSS class name for styling\n */\n className?: string;\n\n /**\n * Inline styles for the upload zone\n */\n style?: React.CSSProperties;\n\n /**\n * Custom text to display in different states\n */\n text?: {\n idle?: string;\n dragging?: string;\n uploading?: string;\n };\n\n /**\n * Custom error message styling\n */\n errorStyle?: React.CSSProperties;\n}\n\n/**\n * Simple pre-styled upload zone component with built-in UI and error handling.\n * Provides a ready-to-use drag-and-drop upload interface with minimal configuration.\n *\n * Features:\n * - Built-in drag-and-drop visual feedback\n * - Automatic progress display\n * - File validation error display\n * - Customizable text and styling\n * - Keyboard accessible\n *\n * @param props - Upload zone configuration with styling options\n * @returns Styled upload zone component\n *\n * @example\n * ```tsx\n * // Multi-file upload with validation\n * <SimpleUploadZone\n * multiple={true}\n * accept={['image/*', '.pdf']}\n * maxFiles={5}\n * maxFileSize={10 * 1024 * 1024} // 10MB\n * onUploadStart={(files) => console.log('Starting uploads:', files.length)}\n * onValidationError={(errors) => {\n * errors.forEach(err => console.error(err));\n * }}\n * multiUploadOptions={{\n * maxConcurrent: 3,\n * onComplete: (results) => {\n * console.log(`${results.successful.length}/${results.total} uploaded`);\n * },\n * }}\n * style={{\n * width: '400px',\n * height: '200px',\n * margin: '20px auto',\n * }}\n * text={{\n * idle: 'Drop your files here or click to browse',\n * dragging: 'Release to upload',\n * uploading: 'Uploading files...',\n * }}\n * errorStyle={{\n * backgroundColor: '#fff3cd',\n * borderColor: '#ffeaa7',\n * }}\n * />\n *\n * // Single file upload\n * <SimpleUploadZone\n * multiple={false}\n * accept={['image/*']}\n * uploadOptions={{\n * onSuccess: (result) => console.log('Uploaded:', result),\n * onError: (error) => console.error('Failed:', error),\n * }}\n * text={{\n * idle: 'Click or drag an image to upload',\n * }}\n * />\n * ```\n */\nexport function SimpleUploadZone({\n className = \"\",\n style = {},\n text = {},\n errorStyle = {},\n children,\n ...uploadZoneProps\n}: SimpleUploadZoneProps) {\n const defaultText = {\n idle: uploadZoneProps.multiple\n ? \"Drag files here or click to select\"\n : \"Drag a file here or click to select\",\n dragging: uploadZoneProps.multiple\n ? \"Drop files here...\"\n : \"Drop file here...\",\n uploading: \"Uploading...\",\n };\n\n const displayText = { ...defaultText, ...text };\n\n // If children render prop is provided, use UploadZone directly\n if (children) {\n return <UploadZone {...uploadZoneProps}>{children}</UploadZone>;\n }\n\n // Otherwise, provide default UI\n return (\n <UploadZone {...uploadZoneProps}>\n {({\n dragDrop,\n upload,\n multiUpload,\n openFilePicker,\n isActive,\n isProcessing,\n }) => (\n <button\n type=\"button\"\n onKeyDown={(e) => {\n if (e.key === \"Enter\" || e.key === \" \") {\n openFilePicker();\n }\n }}\n onKeyUp={(e) => {\n if (e.key === \"Enter\" || e.key === \" \") {\n openFilePicker();\n }\n }}\n {...dragDrop.dragHandlers}\n onClick={openFilePicker}\n className={`upload-zone ${isActive ? \"upload-zone--active\" : \"\"} ${isProcessing ? \"upload-zone--processing\" : \"\"} ${className}`}\n style={{\n border: isActive ? \"2px dashed #007bff\" : \"2px dashed #ccc\",\n borderRadius: \"8px\",\n padding: \"2rem\",\n textAlign: \"center\",\n cursor: \"pointer\",\n backgroundColor: isActive ? \"#f8f9fa\" : \"transparent\",\n transition: \"all 0.2s ease\",\n minHeight: \"120px\",\n display: \"flex\",\n flexDirection: \"column\",\n alignItems: \"center\",\n justifyContent: \"center\",\n ...style,\n }}\n >\n {dragDrop.state.isDragging ? (\n <p style={{ margin: 0, fontSize: \"16px\", color: \"#007bff\" }}>\n {displayText.dragging}\n </p>\n ) : isProcessing ? (\n <div style={{ textAlign: \"center\" }}>\n <p style={{ margin: \"0 0 10px 0\", fontSize: \"14px\" }}>\n {displayText.uploading}\n </p>\n {upload && (\n <div>\n <progress\n value={upload.state.progress}\n max={100}\n style={{ width: \"200px\", height: \"8px\" }}\n />\n <p\n style={{\n margin: \"5px 0 0 0\",\n fontSize: \"12px\",\n color: \"#666\",\n }}\n >\n {upload.state.progress}%\n </p>\n </div>\n )}\n {multiUpload && (\n <div>\n <progress\n value={multiUpload.state.progress}\n max={100}\n style={{ width: \"200px\", height: \"8px\" }}\n />\n <p\n style={{\n margin: \"5px 0 0 0\",\n fontSize: \"12px\",\n color: \"#666\",\n }}\n >\n {multiUpload.state.progress}% ({multiUpload.state.uploading}{\" \"}\n uploading, {multiUpload.state.successful} completed)\n </p>\n </div>\n )}\n </div>\n ) : (\n <p style={{ margin: 0, fontSize: \"16px\", color: \"#666\" }}>\n {displayText.idle}\n </p>\n )}\n\n {dragDrop.state.errors.length > 0 && (\n <div\n style={{\n marginTop: \"10px\",\n padding: \"8px 12px\",\n backgroundColor: \"#f8d7da\",\n border: \"1px solid #f5c6cb\",\n borderRadius: \"4px\",\n maxWidth: \"100%\",\n ...errorStyle,\n }}\n >\n <p\n style={{\n margin: \"0 0 5px 0\",\n fontSize: \"12px\",\n fontWeight: \"bold\",\n color: \"#721c24\",\n }}\n >\n Validation Errors:\n </p>\n {dragDrop.state.errors.map((error, index) => (\n <p\n // biome-ignore lint/suspicious/noArrayIndexKey: index is used as key\n key={index}\n style={{\n color: \"#721c24\",\n fontSize: \"11px\",\n margin: \"2px 0\",\n lineHeight: \"1.3\",\n }}\n >\n • {error}\n </p>\n ))}\n </div>\n )}\n\n <input {...dragDrop.inputProps} />\n </button>\n )}\n </UploadZone>\n );\n}\n"],"mappings":"oKA4CA,SAAgB,EAAU,CACxB,QACA,SAAS,IACT,WAAW,GACX,QACA,WACA,WAAW,GACX,YAAY,IACK,CACjB,IAAM,EAAc,aAAiB,KAC/B,EAAa,OAAO,GAAU,UAAY,EAAM,OAAS,EAGzD,EAAqB,EAAM,aAAe,qBAC1C,EACJ,IACC,EAAM,aAAe,gBACpB,EAAM,aAAe,sBAEnB,EAAW,EAAY,CAC3B,gBAAkB,GAAU,CACtB,EAAM,IACR,EAAS,EAAM,GAAG,EAGtB,OAAQ,EAAS,EAAO,MAAM,IAAI,CAAC,IAAK,GAAS,EAAK,MAAM,CAAC,CAAG,IAAA,GAChE,SAAU,GACX,CAAC,CASI,EAAmB,GAA2C,CAClE,EAAS,EAAE,OAAO,MAAM,EAGpB,MAAoB,CACxB,EAAS,GAAG,EAGd,OACE,EAAC,MAAA,CAAI,UAAW,aAAa,cAE3B,EAAC,MAAA,CAAA,SAAA,CACC,EAAC,MAAA,CAAI,UAAU,yCACb,EA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,YACR,SAAU,OACV,MAAO,OACR,WAEA,EAAY,MAAM,SAAS,MAAI,EAAY,MAAM,UAAW,IAAI,cACrD,EAAY,MAAM,WAAW,gBACvC,CAAA,CAAA,CACA,GAEJ,CAEN,EAAC,IAAA,CAAE,MAAO,CAAE,OAAQ,EAAG,SAAU,OAAQ,MAAO,OAAQ,UACrD,EAAY,MACX,CAGL,EAAS,MAAM,OAAO,OAAS,GAC9B,EAAC,MAAA,CACC,MAAO,CACL,UAAW,OACX,QAAS,WACT,gBAAiB,UACjB,OAAQ,oBACR,aAAc,MACd,SAAU,OACV,GAAG,EACJ,WAED,EAAC,IAAA,CACC,MAAO,CACL,OAAQ,YACR,SAAU,OACV,WAAY,OACZ,MAAO,UACR,UACF,sBAEG,CACH,EAAS,MAAM,OAAO,KAAK,EAAO,IACjC,EAAC,IAAA,CAGC,MAAO,CACL,MAAO,UACP,SAAU,OACV,OAAQ,QACR,WAAY,MACb,WACF,KACI,EAAA,EARE,EASH,CACJ,CAAA,EACE,CAGR,EAAC,QAAA,CAAM,GAAI,EAAS,WAAA,CAAc,GAC3B,EAEA"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{s as e,u as t}from"./use-upload-BDHVhQsI.mjs";import{EventType as n}from"@uploadista/core/flow";import{UploadEventType as r}from"@uploadista/core/types";import i,{useCallback as a,useEffect as o,useRef as s,useState as c}from"react";function l(e){if(!(`eventType`in e))return!1;let t=e;return t.eventType===n.JobStart||t.eventType===n.JobEnd||t.eventType===n.FlowStart||t.eventType===n.FlowEnd||t.eventType===n.FlowError||t.eventType===n.FlowPause||t.eventType===n.FlowCancel||t.eventType===n.NodeStart||t.eventType===n.NodeEnd||t.eventType===n.NodePause||t.eventType===n.NodeResume||t.eventType===n.NodeError||t.eventType===n.NodeStream||t.eventType===n.NodeResponse}function u(e){if(!(`type`in e))return!1;let t=e;return t.type===r.UPLOAD_STARTED||t.type===r.UPLOAD_PROGRESS||t.type===r.UPLOAD_COMPLETE||t.type===r.UPLOAD_FAILED||t.type===r.UPLOAD_VALIDATION_SUCCESS||t.type===r.UPLOAD_VALIDATION_FAILED||t.type===r.UPLOAD_VALIDATION_WARNING}function d(t){let{subscribeToEvents:n}=e();o(()=>n(t),[n,t])}function f(t){let{subscribeToEvents:r}=e();o(()=>r(e=>{if(l(e))switch(e.eventType){case n.JobStart:t.onJobStart?.(e);break;case n.JobEnd:t.onJobEnd?.(e);break;case n.FlowStart:t.onFlowStart?.(e);break;case n.FlowEnd:t.onFlowEnd?.(e);break;case n.FlowError:t.onFlowError?.(e);break;case n.FlowPause:t.onFlowPause?.(e);break;case n.FlowCancel:t.onFlowCancel?.(e);break;case n.NodeStart:t.onNodeStart?.(e);break;case n.NodeEnd:t.onNodeEnd?.(e);break;case n.NodePause:t.onNodePause?.(e);break;case n.NodeResume:t.onNodeResume?.(e);break;case n.NodeError:t.onNodeError?.(e);break}}),[r,t])}function p(t){let{subscribeToEvents:n}=e();o(()=>n(e=>{if(!u(e))return;let n=`flow`in e?e.flow:void 0;switch(e.type){case r.UPLOAD_STARTED:t.onUploadStarted?.({...e.data,flow:n});break;case r.UPLOAD_PROGRESS:t.onUploadProgress?.({...e.data,flow:n});break;case r.UPLOAD_COMPLETE:t.onUploadComplete?.({...e.data,flow:n});break;case r.UPLOAD_FAILED:t.onUploadFailed?.({...e.data,flow:n});break;case r.UPLOAD_VALIDATION_SUCCESS:t.onUploadValidationSuccess?.({...e.data,flow:n});break;case r.UPLOAD_VALIDATION_FAILED:t.onUploadValidationFailed?.({...e.data,flow:n});break;case r.UPLOAD_VALIDATION_WARNING:t.onUploadValidationWarning?.({...e.data,flow:n});break}}),[n,t])}const m={status:`idle`,progress:0,bytesUploaded:0,totalBytes:null,error:null,jobId:null,flowStarted:!1,currentNodeName:null,currentNodeType:null,flowOutputs:null};function h(n){let{client:r}=e(),{getManager:i,releaseManager:l}=t(),[u,d]=c(m),[f,p]=c(null),[h,g]=c(!1),[_,v]=c({}),[y,b]=c(new Map),x=s(null),S=s(n);return o(()=>{S.current=n}),o(()=>{(async()=>{g(!0);try{let{flow:e}=await r.getFlow(n.flowConfig.flowId),t=e.nodes.filter(e=>e.type===`input`);console.log(`inputNodes`,t),p(t.map(e=>({nodeId:e.id,nodeName:e.name,nodeDescription:e.description,nodeTypeId:e.nodeTypeId,required:!0})))}catch(e){console.error(`Failed to discover flow inputs:`,e)}finally{g(!1)}})()},[r,n.flowConfig.flowId]),o(()=>{let e=n.flowConfig.flowId;x.current=i(e,{onStateChange:e=>{d(e)},onProgress:(e,t,n)=>{S.current.onProgress?.(e,t,n)},onChunkComplete:(e,t,n)=>{S.current.onChunkComplete?.(e,t,n)},onFlowComplete:e=>{S.current.onFlowComplete?.(e)},onSuccess:e=>{S.current.onSuccess?.(e)},onError:e=>{S.current.onError?.(e)},onAbort:()=>{S.current.onAbort?.()}},n);let t=setInterval(()=>{if(x.current){let e=x.current.getInputStates();e.size>0&&b(new Map(e))}},100);return()=>{clearInterval(t),l(e),x.current=null}},[n.flowConfig.flowId,n.flowConfig.storageId,n.flowConfig.outputNodeId,i,l]),{state:u,inputMetadata:f,inputStates:y,inputs:_,setInput:a((e,t)=>{v(n=>({...n,[e]:t}))},[]),execute:a(async()=>{if(!x.current)throw Error(`FlowManager not initialized`);if(Object.keys(_).length===0)throw Error(`No inputs provided. Use setInput() to provide inputs before calling execute()`);await x.current.executeFlow(_)},[_]),upload:a(async e=>{if(!x.current)throw Error(`FlowManager not initialized`);if(f&&f.length>0){let t=f[0];if(!t)throw Error(`No input nodes found`);v({[t.nodeId]:e}),await x.current.executeFlow({[t.nodeId]:e})}else await x.current.upload(e)},[f]),abort:a(()=>{x.current?.abort()},[]),pause:a(()=>{x.current?.pause()},[]),reset:a(()=>{x.current?.reset(),v({}),b(new Map)},[]),isUploading:u.status===`uploading`||u.status===`processing`,isUploadingFile:u.status===`uploading`,isProcessing:u.status===`processing`,isDiscoveringInputs:h}}const g={status:`idle`,progress:0,bytesUploaded:0,totalBytes:null,error:null,jobId:null,flowStarted:!1,currentNodeName:null,currentNodeType:null,flowOutputs:null};function _(n){let{client:r}=e(),{getManager:i,releaseManager:l}=t(),[u,d]=c(g),f=s(null),p=s(n),m=s(n.inputBuilder);return o(()=>{p.current=n,m.current=n.inputBuilder}),o(()=>{let e=n.flowConfig.flowId;return f.current=i(e,{onStateChange:d,onProgress:(e,t,n)=>{p.current.onProgress?.(e,t,n)},onChunkComplete:(e,t,n)=>{p.current.onChunkComplete?.(e,t,n)},onFlowComplete:e=>{p.current.onFlowComplete?.(e)},onSuccess:e=>{p.current.onSuccess?.(e)},onError:e=>{p.current.onError?.(e)},onAbort:()=>{p.current.onAbort?.()}},{flowConfig:n.flowConfig}),()=>{f.current&&=(l(e),null)}},[n.flowConfig.flowId,i,l,n]),{state:u,execute:a(async e=>{try{let t=await m.current(e),i=Object.keys(t)[0];if(!i)throw Error(`flowInputs must contain at least one input node`);let a=t[i];typeof a==`object`&&a&&`operation`in a&&a.operation===`init`?f.current&&await f.current.upload(e):(d(e=>({...e,status:`processing`,flowStarted:!0})),(await r.executeFlowWithInputs(n.flowConfig.flowId,t,{storageId:n.flowConfig.storageId,onJobStart:e=>{d(t=>({...t,jobId:e})),p.current.onJobStart?.(e)}})).job?.id||d(e=>({...e,status:`success`,progress:100,flowStarted:!0})))}catch(e){let t=e instanceof Error?e:Error(String(e));d(e=>({...e,status:`error`,error:t})),p.current.onError?.(t)}},[]),abort:a(()=>{f.current&&f.current.abort()},[]),pause:a(()=>{f.current&&f.current.pause()},[]),reset:a(()=>{if(f.current){let e=n.flowConfig.flowId;f.current.reset(),f.current.cleanup(),l(e),f.current=null}d(g)},[n.flowConfig.flowId,l]),isExecuting:u.status===`uploading`||u.status===`processing`,isUploadingFile:u.status===`uploading`,isProcessing:u.status===`processing`}}const v={totalBytesUploaded:0,totalBytes:0,averageSpeed:0,currentSpeed:0,estimatedTimeRemaining:null,totalFiles:0,completedFiles:0,activeUploads:0,progress:0,peakSpeed:0,startTime:null,endTime:null,totalDuration:null,insights:{overallEfficiency:0,chunkingEffectiveness:0,networkStability:0,recommendations:[],optimalChunkSizeRange:{min:256*1024,max:2*1024*1024}},sessionMetrics:[],chunkMetrics:[]};function y(t={}){let{speedCalculationInterval:n=1e3,speedSampleSize:r=10,onMetricsUpdate:o,onFileStart:l,onFileProgress:u,onFileComplete:d}=t,f=e(),[p,m]=c(v),[h,g]=c([]),_=s([]),y=s(0),b=s(null),x=a((e,t)=>{let n={time:e,bytes:t};_.current.push(n),_.current.length>r&&(_.current=_.current.slice(-r));let i=0;if(_.current.length>=2){let e=_.current[_.current.length-1],t=_.current[_.current.length-2];if(e&&t){let n=(e.time-t.time)/1e3,r=e.bytes-t.bytes;i=n>0?r/n:0}}let a=0;if(_.current.length>=2){let e=_.current[0],t=_.current[_.current.length-1];if(e&&t){let n=(t.time-e.time)/1e3,r=t.bytes-e.bytes;a=n>0?r/n:0}}return{currentSpeed:i,averageSpeed:a}},[r]),S=a(()=>{let e=Date.now(),t=h.reduce((e,t)=>e+t.size,0),n=h.reduce((e,t)=>e+t.bytesUploaded,0),r=h.filter(e=>e.isComplete).length,i=h.filter(e=>!e.isComplete&&e.bytesUploaded>0).length,{currentSpeed:a,averageSpeed:s}=x(e,n),c=t>0?Math.round(n/t*100):0,l=null;a>0&&(l=(t-n)/a*1e3);let u=h.filter(e=>e.startTime>0),d=u.length>0?Math.min(...u.map(e=>e.startTime)):null,g=h.filter(e=>e.endTime!==null),_=g.length>0&&r===h.length?Math.max(...g.map(e=>e.endTime).filter(e=>e!==null)):null,v=d&&_?_-d:null,y={totalBytesUploaded:n,totalBytes:t,averageSpeed:s,currentSpeed:a,estimatedTimeRemaining:l,totalFiles:h.length,completedFiles:r,activeUploads:i,progress:c,peakSpeed:Math.max(p.peakSpeed,a),startTime:d,endTime:_,totalDuration:v,insights:f.client.getChunkingInsights(),sessionMetrics:[f.client.exportMetrics().session],chunkMetrics:f.client.exportMetrics().chunks};m(y),o?.(y)},[h,p.peakSpeed,x,o,f.client]),C=a(()=>(b.current&&clearInterval(b.current),b.current=setInterval(()=>{h.some(e=>!e.isComplete&&e.bytesUploaded>0)&&S()},n),()=>{b.current&&=(clearInterval(b.current),null)}),[n,S,h]),w=a((e,t,n)=>{let r={id:e,filename:t,size:n,bytesUploaded:0,progress:0,speed:0,startTime:Date.now(),endTime:null,duration:null,isComplete:!1};g(t=>t.find(t=>t.id===e)?t.map(t=>t.id===e?r:t):[...t,r]),l?.(r),h.filter(e=>!e.isComplete).length===0&&C()},[h,l,C]),T=a((e,t)=>{let n=Date.now();g(r=>r.map(r=>{if(r.id!==e)return r;let i=(n-r.startTime)/1e3,a=i>0?t/i:0,o=r.size>0?Math.round(t/r.size*100):0,s={...r,bytesUploaded:t,progress:o,speed:a};return u?.(s),s})),setTimeout(S,0)},[u,S]),E=a(e=>{let t=Date.now();g(n=>n.map(n=>{if(n.id!==e)return n;let r=t-n.startTime,i=r>0?n.size/r*1e3:0,a={...n,bytesUploaded:n.size,progress:100,speed:i,endTime:t,duration:r,isComplete:!0};return d?.(a),a})),setTimeout(S,0)},[d,S]),D=a(e=>{g(t=>t.filter(t=>t.id!==e)),setTimeout(S,0)},[S]),O=a(()=>{b.current&&=(clearInterval(b.current),null),m(v),g([]),_.current=[],y.current=0},[]),k=a(e=>h.find(t=>t.id===e),[h]),A=a(()=>({overall:p,files:h,exportTime:Date.now()}),[p,h]);return i.useEffect(()=>()=>{b.current&&clearInterval(b.current)},[]),{metrics:p,fileMetrics:h,startFileUpload:w,updateFileProgress:T,completeFileUpload:E,removeFile:D,reset:O,getFileMetrics:k,exportMetrics:A}}export{f as a,u as c,p as i,_ as n,d as o,h as r,l as s,y as t};
|
|
2
|
-
//# sourceMappingURL=use-upload-metrics-OAofTcgA.mjs.map
|