feat: show upload snippet on input
This commit is contained in:
parent
5aef778fc5
commit
15f9dc3526
|
|
@ -4,6 +4,7 @@ import { useState, useEffect, useRef, DragEvent, ChangeEvent } from 'react';
|
|||
import { MinimizedApiKey } from '@/components/demo/MinimizedApiKey';
|
||||
import { CodeExamplesWidget } from '@/components/demo/CodeExamplesWidget';
|
||||
import { ImageZoomModal } from '@/components/demo/ImageZoomModal';
|
||||
import { SelectedFileCodePreview } from '@/components/demo/SelectedFileCodePreview';
|
||||
|
||||
const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000';
|
||||
const API_KEY_STORAGE_KEY = 'banatie_demo_api_key';
|
||||
|
|
@ -330,14 +331,25 @@ export default function DemoUploadPage() {
|
|||
};
|
||||
|
||||
const generateUploadCodeExamples = (item: UploadHistoryItem, key: string, baseUrl: string) => {
|
||||
const localPath = `./${item.originalName}`;
|
||||
const fileName = item.originalName;
|
||||
|
||||
return {
|
||||
curl: `curl -X POST "${baseUrl}/api/upload" \\
|
||||
curl: `# Navigate to your images folder
|
||||
cd /your/images/folder
|
||||
|
||||
# Upload the file
|
||||
curl -X POST "${baseUrl}/api/upload" \\
|
||||
-H "X-API-Key: ${key}" \\
|
||||
-F "file=@${localPath}"`,
|
||||
fetch: `const formData = new FormData();
|
||||
formData.append('file', fileInput.files[0]);
|
||||
-F "file=@${fileName}"`,
|
||||
fetch: `// Set your images folder path
|
||||
const imagePath = '/your/images/folder';
|
||||
const fileName = '${fileName}';
|
||||
|
||||
// For Node.js with fs module:
|
||||
const fs = require('fs');
|
||||
const FormData = require('form-data');
|
||||
const formData = new FormData();
|
||||
formData.append('file', fs.createReadStream(\`\${imagePath}/\${fileName}\`));
|
||||
|
||||
fetch('${baseUrl}/api/upload', {
|
||||
method: 'POST',
|
||||
|
|
@ -349,13 +361,15 @@ fetch('${baseUrl}/api/upload', {
|
|||
.then(response => response.json())
|
||||
.then(data => console.log(data))
|
||||
.catch(error => console.error('Error:', error));`,
|
||||
rest: `POST ${baseUrl}/api/upload
|
||||
rest: `# From your images folder: /your/images/folder
|
||||
|
||||
POST ${baseUrl}/api/upload
|
||||
Headers:
|
||||
X-API-Key: ${key}
|
||||
Content-Type: multipart/form-data
|
||||
|
||||
Body (form-data):
|
||||
file: @${localPath}`,
|
||||
file: @${fileName}`,
|
||||
};
|
||||
};
|
||||
|
||||
|
|
@ -545,6 +559,17 @@ Body (form-data):
|
|||
</p>
|
||||
)}
|
||||
|
||||
{selectedFile && apiKeyValidated && !validationError && (
|
||||
<div className="mt-6">
|
||||
<SelectedFileCodePreview
|
||||
file={selectedFile}
|
||||
apiKey={apiKey}
|
||||
apiBaseUrl={API_BASE_URL}
|
||||
onCopy={handleCopyCode}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex items-center justify-between gap-4 flex-wrap pt-4 mt-4 border-t border-slate-700/50">
|
||||
<div className="text-sm text-gray-500">
|
||||
{uploading ? 'Uploading...' : selectedFile ? 'Ready to upload' : 'No file selected'}
|
||||
|
|
|
|||
|
|
@ -2,6 +2,25 @@
|
|||
|
||||
import { useState } from 'react';
|
||||
|
||||
/**
|
||||
* Production-ready code examples widget.
|
||||
*
|
||||
* Core Principle: All code snippets are designed to be COPY-PASTE-AND-RUN ready.
|
||||
* Users should be able to copy the code, replace the placeholder folder path,
|
||||
* and execute it immediately on their machine with minimal edits.
|
||||
*
|
||||
* Pattern Used:
|
||||
* - Navigate to folder (with placeholder path: /your/images/folder)
|
||||
* - Use actual filename from selected/uploaded file
|
||||
* - Clear comments showing what to replace
|
||||
*
|
||||
* @example
|
||||
* // User has file at: /home/user/Downloads/sunset.jpg
|
||||
* // Code shows: cd /your/images/folder; curl ... -F "file=@sunset.jpg"
|
||||
* // User replaces: /your/images/folder → /home/user/Downloads
|
||||
* // Result: Works immediately after one simple edit!
|
||||
*/
|
||||
|
||||
type CodeTab = 'curl' | 'fetch' | 'rest';
|
||||
|
||||
interface CodeExamplesWidgetProps {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,206 @@
|
|||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { CodeExamplesWidget } from './CodeExamplesWidget';
|
||||
|
||||
/**
|
||||
* SelectedFileCodePreview Component
|
||||
*
|
||||
* Shows code snippets for uploading a selected file BEFORE upload.
|
||||
* Helps users understand they can either:
|
||||
* 1. Upload via UI button
|
||||
* 2. Copy code and run programmatically
|
||||
*
|
||||
* Layout:
|
||||
* - Mobile: Stacked vertically
|
||||
* - Desktop: 3-column grid (1 col preview + 2 cols code)
|
||||
*/
|
||||
|
||||
interface SelectedFileCodePreviewProps {
|
||||
file: File;
|
||||
apiKey: string;
|
||||
apiBaseUrl: string;
|
||||
onCopy: (text: string) => void;
|
||||
}
|
||||
|
||||
export const SelectedFileCodePreview = ({
|
||||
file,
|
||||
apiKey,
|
||||
apiBaseUrl,
|
||||
onCopy,
|
||||
}: SelectedFileCodePreviewProps) => {
|
||||
const [previewUrl, setPreviewUrl] = useState<string>('');
|
||||
|
||||
// Create and cleanup preview URL
|
||||
useEffect(() => {
|
||||
const objectUrl = URL.createObjectURL(file);
|
||||
setPreviewUrl(objectUrl);
|
||||
|
||||
return () => {
|
||||
URL.revokeObjectURL(objectUrl);
|
||||
};
|
||||
}, [file]);
|
||||
|
||||
const codeExamples = generateSelectedFileCodeExamples(file, apiKey, apiBaseUrl);
|
||||
|
||||
return (
|
||||
<section className="space-y-4" aria-label="Selected File Code Preview">
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="text-xl md:text-2xl font-bold text-white">
|
||||
Selected File - Code Preview
|
||||
</h2>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
|
||||
{/* Column 1: Compact File Preview Card */}
|
||||
<div className="lg:col-span-1">
|
||||
<div className="p-4 bg-slate-900/80 backdrop-blur-sm border border-slate-700 rounded-xl h-full">
|
||||
{/* Image Preview - Compact */}
|
||||
<div className="aspect-video bg-slate-800 rounded-lg mb-3 overflow-hidden max-h-32">
|
||||
<img
|
||||
src={previewUrl}
|
||||
alt={`Preview of ${file.name}`}
|
||||
className="w-full h-full object-cover"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* File Metadata */}
|
||||
<div className="space-y-2">
|
||||
<p
|
||||
className="text-white text-sm font-medium truncate"
|
||||
title={file.name}
|
||||
>
|
||||
{file.name}
|
||||
</p>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-2 text-xs">
|
||||
{/* File Size */}
|
||||
<span className="px-2 py-1 bg-slate-700/50 text-gray-300 rounded">
|
||||
{formatFileSize(file.size)}
|
||||
</span>
|
||||
|
||||
{/* File Type Badge */}
|
||||
<span className="px-2 py-1 bg-purple-600/20 text-purple-400 rounded border border-purple-600/30">
|
||||
{getFileType(file.name)}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Status Badge */}
|
||||
<div className="pt-2">
|
||||
<span className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-amber-600/20 text-amber-400 rounded border border-amber-600/30 text-xs font-medium">
|
||||
<svg
|
||||
className="w-3.5 h-3.5"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"
|
||||
/>
|
||||
</svg>
|
||||
Ready to Upload
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Helper Text */}
|
||||
<p className="text-xs text-gray-500 pt-2">
|
||||
Click upload button or copy code to run programmatically
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Columns 2-3: Code Examples Widget */}
|
||||
<div className="lg:col-span-2">
|
||||
<CodeExamplesWidget
|
||||
codeExamples={codeExamples}
|
||||
onCopy={onCopy}
|
||||
defaultTab="curl"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Generate production-ready code examples for selected file upload
|
||||
*
|
||||
* Pattern: Users navigate to their folder, then run the upload command.
|
||||
* This matches how real workflows work - users know where their file is.
|
||||
*/
|
||||
const generateSelectedFileCodeExamples = (
|
||||
file: File,
|
||||
apiKey: string,
|
||||
apiBaseUrl: string
|
||||
) => {
|
||||
const fileName = file.name;
|
||||
|
||||
return {
|
||||
curl: `# Navigate to your images folder
|
||||
cd /your/images/folder
|
||||
|
||||
# Upload the file
|
||||
curl -X POST "${apiBaseUrl}/api/upload" \\
|
||||
-H "X-API-Key: ${apiKey}" \\
|
||||
-F "file=@${fileName}"`,
|
||||
|
||||
fetch: `// Set your images folder path
|
||||
const imagePath = '/your/images/folder';
|
||||
const fileName = '${fileName}';
|
||||
|
||||
// For Node.js with fs module:
|
||||
const fs = require('fs');
|
||||
const FormData = require('form-data');
|
||||
const formData = new FormData();
|
||||
formData.append('file', fs.createReadStream(\`\${imagePath}/\${fileName}\`));
|
||||
|
||||
fetch('${apiBaseUrl}/api/upload', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'X-API-Key': '${apiKey}'
|
||||
},
|
||||
body: formData
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => console.log(data))
|
||||
.catch(error => console.error('Error:', error));`,
|
||||
|
||||
rest: `# From your images folder: /your/images/folder
|
||||
|
||||
POST ${apiBaseUrl}/api/upload
|
||||
Headers:
|
||||
X-API-Key: ${apiKey}
|
||||
Content-Type: multipart/form-data
|
||||
|
||||
Body (form-data):
|
||||
file: @${fileName}`,
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Format file size in human-readable format
|
||||
*/
|
||||
const formatFileSize = (bytes: number): string => {
|
||||
if (bytes === 0) return '0 B';
|
||||
const k = 1024;
|
||||
const sizes = ['B', 'KB', 'MB', 'GB'];
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
||||
return `${(bytes / Math.pow(k, i)).toFixed(1)} ${sizes[i]}`;
|
||||
};
|
||||
|
||||
/**
|
||||
* Extract file type from filename
|
||||
*/
|
||||
const getFileType = (filename: string): string => {
|
||||
const extension = filename.split('.').pop()?.toUpperCase();
|
||||
if (extension === 'JPG' || extension === 'JPEG') return 'JPEG';
|
||||
if (extension === 'PNG') return 'PNG';
|
||||
if (extension === 'WEBP') return 'WebP';
|
||||
if (extension === 'GIF') return 'GIF';
|
||||
return extension || 'FILE';
|
||||
};
|
||||
Loading…
Reference in New Issue