528 lines
18 KiB
JavaScript
528 lines
18 KiB
JavaScript
import React, { useState, useEffect, useRef } from "react";
|
|
import MDEditor, { commands } from '@uiw/react-md-editor';
|
|
import { Input } from './ui/input';
|
|
import { Label } from './ui/label';
|
|
import { Select, SelectTrigger, SelectValue, SelectContent, SelectItem } from './ui/select';
|
|
import { Button } from './ui/button';
|
|
import { Separator } from './ui/separator';
|
|
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from './ui/dialog';
|
|
import { CustomTabs } from './ui/tabs';
|
|
|
|
|
|
const TOPIC_API_URL = 'https://host-api.cs1.hz.siliconpin.com/v1/topics/';
|
|
const MINIO_UPLOAD_URL = 'https://your-minio-api-endpoint/upload';
|
|
const urlParams = new URLSearchParams(window.location.search);
|
|
const slug = urlParams.get('slug');
|
|
// console.log('find slug from url', slug);
|
|
export default function EditTopic (){
|
|
// const { slug } = useParams();
|
|
// const navigate = useNavigate();
|
|
// Form state
|
|
const [formData, setFormData] = useState({ status: 'draft', category: '', slug: '', title: '', content: '', imageUrl: '' });
|
|
// UI state
|
|
const [isSubmitting, setIsSubmitting] = useState(false);
|
|
const [isLoading, setIsLoading] = useState(true);
|
|
const [error, setError] = useState(null);
|
|
const [success, setSuccess] = useState(false);
|
|
const [imageFile, setImageFile] = useState(null);
|
|
const [uploadProgress, setUploadProgress] = useState(0);
|
|
const [imageDialogOpen, setImageDialogOpen] = useState(false);
|
|
const [imageUrlInput, setImageUrlInput] = useState('');
|
|
const [imageUploadFile, setImageUploadFile] = useState(null);
|
|
const [imageUploadPreview, setImageUploadPreview] = useState('');
|
|
const [editorMode, setEditorMode] = useState('edit');
|
|
|
|
// Fetch topic data on component mount
|
|
useEffect(() => {
|
|
const fetchTopic = async () => {
|
|
try {
|
|
const response = await fetch(`${TOPIC_API_URL}?query=get-single-topic&slug=${slug}`, {
|
|
credentials: 'include'
|
|
});
|
|
|
|
if (!response.ok) {
|
|
throw new Error('Failed to fetch topic');
|
|
}
|
|
|
|
const data = await response.json();
|
|
const topic = data.data[0]
|
|
console.log('Single topic data', data)
|
|
setFormData({
|
|
status: topic.status || 'draft',
|
|
category: topic.category || '',
|
|
title: topic.title || '',
|
|
slug: topic.slug || '',
|
|
content: topic.content || '',
|
|
imageUrl: topic.imageUrl || ''
|
|
});
|
|
} catch (err) {
|
|
setError(err.message);
|
|
} finally {
|
|
setIsLoading(false);
|
|
}
|
|
};
|
|
|
|
fetchTopic();
|
|
}, [slug]);
|
|
|
|
// Upload file to MinIO (same as NewTopic)
|
|
const uploadToMinIO = async (file, onProgress) => {
|
|
const formData = new FormData();
|
|
formData.append('file', file);
|
|
formData.append('bucket', 'siliconpin-uploads');
|
|
formData.append('folder', 'topic-images');
|
|
|
|
try {
|
|
const response = await fetch(MINIO_UPLOAD_URL, {
|
|
method: 'POST',
|
|
body: formData,
|
|
credentials: 'include',
|
|
});
|
|
|
|
if (!response.ok) {
|
|
throw new Error('Upload failed');
|
|
}
|
|
|
|
const data = await response.json();
|
|
return data.url;
|
|
} catch (error) {
|
|
console.error('Upload error:', error);
|
|
throw error;
|
|
}
|
|
};
|
|
|
|
// Generate slug from title (same as NewTopic)
|
|
// useEffect(() => {
|
|
// if (formData.title) {
|
|
// const newSlug = formData.title
|
|
// .toLowerCase()
|
|
// .replace(/[^\w\s]/g, '')
|
|
// .replace(/\s+/g, '-');
|
|
// setFormData(prev => ({ ...prev, slug: newSlug }));
|
|
// }
|
|
// }, [formData.title]);
|
|
|
|
// Custom image command for MDEditor (same as NewTopic)
|
|
const customImageCommand = {
|
|
name: 'image',
|
|
keyCommand: 'image',
|
|
buttonProps: { 'aria-label': 'Insert image' },
|
|
icon: (
|
|
<svg width="12" height="12" viewBox="0 0 20 20">
|
|
<path fill="currentColor" d="M15 9c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm4-7H1c-.55 0-1 .45-1 1v14c0 .55.45 1 1 1h18c.55 0 1-.45 1-1V3c0-.55-.45-1-1-1zm-1 13l-6-5-2 2-4-5-4 8V4h16v11z"/>
|
|
</svg>
|
|
),
|
|
execute: () => {
|
|
setImageDialogOpen(true);
|
|
},
|
|
};
|
|
|
|
// Get all commands (same as NewTopic)
|
|
const allCommands = commands.getCommands().map(cmd => {
|
|
if (cmd.name === 'image') {
|
|
return customImageCommand;
|
|
}
|
|
return cmd;
|
|
});
|
|
|
|
// Handle image URL insertion (same as NewTopic)
|
|
const handleInsertImageUrl = () => {
|
|
if (imageUrlInput) {
|
|
const imgMarkdown = ``;
|
|
const textarea = document.querySelector('.w-md-editor-text-input');
|
|
if (textarea) {
|
|
const startPos = textarea.selectionStart;
|
|
const endPos = textarea.selectionEnd;
|
|
const currentValue = formData.content;
|
|
|
|
const newValue =
|
|
currentValue.substring(0, startPos) +
|
|
imgMarkdown +
|
|
currentValue.substring(endPos);
|
|
|
|
setFormData(prev => ({ ...prev, content: newValue }));
|
|
}
|
|
setImageDialogOpen(false);
|
|
setImageUrlInput('');
|
|
}
|
|
};
|
|
|
|
// Handle image file selection (same as NewTopic)
|
|
const handleImageFileSelect = (e) => {
|
|
const file = e.target.files[0];
|
|
if (file) {
|
|
setImageUploadFile(file);
|
|
|
|
const reader = new FileReader();
|
|
reader.onload = () => {
|
|
setImageUploadPreview(reader.result);
|
|
};
|
|
reader.readAsDataURL(file);
|
|
}
|
|
};
|
|
|
|
// Upload image file (same as NewTopic)
|
|
const handleImageUpload = async () => {
|
|
if (!imageUploadFile) return;
|
|
|
|
try {
|
|
setIsSubmitting(true);
|
|
setUploadProgress(0);
|
|
|
|
const uploadedUrl = await uploadToMinIO(imageUploadFile, (progress) => {
|
|
setUploadProgress(progress);
|
|
});
|
|
|
|
const imgMarkdown = ``;
|
|
const textarea = document.querySelector('.w-md-editor-text-input');
|
|
if (textarea) {
|
|
const startPos = textarea.selectionStart;
|
|
const endPos = textarea.selectionEnd;
|
|
const currentValue = formData.content;
|
|
|
|
const newValue =
|
|
currentValue.substring(0, startPos) +
|
|
imgMarkdown +
|
|
currentValue.substring(endPos);
|
|
|
|
setFormData(prev => ({ ...prev, content: newValue }));
|
|
}
|
|
|
|
setImageDialogOpen(false);
|
|
setImageUploadFile(null);
|
|
setImageUploadPreview('');
|
|
} catch (error) {
|
|
setError('Failed to upload image: ' + error.message);
|
|
} finally {
|
|
setIsSubmitting(false);
|
|
}
|
|
};
|
|
|
|
// Form submission for EDIT
|
|
const handleSubmit = async (e) => {
|
|
e.preventDefault();
|
|
setIsSubmitting(true);
|
|
setError(null);
|
|
setUploadProgress(0);
|
|
|
|
try {
|
|
// Upload new featured image if selected
|
|
let imageUrl = formData.imageUrl;
|
|
if (imageFile) {
|
|
imageUrl = await uploadToMinIO(imageFile, (progress) => {
|
|
setUploadProgress(progress);
|
|
});
|
|
}
|
|
|
|
// Prepare payload
|
|
const payload = {
|
|
...formData,
|
|
imageUrl
|
|
};
|
|
|
|
// Submit to API (PUT request for update)
|
|
const response = await fetch(`${TOPIC_API_URL}?query=update-topic&slug=${formData.slug}`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
},
|
|
credentials: 'include',
|
|
body: JSON.stringify(payload)
|
|
});
|
|
|
|
if (!response.ok) {
|
|
const errorData = await response.json();
|
|
throw new Error(errorData.message || 'Failed to update topic');
|
|
}
|
|
|
|
setSuccess(true);
|
|
setTimeout(() => {
|
|
navigate(`/topic/${formData.slug}`);
|
|
}, 1500);
|
|
} catch (err) {
|
|
setError(err.message);
|
|
} finally {
|
|
setIsSubmitting(false);
|
|
setUploadProgress(0);
|
|
}
|
|
};
|
|
|
|
// Handle form field changes (same as NewTopic)
|
|
const handleChange = (e) => {
|
|
const { name, value } = e.target;
|
|
setFormData(prev => ({ ...prev, [name]: value }));
|
|
};
|
|
|
|
// Handle featured image file selection (same as NewTopic)
|
|
const handleFileChange = (e) => {
|
|
const file = e.target.files[0];
|
|
if (file) {
|
|
setImageFile(file);
|
|
const reader = new FileReader();
|
|
reader.onload = () => {
|
|
setFormData(prev => ({ ...prev, imageUrl: reader.result }));
|
|
};
|
|
reader.readAsDataURL(file);
|
|
}
|
|
};
|
|
|
|
// Loading state
|
|
if (isLoading) {
|
|
return (
|
|
<div className="container mx-auto px-4 py-8 text-center">
|
|
<div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-[#6d9e37] mx-auto"></div>
|
|
<p className="mt-4 text-gray-600">Topic Loading...</p>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
// Success state
|
|
if (success) {
|
|
return (
|
|
<div className="container mx-auto px-4 text-center py-8">
|
|
<h3 className="text-xl font-semibold text-green-600 mb-4">Topic has been successfully updated!</h3>
|
|
<p className="mb-4">You are being automatically redirected to the topic page...</p>
|
|
<div className="flex justify-center gap-4">
|
|
<Button onClick={() => navigate(`/topic/${formData.slug}`)}>Preview this Topic</Button>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
return (
|
|
<div className="container mx-auto px-4 py-8">
|
|
<div className="max-w-3xl mx-auto bg-neutral-800 rounded-lg shadow-md p-6">
|
|
<h2 className="text-2xl font-bold text-[#6d9e37] mb-2">Edit Topic</h2>
|
|
<p className="text-gray-600 mb-6">{formData.title}</p>
|
|
|
|
<form onSubmit={handleSubmit} className="space-y-6">
|
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
|
<div className="space-y-2">
|
|
<Label htmlFor="status">Status</Label>
|
|
<Select
|
|
name="status"
|
|
required
|
|
value={formData.status}
|
|
onValueChange={(value) => setFormData(prev => ({ ...prev, status: value }))}
|
|
>
|
|
<SelectTrigger id="status" className="text-sm sm:text-base w-full">
|
|
<SelectValue placeholder="Select Status" />
|
|
</SelectTrigger>
|
|
<SelectContent>
|
|
<SelectItem value="draft">Draft</SelectItem>
|
|
<SelectItem value="published">Publish</SelectItem>
|
|
<SelectItem value="archived">Archive</SelectItem>
|
|
</SelectContent>
|
|
</Select>
|
|
</div>
|
|
|
|
<div className="space-y-2">
|
|
<Label htmlFor="category">Category *</Label>
|
|
<Select
|
|
name="category"
|
|
required
|
|
value={formData.category}
|
|
onValueChange={(value) => setFormData(prev => ({ ...prev, category: value }))}
|
|
>
|
|
<SelectTrigger id="category" className="text-sm sm:text-base w-full">
|
|
<SelectValue placeholder="Select Category" />
|
|
</SelectTrigger>
|
|
<SelectContent position="popper" className="z-50">
|
|
<SelectItem value="php">PHP Hosting</SelectItem>
|
|
<SelectItem value="nodejs">Node.js Hosting</SelectItem>
|
|
</SelectContent>
|
|
</Select>
|
|
</div>
|
|
</div>
|
|
|
|
{/* Title and Slug */}
|
|
<div className="space-y-2">
|
|
<Label htmlFor="title">Title *</Label>
|
|
<Input
|
|
type="text"
|
|
name="title"
|
|
value={formData.title}
|
|
onChange={handleChange}
|
|
placeholder="Wriet Topic Title"
|
|
required
|
|
/>
|
|
</div>
|
|
|
|
<div className="space-y-2">
|
|
<Label htmlFor="slug">URL Slug</Label>
|
|
<input
|
|
type="hidden"
|
|
name="slug"
|
|
value={formData.slug}
|
|
onChange={handleChange}
|
|
className="bg-gray-50"
|
|
/>
|
|
<p className="text-xs text-gray-500">This will be used in the topic URL</p>
|
|
</div>
|
|
|
|
{/* Content Editor */}
|
|
<div className="space-y-2">
|
|
<div className="flex justify-between items-center">
|
|
<Label htmlFor="content">Content *</Label>
|
|
<button
|
|
type="button"
|
|
onClick={() => setEditorMode(editorMode === 'edit' ? 'preview' : 'edit')}
|
|
className={`ml-2 ${editorMode !== 'edit' ? 'bg-[#6d9e37]' : ''} text-white border border-[#6d9e37] text-[#6d9e37] px-2 py-1 rounded-md`}
|
|
>
|
|
{editorMode === 'edit' ? 'Preview' : 'Edit'}
|
|
</button>
|
|
</div>
|
|
<div data-color-mode="light">
|
|
<MDEditor
|
|
value={formData.content}
|
|
onChange={(value) => setFormData(prev => ({ ...prev, content: value || '' }))}
|
|
height={400}
|
|
preview={editorMode}
|
|
commands={allCommands}
|
|
/>
|
|
</div>
|
|
</div>
|
|
|
|
{/* Image Upload Dialog (same as NewTopic) */}
|
|
<Dialog open={imageDialogOpen} onOpenChange={setImageDialogOpen}>
|
|
<DialogContent className="sm:max-w-[425px]">
|
|
<DialogHeader>
|
|
<DialogTitle>Add Image</DialogTitle>
|
|
</DialogHeader>
|
|
<CustomTabs
|
|
tabs={[
|
|
{
|
|
label: "URL",
|
|
value: "url",
|
|
content: (
|
|
<div className="space-y-4">
|
|
<Input
|
|
type="text"
|
|
placeholder="Image URL"
|
|
value={imageUrlInput}
|
|
onChange={(e) => setImageUrlInput(e.target.value)}
|
|
/>
|
|
<div className="flex justify-end">
|
|
<Button
|
|
type="button"
|
|
onClick={handleInsertImageUrl}
|
|
disabled={!imageUrlInput}
|
|
>
|
|
Upload Image
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
)
|
|
},
|
|
{
|
|
label: "Upload",
|
|
value: "upload",
|
|
content: (
|
|
<div className="space-y-4">
|
|
<Input
|
|
type="file"
|
|
accept="image/*"
|
|
onChange={handleImageFileSelect}
|
|
/>
|
|
{imageUploadPreview && (
|
|
<div className="mt-2">
|
|
<img
|
|
src={imageUploadPreview}
|
|
alt="Preview"
|
|
className="max-h-40 rounded-md border"
|
|
/>
|
|
</div>
|
|
)}
|
|
{uploadProgress > 0 && uploadProgress < 100 && (
|
|
<div className="w-full bg-gray-200 rounded-full h-2.5">
|
|
<div
|
|
className="bg-blue-600 h-2.5 rounded-full"
|
|
style={{ width: `${uploadProgress}%` }}
|
|
></div>
|
|
</div>
|
|
)}
|
|
<div className="flex justify-end">
|
|
<Button
|
|
type="button"
|
|
onClick={handleImageUpload}
|
|
disabled={!imageUploadFile || isSubmitting}
|
|
>
|
|
{isSubmitting ? 'Uploading...' : 'Upload'}
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
)
|
|
}
|
|
]}
|
|
/>
|
|
</DialogContent>
|
|
</Dialog>
|
|
|
|
{/* Featured Image Upload */}
|
|
<div className="space-y-2">
|
|
<Label htmlFor="image">Featured Image</Label>
|
|
<Input
|
|
type="file"
|
|
id="image"
|
|
onChange={handleFileChange}
|
|
accept="image/*"
|
|
className="cursor-pointer"
|
|
/>
|
|
|
|
{uploadProgress > 0 && uploadProgress < 100 && (
|
|
<div className="w-full bg-gray-200 rounded-full h-2.5">
|
|
<div
|
|
className="bg-blue-600 h-2.5 rounded-full"
|
|
style={{ width: `${uploadProgress}%` }}
|
|
></div>
|
|
</div>
|
|
)}
|
|
|
|
{formData.imageUrl && (
|
|
<div className="mt-2">
|
|
<img
|
|
src={formData.imageUrl}
|
|
alt="Preview"
|
|
className="max-h-40 rounded-md border"
|
|
/>
|
|
<p className="text-xs text-gray-500 mt-1">Current Image</p>
|
|
</div>
|
|
)}
|
|
</div>
|
|
|
|
<Separator />
|
|
|
|
{/* Form Actions */}
|
|
<div className="flex justify-end gap-4">
|
|
<Button
|
|
type="button"
|
|
variant="outline"
|
|
onClick={() => navigate(-1)}
|
|
disabled={isSubmitting}
|
|
>
|
|
Cancel
|
|
</Button>
|
|
<Button
|
|
type="submit"
|
|
disabled={isSubmitting}
|
|
className="min-w-32 bg-[#6d9e37] hover:bg-[#5a8a2a]"
|
|
>
|
|
{isSubmitting ? (
|
|
<span className="flex items-center gap-2">
|
|
<span className="animate-spin">↻</span>
|
|
Uploading...
|
|
</span>
|
|
) : 'Update'}
|
|
</Button>
|
|
</div>
|
|
|
|
{error && (
|
|
<div className="p-4 bg-red-50 text-red-600 rounded-md">
|
|
Error: {error}
|
|
</div>
|
|
)}
|
|
</form>
|
|
</div>
|
|
</div>
|
|
);
|
|
}; |