"use client"; import React, { useState, useEffect, useMemo, useRef } from "react"; import { Input, Button, AccordionItem, Accordion, Select, SelectItem, Switch, Card, Spinner, } from "@nextui-org/react"; import { PlatformConfig, Theme } from "@/shared/types/system"; import { useTranslation } from "@/shared/lib/useTranslation"; import { SUPPORTED_LANGUAGES } from "@/shared/lib/i18n"; import { ThemeSelector } from "./ThemeSelector"; import "@uiw/react-md-editor/markdown-editor.css"; import "@uiw/react-markdown-preview/markdown.css"; import toast from "react-hot-toast"; import { UploadIcon } from "lucide-react"; import { calculateFileSha256 } from "@/shared/utils/crypto"; import { withComponentInjection } from "@/shared/hooks/useComponentInjection"; interface PlatformConfigFormProps { config: PlatformConfig; onSave: (config: PlatformConfig) => void; onThemeChange?: (theme: Theme) => Promise; isLoading?: boolean; uploadImage: (file: File, sha256?: string) => Promise; } const PlatformConfigFormBase: React.FC = ({ config, onSave, onThemeChange, isLoading = false, uploadImage, }) => { const { t } = useTranslation(); const [formData, setFormData] = useState(config); const [validationErrors, setValidationErrors] = useState<{ domain?: string; mcp_server_prefix?: string; }>({}); const [isUploading, setIsUploading] = useState(false); const fileInputRef = useRef(null); const isValidate = useMemo(() => { return formData.name.trim().length > 0 && !isUploading; }, [formData, isUploading]); // when context config updated, sync to form useEffect(() => { setFormData(config); }, [config]); // URL validation function with strict regex const validateUrl = (url: string): boolean => { if (!url.trim()) return true; // Empty is valid (optional field) // Strict regex for domain validation const domainRegex = /^https?:\/\/(?:[-\w.])+(?:\:[0-9]+)?(?:\/.*)?$/; // First check with regex if (!domainRegex.test(url)) { return false; } // Then validate with URL constructor for additional checks try { const urlObj = new URL(url); return ( (urlObj.protocol === "http:" || urlObj.protocol === "https:") && urlObj.hostname.length > 0 && urlObj.hostname.includes(".") ); } catch { return false; } }; // Validate field and update errors const validateField = ( field: "domain" | "mcp_server_prefix", value: string ) => { const isValid = validateUrl(value); setValidationErrors((prev) => ({ ...prev, [field]: isValid ? undefined : t("Please enter a valid URL with http:// or https://"), })); return isValid; }; const handleInputChange = ( field: keyof PlatformConfig, value: string | boolean ) => { // Validate URL fields if (field === "domain" || field === "mcp_server_prefix") { validateField(field, value as string); } setFormData((prev) => { const newData = { ...prev, [field]: value, }; return newData; }); }; const handleSave = async () => { // Validate all URL fields before saving const domainValid = validateField("domain", formData.domain || ""); const mcpServerValid = validateField( "mcp_server_prefix", formData.mcp_server_prefix || "" ); if (!domainValid || !mcpServerValid) { toast.error(t("Please fix validation errors before saving")); return; } onSave(formData); }; const handleThemeChange = async (theme: Theme) => { handleInputChange("theme", theme); onThemeChange?.(theme); }; const handleImageUpload = async ( event: React.ChangeEvent ) => { const file = event.target.files?.[0]; if (!file) return; // Validate file type if (!file.type.startsWith("image/")) { toast.error(t("Please select a valid image file")); return; } // Validate file size (max 5MB) if (file.size > 5 * 1024 * 1024) { toast.error(t("Image size should be less than 5MB")); return; } setIsUploading(true); try { const sha256 = await calculateFileSha256(file); const imageUrl = await uploadImage(file, sha256); handleInputChange("logo", imageUrl); } catch (error) { console.error("Upload failed:", error); toast.error(t("Failed to upload image")); } finally { setIsUploading(false); } }; const handleImageClick = () => { if (!isUploading) { fileInputRef.current?.click(); } }; return (
{/* Platform Information Accordion */}

{t("Platform Information")}

{t("Configure platform logo, name, titles, language")}

} >
{/* platform name */} handleInputChange("name", e.target.value)} isRequired labelPlacement="outside" /> {/* platform logo */}

{t("Support JPG, PNG, GIF. Max size 5MB")}

{isUploading ? ( ) : ( )}
{/* website title */} handleInputChange("website_title", e.target.value) } labelPlacement="outside" /> {/* homepage headline */} handleInputChange("headline", e.target.value)} labelPlacement="outside" /> {/* homepage subheadline */} handleInputChange("subheadline", e.target.value)} labelPlacement="outside" /> {/* platform language */} {/* platform domain */} handleInputChange("domain", e.target.value)} isInvalid={!!validationErrors.domain} errorMessage={validationErrors.domain} labelPlacement="outside" /> {/* mcp server prefix */} handleInputChange("mcp_server_prefix", e.target.value) } isInvalid={!!validationErrors.mcp_server_prefix} errorMessage={validationErrors.mcp_server_prefix} labelPlacement="outside" /> {/* showcase in xpack */}
{t("Featured in the XPack showcase")} {t( "Enable this option to feature your site in the XPack global showcase and reach users worldwide." )}
{ handleInputChange("is_showcased", value); }} color="primary" size="sm" />
{/* Action Buttons */}
{/* Theme Accordion */}

{t("Theme")}

{t("Choose your preferred theme style")}

} >
); }; // Export the base component for direct use (avoiding circular dependency) export { PlatformConfigFormBase }; // Export with component injection support export const PlatformConfigForm = withComponentInjection( "forms/PlatformConfigForm", PlatformConfigFormBase );