import React, { useState, useRef, useEffect } from "react"; import { createPortal } from "react-dom"; import { ToggleRight, Check } from "lucide-react"; import { HexColorPicker } from "react-colorful"; export default function InlineSwitchEditor({ field, children, viewMode, onUpdate, setIsDirty, }) { const [isEditing, setIsEditing] = useState(false); const [toolbarPosition, setToolbarPosition] = useState({ top: 0, left: 0 }); const [showOnColorPicker, setShowOnColorPicker] = useState(false); const [showOffColorPicker, setShowOffColorPicker] = useState(false); const containerRef = useRef(null); const toolbarRef = useRef(null); const onColorPickerRef = useRef(null); const offColorPickerRef = useRef(null); useEffect(() => { if (isEditing && containerRef.current) { const updatePosition = () => { if (!containerRef.current) return; const rect = containerRef.current.getBoundingClientRect(); const toolbarWidth = 260; let left = rect.left + (rect.width / 2) - (toolbarWidth / 2); let top = rect.bottom + 8; if (left < 10) left = 10; if (left + toolbarWidth > window.innerWidth - 10) left = window.innerWidth - toolbarWidth - 10; if (top + 50 > window.innerHeight) top = rect.top - 50; setToolbarPosition({ top, left }); }; updatePosition(); window.addEventListener("scroll", updatePosition, true); window.addEventListener("resize", updatePosition); return () => { window.removeEventListener("scroll", updatePosition, true); window.removeEventListener("resize", updatePosition); }; } }, [isEditing]); useEffect(() => { const handleClickOutside = (e) => { if (!isEditing) return; if ( containerRef.current && !containerRef.current.contains(e.target) && toolbarRef.current && !toolbarRef.current.contains(e.target) && (!onColorPickerRef.current || !onColorPickerRef.current.contains(e.target)) && (!offColorPickerRef.current || !offColorPickerRef.current.contains(e.target)) ) { setIsEditing(false); setShowOnColorPicker(false); setShowOffColorPicker(false); } }; document.addEventListener("mousedown", handleClickOutside); return () => document.removeEventListener("mousedown", handleClickOutside); }, [isEditing]); const updateFieldData = (updates) => { if (setIsDirty) setIsDirty(true); onUpdate(updates); }; const switchOnColor = field.switchOnColor || "#10B981"; const switchOffColor = field.switchOffColor || "#E5E7EB"; const isDefaultOn = field.defaultValue === true || field.defaultValue === "on"; return ( <>
{ if (viewMode === 'preview') return; e.stopPropagation(); setIsEditing(true); }} className={`inline-switch-editor-trigger ${viewMode === 'edit' ? "cursor-pointer group/switch relative" : ""}`} > {children}
{isEditing && createPortal(
e.stopPropagation()} > {/* On Color */}
{showOnColorPicker && (
Switch Active Color
updateFieldData({ switchOnColor: c })} />
)}
{/* Off Color */}
{showOffColorPicker && (
Switch Inactive Color
updateFieldData({ switchOffColor: c })} />
)}
{/* Default Value Toggle */}
, document.body )} ); }