diff --git a/# CodeByDante.txt b/# CodeByDante.txt new file mode 100644 index 0000000000000000000000000000000000000000..575b7053bc779f1dca483e350d5690d44ac817a9 --- /dev/null +++ b/# CodeByDante.txt @@ -0,0 +1,91 @@ +# CodeByDante + + + + + + + + + + + + + CodeByDante + + + + + + + + + + + +
+ + + + \ No newline at end of file diff --git a/.env.example b/.env.example new file mode 100644 index 0000000000000000000000000000000000000000..9ae0aaae438c242ab38912ef5309ccc299e44a75 --- /dev/null +++ b/.env.example @@ -0,0 +1 @@ +VITE_GEMINI_API_KEY=INSERT_YOUR_API_KEY_HERE diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..7ceb59f89a14551ad717dd1c9b2492359ba58ef2 --- /dev/null +++ b/.gitignore @@ -0,0 +1,25 @@ +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +pnpm-debug.log* +lerna-debug.log* + +node_modules +dist +dist-ssr +*.local + +# Editor directories and files +.vscode/* +!.vscode/extensions.json +.idea +.DS_Store +*.suo +*.ntvs* +*.njsproj +*.sln +*.sw? +.env diff --git a/App.tsx b/App.tsx new file mode 100644 index 0000000000000000000000000000000000000000..7797b60759aff1134890006ceea94e7f5a55a85e --- /dev/null +++ b/App.tsx @@ -0,0 +1,458 @@ +import React, { useState, useEffect, useMemo } from 'react'; +import { DataItem, ViewState } from './types'; +import { AdminLoginModal } from './components/AdminLoginModal'; +import { Card } from './components/Card'; +import { DataForm } from './components/DataForm'; +import { DetailView } from './components/DetailView'; +import { Button } from './components/Button'; +import { Plus, Search, Layers, Loader2, WifiOff, Settings, Code, Type, Clock, Calendar, Shuffle } from 'lucide-react'; +import { subscribeToItems, addItem, updateItem, deleteItem } from './services/firebase'; +import { subscribeToStyleConfig } from './services/codeStyleService'; + +const App: React.FC = () => { + const [items, setItems] = useState([]); + const [view, setView] = useState('LIST'); + const [viewMode, setViewMode] = useState<'normal' | 'admin'>(() => { + if (typeof window !== 'undefined') { + return (localStorage.getItem('viewMode') as 'normal' | 'admin') || 'normal'; + } + return 'normal'; + }); + const [showAdminLogin, setShowAdminLogin] = useState(false); + const [isSettingsOpen, setIsSettingsOpen] = useState(false); + const [selectedItem, setSelectedItem] = useState(null); + const [searchQuery, setSearchQuery] = useState(''); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(null); + const [sortOrder, setSortOrder] = useState<'updated' | 'created' | 'name' | 'random'>(() => { + if (typeof window !== 'undefined') { + const saved = localStorage.getItem('sortOrder'); + if (saved && ['updated', 'created', 'name', 'random'].includes(saved)) { + return saved as 'updated' | 'created' | 'name' | 'random'; + } + } + return 'random'; + }); + + useEffect(() => { + localStorage.setItem('sortOrder', sortOrder); + }, [sortOrder]); + + // Helper function to apply code style dynamically to DOM + const applyCodeStyleToDOM = (config: any) => { + const rgbaMatch = config.bgColor.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*[\d.]+)?\)/); + let bgColorWithOpacity = config.bgColor; + + if (rgbaMatch) { + const [_, r, g, b] = rgbaMatch; + bgColorWithOpacity = `rgba(${r}, ${g}, ${b}, ${config.opacity / 100})`; + } + + const widthValue = config.width === 'auto' ? 0 : parseFloat(config.width) || 0; + const heightValue = config.height === 'auto' ? 0 : parseFloat(config.height) || 0; + + const existingStyle = document.getElementById('dynamic-code-style'); + if (existingStyle) { + existingStyle.remove(); + } + + const style = document.createElement('style'); + style.id = 'dynamic-code-style'; + style.innerHTML = ` + :not(pre) > code { + background-color: ${bgColorWithOpacity} !important; + color: ${config.textColor} !important; + font-size: ${config.fontSize} !important; + border-radius: ${config.borderRadius} !important; + padding: 0px 2px !important; + ${config.width !== 'auto' && widthValue > 0 ? `min-width: ${config.width} !important;` : ''} + ${config.height !== 'auto' && heightValue > 0 ? `min-height: ${config.height} !important;` : ''} + + display: inline-flex !important; + align-items: center !important; + justify-content: center !important; + + vertical-align: middle !important; + border: none !important; + font-family: 'Consolas', monospace !important; + line-height: 1 !important; + margin: 0 1px !important; + } + + button code, a code, .btn code { + background: transparent !important; + padding: 0 !important; + color: inherit !important; + border: none !important; + } + + code::before, code::after { + content: "" !important; + display: none !important; + } + `; + + document.head.appendChild(style); + }; + + // Subscribe to style config changes from cloud + useEffect(() => { + const unsubscribe = subscribeToStyleConfig((config) => { + applyCodeStyleToDOM(config.code); + }); + return () => unsubscribe(); + }, [applyCodeStyleToDOM]); + + // Persist viewMode to localStorage + useEffect(() => { + localStorage.setItem('viewMode', viewMode); + }, [viewMode]); + + // Subscribe to Firestore updates + useEffect(() => { + const unsubscribe = subscribeToItems((newItems) => { + setItems(newItems); + setLoading(false); + setError(null); + }); + + // Cleanup subscription on unmount + return () => unsubscribe(); + }, []); + + const filteredItems = useMemo(() => { + if (!searchQuery.trim()) { + const allItems = [...items]; + // Default sorting when no search + if (sortOrder === 'random') return allItems.sort(() => Math.random() - 0.5); + if (sortOrder === 'name') return allItems.sort((a, b) => a.title.localeCompare(b.title)); + if (sortOrder === 'updated') return allItems.sort((a, b) => (b.updatedAt || b.createdAt) - (a.updatedAt || a.createdAt)); + return allItems.sort((a, b) => b.createdAt - a.createdAt); + } + + const lowerQ = searchQuery.toLowerCase(); + + // SMART SEARCH LOGIC + const stopWords = new Set([ + 'el', 'la', 'los', 'las', 'un', 'una', 'unos', 'unas', 'y', 'o', 'pero', 'si', 'no', + 'de', 'del', 'a', 'al', 'en', 'con', 'por', 'para', 'sin', 'sobre', 'entre', + 'mi', 'tu', 'su', 'nuestro', 'vuestro', 'sus', 'mis', 'tus', + 'que', 'cual', 'quien', 'donde', 'cuando', 'como', 'porque', + 'es', 'son', 'fue', 'fueron', 'era', 'eran', 'está', 'están', + 'este', 'esta', 'ese', 'esa', 'aquel', 'aquella', 'esto', 'eso', 'aquello', + 'hizo', 'hacer', 'todo', 'toda', 'todos', 'todas', 'muy', 'más', 'tan', + 'ya', 'hoy', 'ayer', 'ahora', 'después', 'antes', 'mira', 'voy' + ]); + + // Tokenize and clean query + const tokens = lowerQ.replace(/[^\w\sáéíóúñü]/g, '').split(/\s+/).filter(t => t.length > 0); + const keywords = tokens.filter(t => !stopWords.has(t)); + + // Fallback: If all words were stop words (e.g. "el la"), search normally with full query + const validKeywords = keywords.length > 0 ? keywords : tokens; + + // Scoring function + const getScore = (item: DataItem) => { + let score = 0; + const title = item.title.toLowerCase(); + const summary = item.summary.toLowerCase(); + const tags = item.tags.map(t => t.toLowerCase()); + + validKeywords.forEach(keyword => { + if (title.includes(keyword)) score += 10; + else if (tags.some(t => t.includes(keyword))) score += 5; + else if (summary.includes(keyword)) score += 2; + }); + + return score; + }; + + // Filter and Map to [Item, Score] + const scoredItems = items + .map(item => ({ item, score: getScore(item) })) + .filter(entry => entry.score > 0); + + // Sort by Score DESC, then by sortOrder + scoredItems.sort((a, b) => { + if (a.score !== b.score) return b.score - a.score; // Higher score first + + // Secondary sort based on user preference + if (sortOrder === 'name') return a.item.title.localeCompare(b.item.title); + if (sortOrder === 'updated') return (b.item.updatedAt || b.item.createdAt) - (a.item.updatedAt || a.item.createdAt); + if (sortOrder === 'created') return b.item.createdAt - a.item.createdAt; + return 0; + }); + + return scoredItems.map(entry => entry.item); + + }, [items, searchQuery, sortOrder]); + + const handleCreate = async (data: Omit) => { + try { + await addItem(data); + setView('LIST'); + } catch (e) { + alert("Error al guardar en la nube."); + } + }; + + const handleUpdate = async (data: Omit) => { + if (!selectedItem) return; + try { + await updateItem(selectedItem.id, data); + + // Update local selected item to reflect changes immediately in UI if still in Detail view + setSelectedItem(prev => prev ? { ...prev, ...data } : null); + // We do NOT switch view here automatically to allow inline edits in DetailView + } catch (e) { + alert("Error al actualizar."); + } + }; + + const handleDelete = async (id: string) => { + try { + await deleteItem(id); + setView('LIST'); + setSelectedItem(null); + } catch (e) { + alert("Error al eliminar."); + } + }; + + if (error) { + return ( +
+ +

Error de Conexión

+

{error}

+

Por favor verifica tu conexión a internet o la configuración de Firebase.

+
+ ); + } + + return ( +
+ + {/* Navbar */} + + + {/* Mobile Search Bar */} + {view === 'LIST' && ( +
+
+ + setSearchQuery(e.target.value)} + /> +
+
+ )} + + {/* Main Content */} +
+ + {loading ? ( +
+ +

Sincronizando con CodeByDante Cloud...

+
+ ) : ( + <> + {view === 'LIST' && ( + <> + {filteredItems.length === 0 ? ( +
+
+ +
+

No se encontraron elementos

+

El repositorio está vacío o no hay coincidencias.

+
+ ) : ( +
+ {filteredItems.map(item => ( + { setSelectedItem(i); setView('DETAIL'); }} + onTagClick={(tag) => { + setSearchQuery(tag); + setView('LIST'); + }} + /> + ))} +
+ )} + + )} + + {view === 'CREATE' && ( + setView('LIST')} + /> + )} + + {view === 'EDIT' && selectedItem && ( + { + handleUpdate(data); + setView('DETAIL'); // Explicitly go back to detail after full edit + }} + onCancel={() => setView('DETAIL')} + /> + )} + + {view === 'DETAIL' && selectedItem && ( + setView('LIST')} + onUpdate={handleUpdate} + onDelete={handleDelete} + isEditable={viewMode === 'admin'} + onTagClick={(tag) => { + setSearchQuery(tag); + setView('LIST'); + }} + /> + )} + + )} + +
+ setShowAdminLogin(false)} + onSuccess={() => { + setViewMode('admin'); + setShowAdminLogin(false); + }} + /> +
+ ); +}; + +export default App; \ No newline at end of file diff --git a/README.md b/README.md index 1ffcc9e6ef91a6254ca5db8e326f720ae06eef02..b62d17a678885ffd3b41d3a57afae9188fdcece9 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,3 @@ ---- -title: Codebydante -emoji: 🚀 -colorFrom: yellow -colorTo: pink -sdk: docker -pinned: false ---- +# CodeByDante -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference +pacto del colbador diff --git a/components/AIInstructionModal.tsx b/components/AIInstructionModal.tsx new file mode 100644 index 0000000000000000000000000000000000000000..6c8e8448ce47a3588d184819a92df4b641a8fb14 --- /dev/null +++ b/components/AIInstructionModal.tsx @@ -0,0 +1,135 @@ +import React, { useState, useEffect, useRef } from 'react'; +import { X, Sparkles, Wand2, Loader2 } from 'lucide-react'; +import { motion, AnimatePresence } from 'framer-motion'; + +interface AIInstructionModalProps { + isOpen: boolean; + onClose: () => void; + onGenerate: (instructions: string) => Promise; + currentContent?: string; +} + +export const AIInstructionModal: React.FC = ({ + isOpen, + onClose, + onGenerate, + currentContent +}) => { + const [instructions, setInstructions] = useState(''); + const [isGenerating, setIsGenerating] = useState(false); + const textareaRef = useRef(null); + + useEffect(() => { + if (isOpen) { + setInstructions(''); + setIsGenerating(false); + // Focus after animation + setTimeout(() => textareaRef.current?.focus(), 100); + } + }, [isOpen]); + + const handleSubmit = async (e?: React.FormEvent) => { + e?.preventDefault(); + if (!instructions.trim() || isGenerating) return; + + setIsGenerating(true); + try { + await onGenerate(instructions); + onClose(); + } catch (error) { + console.error("Analysis failed", error); + } finally { + setIsGenerating(false); + } + }; + + const isContentEmpty = !currentContent || currentContent.trim().length === 0; + const title = isContentEmpty ? "¿Qué deseas crear?" : "¿Cómo deseas mejorarlo?"; + const placeholder = isContentEmpty + ? "Ej: Escribe un resumen sobre React Hooks..." + : "Ej: Hazlo más conciso, añade emojis, tradúcelo al inglés..."; + + return ( + + {isOpen && ( + <> + {/* Backdrop */} + + + {/* Modal */} + +
+ + {/* Header */} +
+ + +
+ +
+

{title}

+

Dante AI Assistant

+
+ + {/* Body */} +
+
+