codebybrody commited on
Commit
5683f0b
·
verified ·
1 Parent(s): a1ac1c2

Upload 51 files

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. # CodeByDante.txt +91 -0
  2. .env.example +1 -0
  3. .gitignore +25 -0
  4. App.tsx +458 -0
  5. README.md +2 -9
  6. components/AIInstructionModal.tsx +135 -0
  7. components/AdminLoginModal.tsx +158 -0
  8. components/BlockEditorModal.tsx +125 -0
  9. components/Button.tsx +37 -0
  10. components/Card.tsx +78 -0
  11. components/CodeBlockComponent.tsx +249 -0
  12. components/ConfirmDialog.tsx +65 -0
  13. components/CopyButton.tsx +22 -0
  14. components/CustomBlockquote.tsx +76 -0
  15. components/CustomButtonComponent.tsx +102 -0
  16. components/DataForm.tsx +200 -0
  17. components/DetailView.tsx +703 -0
  18. components/DownloadButton.tsx +30 -0
  19. components/EditorContextMenu.tsx +235 -0
  20. components/EditorSelectionWrapper.tsx +183 -0
  21. components/EditorToolbar.tsx +792 -0
  22. components/IconPicker.tsx +203 -0
  23. components/MarkdownRenderer.tsx +235 -0
  24. components/QuoteBlock.tsx +91 -0
  25. components/QuoteComponent.tsx +159 -0
  26. components/StyleSettingsPanel.tsx +817 -0
  27. components/TextFormatToolbar.tsx +507 -0
  28. components/TiktokIcon.tsx +28 -0
  29. components/TipTapEditor.tsx +494 -0
  30. components/extensions/CustomBlockquote.ts +161 -0
  31. components/extensions/CustomButton.ts +198 -0
  32. components/extensions/CustomCodeBlock.ts +48 -0
  33. components/extensions/CustomImageExtension.ts +41 -0
  34. components/extensions/ResizableImageComponent.tsx +273 -0
  35. components/extensions/ResizableVideoComponent.tsx +237 -0
  36. components/extensions/UniversalVideoExtension.ts +72 -0
  37. index.css +76 -0
  38. index.html +81 -0
  39. index.tsx +15 -0
  40. metadata.json +5 -0
  41. package-lock.json +0 -0
  42. package.json +40 -0
  43. services/aiService.ts +143 -0
  44. services/codeStyleService.ts +351 -0
  45. services/firebase.ts +117 -0
  46. services/geminiService.ts +44 -0
  47. services/imageService.ts +25 -0
  48. tsconfig.json +29 -0
  49. types.ts +27 -0
  50. utils/codeStyleLoader.ts +68 -0
# CodeByDante.txt ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # CodeByDante
2
+
3
+ <!DOCTYPE html>
4
+ <html lang="es">
5
+
6
+ <head>
7
+ <script type="importmap">
8
+ {
9
+ "imports": {
10
+ "react": "https://aistudiocdn.com/react@^19.2.0",
11
+ "react-dom/": "https://aistudiocdn.com/react-dom@^19.2.0/",
12
+ "react/": "https://aistudiocdn.com/react@^19.2.0/",
13
+ "@google/genai": "https://aistudiocdn.com/@google/genai@^1.30.0",
14
+ "lucide-react": "https://aistudiocdn.com/lucide-react@^0.554.0",
15
+ "firebase/app": "https://www.gstatic.com/firebasejs/10.8.0/firebase-app.js",
16
+ "firebase/firestore": "https://www.gstatic.com/firebasejs/10.8.0/firebase-firestore.js",
17
+ "firebase/": "https://aistudiocdn.com/firebase@^12.6.0/",
18
+ "react-markdown": "https://aistudiocdn.com/react-markdown@^10.1.0",
19
+ "@vitejs/plugin-react": "https://aistudiocdn.com/@vitejs/plugin-react@^5.1.1",
20
+ "vite": "https://aistudiocdn.com/vite@^7.2.4",
21
+ "remark-gfm": "https://aistudiocdn.com/remark-gfm@^4.0.1",
22
+ "path": "https://aistudiocdn.com/path@^0.12.7",
23
+ "rehype-raw": "https://aistudiocdn.com/rehype-raw@^7.0.0",
24
+ "rehype-sanitize": "https://aistudiocdn.com/rehype-sanitize@^6.0.0"
25
+ }
26
+ }
27
+ </script>
28
+ <script type="module">import { injectIntoGlobalHook } from "/@react-refresh";
29
+ injectIntoGlobalHook(window);
30
+ window.$RefreshReg$ = () => {};
31
+ window.$RefreshSig$ = () => (type) => type;</script>
32
+
33
+ <script type="module" src="/@vite/client"></script>
34
+
35
+ <meta charset="UTF-8" />
36
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
37
+ <title>CodeByDante</title>
38
+ <script src="https://cdn.tailwindcss.com"></script>
39
+ <script>
40
+ tailwind.config = {
41
+ theme: {
42
+ extend: {
43
+ colors: {
44
+ background: '#121212',
45
+ primary: '#bb86fc',
46
+ surface: '#1e1e1e',
47
+ surfaceHover: '#2d2d2d',
48
+ }
49
+ }
50
+ }
51
+ }
52
+ </script>
53
+ <style>
54
+ body {
55
+ background-color: #121212;
56
+ color: #e0e0e0;
57
+ }
58
+
59
+ /* Custom Scrollbar */
60
+ ::-webkit-scrollbar {
61
+ width: 8px;
62
+ }
63
+
64
+ ::-webkit-scrollbar-track {
65
+ background: #121212;
66
+ }
67
+
68
+ ::-webkit-scrollbar-thumb {
69
+ background: #333;
70
+ border-radius: 4px;
71
+ }
72
+
73
+ ::-webkit-scrollbar-thumb:hover {
74
+ background: #bb86fc;
75
+ }
76
+ </style>
77
+
78
+ <link rel="preconnect" href="https://fonts.googleapis.com">
79
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
80
+ <link
81
+ href="https://fonts.googleapis.com/css2?family=Dancing+Script:wght@400..700&family=Fira+Code:wght@300..700&family=Inter:wght@100..900&family=JetBrains+Mono:ital,wght@0,100..800;1,100..800&family=Merriweather:ital,wght@0,300;0,400;0,700;0,900;1,300;1,400;1,700;1,900&family=Pacifico&family=Playfair+Display:ital,wght@0,400..900;1,400..900&family=Roboto:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&family=Source+Code+Pro:ital,wght@0,200..900;1,200..900&display=swap"
82
+ rel="stylesheet">
83
+ <link rel="stylesheet" href="/index.css">
84
+ </head>
85
+
86
+ <body>
87
+ <div id="root"></div>
88
+ <script type="module" src="/index.tsx"></script>
89
+ </body>
90
+
91
+ </html>
.env.example ADDED
@@ -0,0 +1 @@
 
 
1
+ VITE_GEMINI_API_KEY=INSERT_YOUR_API_KEY_HERE
.gitignore ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Logs
2
+ logs
3
+ *.log
4
+ npm-debug.log*
5
+ yarn-debug.log*
6
+ yarn-error.log*
7
+ pnpm-debug.log*
8
+ lerna-debug.log*
9
+
10
+ node_modules
11
+ dist
12
+ dist-ssr
13
+ *.local
14
+
15
+ # Editor directories and files
16
+ .vscode/*
17
+ !.vscode/extensions.json
18
+ .idea
19
+ .DS_Store
20
+ *.suo
21
+ *.ntvs*
22
+ *.njsproj
23
+ *.sln
24
+ *.sw?
25
+ .env
App.tsx ADDED
@@ -0,0 +1,458 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useState, useEffect, useMemo } from 'react';
2
+ import { DataItem, ViewState } from './types';
3
+ import { AdminLoginModal } from './components/AdminLoginModal';
4
+ import { Card } from './components/Card';
5
+ import { DataForm } from './components/DataForm';
6
+ import { DetailView } from './components/DetailView';
7
+ import { Button } from './components/Button';
8
+ import { Plus, Search, Layers, Loader2, WifiOff, Settings, Code, Type, Clock, Calendar, Shuffle } from 'lucide-react';
9
+ import { subscribeToItems, addItem, updateItem, deleteItem } from './services/firebase';
10
+ import { subscribeToStyleConfig } from './services/codeStyleService';
11
+
12
+ const App: React.FC = () => {
13
+ const [items, setItems] = useState<DataItem[]>([]);
14
+ const [view, setView] = useState<ViewState>('LIST');
15
+ const [viewMode, setViewMode] = useState<'normal' | 'admin'>(() => {
16
+ if (typeof window !== 'undefined') {
17
+ return (localStorage.getItem('viewMode') as 'normal' | 'admin') || 'normal';
18
+ }
19
+ return 'normal';
20
+ });
21
+ const [showAdminLogin, setShowAdminLogin] = useState(false);
22
+ const [isSettingsOpen, setIsSettingsOpen] = useState(false);
23
+ const [selectedItem, setSelectedItem] = useState<DataItem | null>(null);
24
+ const [searchQuery, setSearchQuery] = useState('');
25
+ const [loading, setLoading] = useState(true);
26
+ const [error, setError] = useState<string | null>(null);
27
+ const [sortOrder, setSortOrder] = useState<'updated' | 'created' | 'name' | 'random'>(() => {
28
+ if (typeof window !== 'undefined') {
29
+ const saved = localStorage.getItem('sortOrder');
30
+ if (saved && ['updated', 'created', 'name', 'random'].includes(saved)) {
31
+ return saved as 'updated' | 'created' | 'name' | 'random';
32
+ }
33
+ }
34
+ return 'random';
35
+ });
36
+
37
+ useEffect(() => {
38
+ localStorage.setItem('sortOrder', sortOrder);
39
+ }, [sortOrder]);
40
+
41
+ // Helper function to apply code style dynamically to DOM
42
+ const applyCodeStyleToDOM = (config: any) => {
43
+ const rgbaMatch = config.bgColor.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*[\d.]+)?\)/);
44
+ let bgColorWithOpacity = config.bgColor;
45
+
46
+ if (rgbaMatch) {
47
+ const [_, r, g, b] = rgbaMatch;
48
+ bgColorWithOpacity = `rgba(${r}, ${g}, ${b}, ${config.opacity / 100})`;
49
+ }
50
+
51
+ const widthValue = config.width === 'auto' ? 0 : parseFloat(config.width) || 0;
52
+ const heightValue = config.height === 'auto' ? 0 : parseFloat(config.height) || 0;
53
+
54
+ const existingStyle = document.getElementById('dynamic-code-style');
55
+ if (existingStyle) {
56
+ existingStyle.remove();
57
+ }
58
+
59
+ const style = document.createElement('style');
60
+ style.id = 'dynamic-code-style';
61
+ style.innerHTML = `
62
+ :not(pre) > code {
63
+ background-color: ${bgColorWithOpacity} !important;
64
+ color: ${config.textColor} !important;
65
+ font-size: ${config.fontSize} !important;
66
+ border-radius: ${config.borderRadius} !important;
67
+ padding: 0px 2px !important;
68
+ ${config.width !== 'auto' && widthValue > 0 ? `min-width: ${config.width} !important;` : ''}
69
+ ${config.height !== 'auto' && heightValue > 0 ? `min-height: ${config.height} !important;` : ''}
70
+
71
+ display: inline-flex !important;
72
+ align-items: center !important;
73
+ justify-content: center !important;
74
+
75
+ vertical-align: middle !important;
76
+ border: none !important;
77
+ font-family: 'Consolas', monospace !important;
78
+ line-height: 1 !important;
79
+ margin: 0 1px !important;
80
+ }
81
+
82
+ button code, a code, .btn code {
83
+ background: transparent !important;
84
+ padding: 0 !important;
85
+ color: inherit !important;
86
+ border: none !important;
87
+ }
88
+
89
+ code::before, code::after {
90
+ content: "" !important;
91
+ display: none !important;
92
+ }
93
+ `;
94
+
95
+ document.head.appendChild(style);
96
+ };
97
+
98
+ // Subscribe to style config changes from cloud
99
+ useEffect(() => {
100
+ const unsubscribe = subscribeToStyleConfig((config) => {
101
+ applyCodeStyleToDOM(config.code);
102
+ });
103
+ return () => unsubscribe();
104
+ }, [applyCodeStyleToDOM]);
105
+
106
+ // Persist viewMode to localStorage
107
+ useEffect(() => {
108
+ localStorage.setItem('viewMode', viewMode);
109
+ }, [viewMode]);
110
+
111
+ // Subscribe to Firestore updates
112
+ useEffect(() => {
113
+ const unsubscribe = subscribeToItems((newItems) => {
114
+ setItems(newItems);
115
+ setLoading(false);
116
+ setError(null);
117
+ });
118
+
119
+ // Cleanup subscription on unmount
120
+ return () => unsubscribe();
121
+ }, []);
122
+
123
+ const filteredItems = useMemo(() => {
124
+ if (!searchQuery.trim()) {
125
+ const allItems = [...items];
126
+ // Default sorting when no search
127
+ if (sortOrder === 'random') return allItems.sort(() => Math.random() - 0.5);
128
+ if (sortOrder === 'name') return allItems.sort((a, b) => a.title.localeCompare(b.title));
129
+ if (sortOrder === 'updated') return allItems.sort((a, b) => (b.updatedAt || b.createdAt) - (a.updatedAt || a.createdAt));
130
+ return allItems.sort((a, b) => b.createdAt - a.createdAt);
131
+ }
132
+
133
+ const lowerQ = searchQuery.toLowerCase();
134
+
135
+ // SMART SEARCH LOGIC
136
+ const stopWords = new Set([
137
+ 'el', 'la', 'los', 'las', 'un', 'una', 'unos', 'unas', 'y', 'o', 'pero', 'si', 'no',
138
+ 'de', 'del', 'a', 'al', 'en', 'con', 'por', 'para', 'sin', 'sobre', 'entre',
139
+ 'mi', 'tu', 'su', 'nuestro', 'vuestro', 'sus', 'mis', 'tus',
140
+ 'que', 'cual', 'quien', 'donde', 'cuando', 'como', 'porque',
141
+ 'es', 'son', 'fue', 'fueron', 'era', 'eran', 'está', 'están',
142
+ 'este', 'esta', 'ese', 'esa', 'aquel', 'aquella', 'esto', 'eso', 'aquello',
143
+ 'hizo', 'hacer', 'todo', 'toda', 'todos', 'todas', 'muy', 'más', 'tan',
144
+ 'ya', 'hoy', 'ayer', 'ahora', 'después', 'antes', 'mira', 'voy'
145
+ ]);
146
+
147
+ // Tokenize and clean query
148
+ const tokens = lowerQ.replace(/[^\w\sáéíóúñü]/g, '').split(/\s+/).filter(t => t.length > 0);
149
+ const keywords = tokens.filter(t => !stopWords.has(t));
150
+
151
+ // Fallback: If all words were stop words (e.g. "el la"), search normally with full query
152
+ const validKeywords = keywords.length > 0 ? keywords : tokens;
153
+
154
+ // Scoring function
155
+ const getScore = (item: DataItem) => {
156
+ let score = 0;
157
+ const title = item.title.toLowerCase();
158
+ const summary = item.summary.toLowerCase();
159
+ const tags = item.tags.map(t => t.toLowerCase());
160
+
161
+ validKeywords.forEach(keyword => {
162
+ if (title.includes(keyword)) score += 10;
163
+ else if (tags.some(t => t.includes(keyword))) score += 5;
164
+ else if (summary.includes(keyword)) score += 2;
165
+ });
166
+
167
+ return score;
168
+ };
169
+
170
+ // Filter and Map to [Item, Score]
171
+ const scoredItems = items
172
+ .map(item => ({ item, score: getScore(item) }))
173
+ .filter(entry => entry.score > 0);
174
+
175
+ // Sort by Score DESC, then by sortOrder
176
+ scoredItems.sort((a, b) => {
177
+ if (a.score !== b.score) return b.score - a.score; // Higher score first
178
+
179
+ // Secondary sort based on user preference
180
+ if (sortOrder === 'name') return a.item.title.localeCompare(b.item.title);
181
+ if (sortOrder === 'updated') return (b.item.updatedAt || b.item.createdAt) - (a.item.updatedAt || a.item.createdAt);
182
+ if (sortOrder === 'created') return b.item.createdAt - a.item.createdAt;
183
+ return 0;
184
+ });
185
+
186
+ return scoredItems.map(entry => entry.item);
187
+
188
+ }, [items, searchQuery, sortOrder]);
189
+
190
+ const handleCreate = async (data: Omit<DataItem, 'id' | 'createdAt'>) => {
191
+ try {
192
+ await addItem(data);
193
+ setView('LIST');
194
+ } catch (e) {
195
+ alert("Error al guardar en la nube.");
196
+ }
197
+ };
198
+
199
+ const handleUpdate = async (data: Omit<DataItem, 'id' | 'createdAt'>) => {
200
+ if (!selectedItem) return;
201
+ try {
202
+ await updateItem(selectedItem.id, data);
203
+
204
+ // Update local selected item to reflect changes immediately in UI if still in Detail view
205
+ setSelectedItem(prev => prev ? { ...prev, ...data } : null);
206
+ // We do NOT switch view here automatically to allow inline edits in DetailView
207
+ } catch (e) {
208
+ alert("Error al actualizar.");
209
+ }
210
+ };
211
+
212
+ const handleDelete = async (id: string) => {
213
+ try {
214
+ await deleteItem(id);
215
+ setView('LIST');
216
+ setSelectedItem(null);
217
+ } catch (e) {
218
+ alert("Error al eliminar.");
219
+ }
220
+ };
221
+
222
+ if (error) {
223
+ return (
224
+ <div className="min-h-screen bg-background flex flex-col items-center justify-center text-white p-4 text-center">
225
+ <WifiOff size={48} className="text-red-500 mb-4" />
226
+ <h2 className="text-xl font-bold mb-2">Error de Conexión</h2>
227
+ <p className="text-gray-400 max-w-md">{error}</p>
228
+ <p className="text-sm text-gray-500 mt-4">Por favor verifica tu conexión a internet o la configuración de Firebase.</p>
229
+ </div>
230
+ );
231
+ }
232
+
233
+ return (
234
+ <div className="min-h-screen bg-background font-sans text-gray-200 selection:bg-primary selection:text-background pb-20">
235
+
236
+ {/* Navbar */}
237
+ <nav className="sticky top-0 z-50 bg-background/80 backdrop-blur-md border-b border-white/5">
238
+ <div className="w-full max-w-[95%] 2xl:max-w-[1800px] mx-auto px-4 sm:px-6 lg:px-8">
239
+ <div className="flex items-center justify-between h-20">
240
+ <div
241
+ className="flex items-center gap-2 cursor-pointer group"
242
+ onClick={() => { setView('LIST'); setSearchQuery(''); }}
243
+ >
244
+ <div className="p-2 bg-surface rounded-lg group-hover:bg-primary/20 transition-colors">
245
+ <Layers className="text-primary" size={24} />
246
+ </div>
247
+ <span className="text-xl font-bold tracking-tight text-white">
248
+ CodeBy<span className="text-primary">Dante</span>
249
+ </span>
250
+ </div>
251
+
252
+ {view === 'LIST' && (
253
+ <div className="hidden md:flex flex-1 max-w-2xl mx-8 relative">
254
+ <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500" size={18} />
255
+ <input
256
+ type="text"
257
+ placeholder="Buscar en CodeByDante..."
258
+ className="w-full bg-surface border border-white/5 focus:border-primary rounded-full py-2.5 pl-10 pr-4 outline-none text-sm transition-all shadow-inner bg-opacity-50"
259
+ value={searchQuery}
260
+ onChange={(e) => setSearchQuery(e.target.value)}
261
+ />
262
+ </div>
263
+ )}
264
+
265
+ <div className="flex items-center gap-3">
266
+ <Button
267
+ variant="secondary"
268
+ onClick={() => {
269
+ const orders: ('updated' | 'created' | 'name' | 'random')[] = ['updated', 'created', 'name', 'random'];
270
+ const currentIndex = orders.indexOf(sortOrder);
271
+ const nextOrder = orders[(currentIndex + 1) % orders.length];
272
+ setSortOrder(nextOrder);
273
+ }}
274
+ className="bg-surface border border-white/5 hover:bg-surfaceHover transition-all hover:scale-105 active:scale-95 flex items-center gap-2 px-3 min-w-0 sm:min-w-[140px] justify-center"
275
+ title={`Ordenar por: ${sortOrder === 'updated' ? 'Modificación' : sortOrder === 'created' ? 'Fecha' : sortOrder === 'name' ? 'Nombre' : 'Aleatorio'}`}
276
+ >
277
+ {sortOrder === 'updated' && (
278
+ <>
279
+ <Clock size={16} className="text-primary" />
280
+ <span className="text-sm font-medium hidden sm:inline">Recientes</span>
281
+ </>
282
+ )}
283
+ {sortOrder === 'created' && (
284
+ <>
285
+ <Calendar size={16} className="text-primary" />
286
+ <span className="text-sm font-medium hidden sm:inline">Fecha</span>
287
+ </>
288
+ )}
289
+ {sortOrder === 'name' && (
290
+ <>
291
+ <Type size={16} className="text-primary" />
292
+ <span className="text-sm font-medium hidden sm:inline">Nombre</span>
293
+ </>
294
+ )}
295
+ {sortOrder === 'random' && (
296
+ <>
297
+ <Shuffle size={16} className="text-primary" />
298
+ <span className="text-sm font-medium hidden sm:inline">Aleatorio</span>
299
+ </>
300
+ )}
301
+ </Button>
302
+
303
+ <div className="relative">
304
+ <Button
305
+ variant="secondary"
306
+ onClick={() => setIsSettingsOpen(!isSettingsOpen)}
307
+ className="bg-surface border border-white/5 hover:bg-surfaceHover"
308
+ >
309
+ <Settings size={20} />
310
+ </Button>
311
+
312
+ {isSettingsOpen && (
313
+ <>
314
+ <div
315
+ className="fixed inset-0 z-10"
316
+ onClick={() => setIsSettingsOpen(false)}
317
+ />
318
+ <div className="absolute right-0 mt-2 w-48 bg-surface border border-white/10 rounded-xl shadow-xl z-20 overflow-hidden animate-in fade-in zoom-in-95 duration-200">
319
+ <div className="p-1">
320
+
321
+ <button
322
+ onClick={() => {
323
+ if (viewMode === 'admin') {
324
+ setViewMode('normal');
325
+ setIsSettingsOpen(false);
326
+ } else {
327
+ setShowAdminLogin(true);
328
+ setIsSettingsOpen(false);
329
+ }
330
+ }}
331
+ className={`w-full flex items-center gap-2 px-3 py-2 rounded-lg text-sm transition-colors ${viewMode === 'admin'
332
+ ? 'bg-primary/10 text-primary'
333
+ : 'text-gray-400 hover:bg-white/5 hover:text-white'
334
+ }`}
335
+ >
336
+ <Settings size={16} />
337
+ {viewMode === 'admin' ? 'Desactivar Admin' : 'Modo Admin'}
338
+ </button>
339
+ </div>
340
+ </div>
341
+ </>
342
+ )}
343
+ </div>
344
+
345
+ {viewMode === 'admin' && (
346
+ <Button onClick={() => { setSelectedItem(null); setView('CREATE'); }}>
347
+ <Plus size={20} /> <span className="hidden sm:inline">Nueva Entrada</span>
348
+ </Button>
349
+ )}
350
+ </div>
351
+ </div>
352
+ </div>
353
+ </nav>
354
+
355
+ {/* Mobile Search Bar */}
356
+ {view === 'LIST' && (
357
+ <div className="md:hidden px-4 py-4 bg-background border-b border-white/5">
358
+ <div className="relative">
359
+ <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500" size={18} />
360
+ <input
361
+ type="text"
362
+ placeholder="Buscar..."
363
+ className="w-full bg-surface border border-white/5 focus:border-primary rounded-lg py-3 pl-10 pr-4 outline-none text-sm"
364
+ value={searchQuery}
365
+ onChange={(e) => setSearchQuery(e.target.value)}
366
+ />
367
+ </div>
368
+ </div>
369
+ )}
370
+
371
+ {/* Main Content */}
372
+ <main className="w-full max-w-[95%] 2xl:max-w-[1800px] mx-auto px-4 sm:px-6 lg:px-8 py-8">
373
+
374
+ {loading ? (
375
+ <div className="flex flex-col items-center justify-center py-20">
376
+ <Loader2 className="animate-spin text-primary mb-4" size={40} />
377
+ <p className="text-gray-500">Sincronizando con CodeByDante Cloud...</p>
378
+ </div>
379
+ ) : (
380
+ <>
381
+ {view === 'LIST' && (
382
+ <>
383
+ {filteredItems.length === 0 ? (
384
+ <div className="text-center py-20 opacity-50">
385
+ <div className="inline-block p-6 rounded-full bg-surface mb-4">
386
+ <Search size={48} className="text-gray-600" />
387
+ </div>
388
+ <h3 className="text-xl font-medium">No se encontraron elementos</h3>
389
+ <p className="text-gray-500 mt-2">El repositorio está vacío o no hay coincidencias.</p>
390
+ </div>
391
+ ) : (
392
+ <div
393
+ className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3"
394
+ >
395
+ {filteredItems.map(item => (
396
+ <Card
397
+ key={item.id}
398
+ item={item}
399
+ onClick={(i) => { setSelectedItem(i); setView('DETAIL'); }}
400
+ onTagClick={(tag) => {
401
+ setSearchQuery(tag);
402
+ setView('LIST');
403
+ }}
404
+ />
405
+ ))}
406
+ </div>
407
+ )}
408
+ </>
409
+ )}
410
+
411
+ {view === 'CREATE' && (
412
+ <DataForm
413
+ onSave={handleCreate}
414
+ onCancel={() => setView('LIST')}
415
+ />
416
+ )}
417
+
418
+ {view === 'EDIT' && selectedItem && (
419
+ <DataForm
420
+ initialData={selectedItem}
421
+ onSave={(data) => {
422
+ handleUpdate(data);
423
+ setView('DETAIL'); // Explicitly go back to detail after full edit
424
+ }}
425
+ onCancel={() => setView('DETAIL')}
426
+ />
427
+ )}
428
+
429
+ {view === 'DETAIL' && selectedItem && (
430
+ <DetailView
431
+ item={selectedItem}
432
+ onBack={() => setView('LIST')}
433
+ onUpdate={handleUpdate}
434
+ onDelete={handleDelete}
435
+ isEditable={viewMode === 'admin'}
436
+ onTagClick={(tag) => {
437
+ setSearchQuery(tag);
438
+ setView('LIST');
439
+ }}
440
+ />
441
+ )}
442
+ </>
443
+ )}
444
+
445
+ </main>
446
+ <AdminLoginModal
447
+ isOpen={showAdminLogin}
448
+ onClose={() => setShowAdminLogin(false)}
449
+ onSuccess={() => {
450
+ setViewMode('admin');
451
+ setShowAdminLogin(false);
452
+ }}
453
+ />
454
+ </div>
455
+ );
456
+ };
457
+
458
+ export default App;
README.md CHANGED
@@ -1,10 +1,3 @@
1
- ---
2
- title: Codebydante
3
- emoji: 🚀
4
- colorFrom: yellow
5
- colorTo: pink
6
- sdk: docker
7
- pinned: false
8
- ---
9
 
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
+ # CodeByDante
 
 
 
 
 
 
 
2
 
3
+ pacto del colbador
components/AIInstructionModal.tsx ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useState, useEffect, useRef } from 'react';
2
+ import { X, Sparkles, Wand2, Loader2 } from 'lucide-react';
3
+ import { motion, AnimatePresence } from 'framer-motion';
4
+
5
+ interface AIInstructionModalProps {
6
+ isOpen: boolean;
7
+ onClose: () => void;
8
+ onGenerate: (instructions: string) => Promise<void>;
9
+ currentContent?: string;
10
+ }
11
+
12
+ export const AIInstructionModal: React.FC<AIInstructionModalProps> = ({
13
+ isOpen,
14
+ onClose,
15
+ onGenerate,
16
+ currentContent
17
+ }) => {
18
+ const [instructions, setInstructions] = useState('');
19
+ const [isGenerating, setIsGenerating] = useState(false);
20
+ const textareaRef = useRef<HTMLTextAreaElement>(null);
21
+
22
+ useEffect(() => {
23
+ if (isOpen) {
24
+ setInstructions('');
25
+ setIsGenerating(false);
26
+ // Focus after animation
27
+ setTimeout(() => textareaRef.current?.focus(), 100);
28
+ }
29
+ }, [isOpen]);
30
+
31
+ const handleSubmit = async (e?: React.FormEvent) => {
32
+ e?.preventDefault();
33
+ if (!instructions.trim() || isGenerating) return;
34
+
35
+ setIsGenerating(true);
36
+ try {
37
+ await onGenerate(instructions);
38
+ onClose();
39
+ } catch (error) {
40
+ console.error("Analysis failed", error);
41
+ } finally {
42
+ setIsGenerating(false);
43
+ }
44
+ };
45
+
46
+ const isContentEmpty = !currentContent || currentContent.trim().length === 0;
47
+ const title = isContentEmpty ? "¿Qué deseas crear?" : "¿Cómo deseas mejorarlo?";
48
+ const placeholder = isContentEmpty
49
+ ? "Ej: Escribe un resumen sobre React Hooks..."
50
+ : "Ej: Hazlo más conciso, añade emojis, tradúcelo al inglés...";
51
+
52
+ return (
53
+ <AnimatePresence>
54
+ {isOpen && (
55
+ <>
56
+ {/* Backdrop */}
57
+ <motion.div
58
+ initial={{ opacity: 0 }}
59
+ animate={{ opacity: 1 }}
60
+ exit={{ opacity: 0 }}
61
+ onClick={onClose}
62
+ className="fixed inset-0 bg-black/60 backdrop-blur-sm z-50 flex items-center justify-center p-4"
63
+ />
64
+
65
+ {/* Modal */}
66
+ <motion.div
67
+ initial={{ opacity: 0, scale: 0.95, y: 20 }}
68
+ animate={{ opacity: 1, scale: 1, y: 0 }}
69
+ exit={{ opacity: 0, scale: 0.95, y: 20 }}
70
+ className="fixed inset-0 z-50 flex items-center justify-center pointer-events-none"
71
+ >
72
+ <div className="w-full max-w-lg bg-[#1a1a1a] border border-white/10 rounded-2xl shadow-2xl overflow-hidden pointer-events-auto flex flex-col">
73
+
74
+ {/* Header */}
75
+ <div className="relative h-32 bg-gradient-to-br from-indigo-600/20 via-purple-600/20 to-pink-600/20 flex flex-col items-center justify-center border-b border-white/5">
76
+ <button
77
+ onClick={onClose}
78
+ className="absolute top-4 right-4 text-white/50 hover:text-white transition-colors"
79
+ >
80
+ <X size={20} />
81
+ </button>
82
+
83
+ <div className="w-12 h-12 rounded-full bg-gradient-to-tr from-indigo-500 to-purple-500 flex items-center justify-center shadow-lg shadow-purple-500/30 mb-3">
84
+ <Sparkles className="text-white" size={24} />
85
+ </div>
86
+ <h3 className="text-xl font-bold text-white tracking-tight">{title}</h3>
87
+ <p className="text-white/50 text-xs mt-1">Dante AI Assistant</p>
88
+ </div>
89
+
90
+ {/* Body */}
91
+ <div className="p-6 space-y-4">
92
+ <div className="relative">
93
+ <textarea
94
+ ref={textareaRef}
95
+ value={instructions}
96
+ onChange={(e) => setInstructions(e.target.value)}
97
+ onKeyDown={(e) => {
98
+ if (e.key === 'Enter' && !e.shiftKey) {
99
+ e.preventDefault();
100
+ handleSubmit();
101
+ }
102
+ }}
103
+ placeholder={placeholder}
104
+ className="w-full h-32 bg-black/20 border border-white/10 rounded-xl p-4 text-white placeholder:text-white/20 resize-none focus:outline-none focus:border-purple-500/50 focus:ring-1 focus:ring-purple-500/50 transition-all text-base"
105
+ />
106
+ <div className="absolute bottom-3 right-3 text-xs text-white/30">
107
+ Enter para enviar
108
+ </div>
109
+ </div>
110
+
111
+ <button
112
+ onClick={() => handleSubmit()}
113
+ disabled={!instructions.trim() || isGenerating}
114
+ className="w-full py-3 bg-white text-black font-semibold rounded-xl hover:bg-white/90 disabled:opacity-50 disabled:cursor-not-allowed transition-all flex items-center justify-center gap-2 shadow-lg shadow-white/10"
115
+ >
116
+ {isGenerating ? (
117
+ <>
118
+ <Loader2 size={18} className="animate-spin" />
119
+ <span>Procesando...</span>
120
+ </>
121
+ ) : (
122
+ <>
123
+ <Wand2 size={18} />
124
+ <span>{isContentEmpty ? 'Generar Contenido' : 'Aplicar Mejoras'}</span>
125
+ </>
126
+ )}
127
+ </button>
128
+ </div>
129
+ </div>
130
+ </motion.div>
131
+ </>
132
+ )}
133
+ </AnimatePresence>
134
+ );
135
+ };
components/AdminLoginModal.tsx ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useState, useEffect } from 'react';
2
+ import { Lock, X, KeyRound } from 'lucide-react';
3
+ import { Button } from './Button';
4
+
5
+ interface AdminLoginModalProps {
6
+ isOpen: boolean;
7
+ onClose: () => void;
8
+ onSuccess: () => void;
9
+ }
10
+
11
+ export const AdminLoginModal: React.FC<AdminLoginModalProps> = ({ isOpen, onClose, onSuccess }) => {
12
+ const [password, setPassword] = useState('');
13
+ const [error, setError] = useState(false);
14
+ const [isAnimating, setIsAnimating] = useState(false);
15
+
16
+ useEffect(() => {
17
+ if (isOpen) {
18
+ setIsAnimating(true);
19
+ setPassword('');
20
+ setError(false);
21
+ } else {
22
+ setTimeout(() => setIsAnimating(false), 200);
23
+ }
24
+ }, [isOpen]);
25
+
26
+ if (!isOpen && !isAnimating) return null;
27
+
28
+ const handleLogin = async () => {
29
+ try {
30
+ console.log('[AdminLogin] Starting login process...');
31
+
32
+ if (!password) {
33
+ console.log('[AdminLogin] No password entered');
34
+ setError(true);
35
+ return;
36
+ }
37
+
38
+ if (!window.crypto || !window.crypto.subtle) {
39
+ console.error('[AdminLogin] Crypto API not available', { crypto: !!window.crypto, subtle: !!window.crypto?.subtle });
40
+ alert('Error crítico: Tu navegador no soporta la encriptación necesaria (crypto.subtle). Por favor usa un navegador moderno o contexto seguro (HTTPS/localhost).');
41
+ return;
42
+ }
43
+
44
+ const encoder = new TextEncoder();
45
+ const data = encoder.encode(password);
46
+
47
+ console.log('[AdminLogin] Hashing password...');
48
+ const hashBuffer = await crypto.subtle.digest('SHA-256', data);
49
+ const hashArray = Array.from(new Uint8Array(hashBuffer));
50
+ const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
51
+
52
+ console.log('[AdminLogin] Hash generated:', hashHex);
53
+
54
+ // Hash for 'codebydante069012*'
55
+ const expectedHash = '19362a1b321cd1b4fe5a625b8a6647a371beebebd3daddccdb2ed271a9a7ee5d';
56
+
57
+ if (hashHex === expectedHash) {
58
+ console.log('[AdminLogin] Password correct!');
59
+ onSuccess();
60
+ onClose();
61
+ } else {
62
+ console.warn('[AdminLogin] Password incorrect. Expected:', expectedHash, 'Got:', hashHex);
63
+ setError(true);
64
+ }
65
+ } catch (e: any) {
66
+ console.error('[AdminLogin] Unexpected error:', e);
67
+ alert(`Error inesperado: ${e.message || e}`);
68
+ }
69
+ };
70
+
71
+ const handleKeyDown = (e: React.KeyboardEvent) => {
72
+ if (e.key === 'Enter') {
73
+ handleLogin();
74
+ }
75
+ };
76
+
77
+ return (
78
+ <div
79
+ className={`fixed inset-0 z-50 flex items-center justify-center p-4 transition-all duration-300 ${isOpen ? 'opacity-100 backdrop-blur-sm bg-black/50' : 'opacity-0 pointer-events-none'
80
+ }`}
81
+ >
82
+ <div
83
+ className={`bg-[#1a1a1a] border border-white/10 rounded-2xl w-full max-w-md overflow-hidden shadow-2xl transition-all duration-300 transform ${isOpen ? 'scale-100 translate-y-0' : 'scale-95 translate-y-4'
84
+ }`}
85
+ >
86
+ {/* Header */}
87
+ <div className="flex items-center justify-between p-6 border-b border-white/5">
88
+ <div className="flex items-center gap-3">
89
+ <div className="p-2 bg-primary/20 rounded-lg">
90
+ <Lock className="w-6 h-6 text-primary" />
91
+ </div>
92
+ <div>
93
+ <h2 className="text-lg font-bold text-white">Acceso Administrativo</h2>
94
+ <p className="text-xs text-gray-400">Introduce la credencial de seguridad</p>
95
+ </div>
96
+ </div>
97
+ <button
98
+ onClick={onClose}
99
+ className="text-gray-400 hover:text-white transition-colors p-1"
100
+ >
101
+ <X size={20} />
102
+ </button>
103
+ </div>
104
+
105
+ {/* Content */}
106
+ <div className="p-6 space-y-4">
107
+ <div className="bg-primary/5 border border-primary/20 rounded-lg p-3 text-xs text-primary/80">
108
+ <p>Esta zona está protegida. Solo personal autorizado.</p>
109
+ </div>
110
+
111
+ <div className="space-y-2">
112
+ <label className="text-sm font-medium text-gray-300 flex items-center gap-2">
113
+ <KeyRound size={14} /> Tu Clave Maestra
114
+ </label>
115
+ <input
116
+ type="password"
117
+ value={password}
118
+ onChange={(e) => {
119
+ setPassword(e.target.value);
120
+ setError(false);
121
+ }}
122
+ onKeyDown={handleKeyDown}
123
+ className={`w-full bg-black/40 border rounded-lg px-4 py-3 text-white placeholder-gray-600 outline-none focus:ring-1 transition-all ${error
124
+ ? 'border-red-500 focus:border-red-500 focus:ring-red-500/20'
125
+ : 'border-white/10 focus:border-primary focus:ring-primary/20'
126
+ }`}
127
+ placeholder="••••••••••••••"
128
+ autoFocus
129
+ />
130
+ {error && (
131
+ <p className="text-xs text-red-500 animate-pulse">
132
+ Acceso denegado. Credencial inválida.
133
+ </p>
134
+ )}
135
+ </div>
136
+ </div>
137
+
138
+ {/* Footer */}
139
+ <div className="p-6 pt-0 flex gap-3">
140
+ <Button
141
+ variant="danger"
142
+ onClick={onClose}
143
+ className="flex-1 bg-white/5 border-white/10 hover:bg-white/10"
144
+ >
145
+ Cancelar
146
+ </Button>
147
+ <Button
148
+ variant="primary"
149
+ onClick={handleLogin}
150
+ className="flex-1"
151
+ >
152
+ Acceder
153
+ </Button>
154
+ </div>
155
+ </div>
156
+ </div>
157
+ );
158
+ };
components/BlockEditorModal.tsx ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useState, useEffect } from 'react';
2
+ import { X, Check } from 'lucide-react';
3
+ import { StyleSettingsPanel } from './StyleSettingsPanel';
4
+ import { Editor } from '@tiptap/react';
5
+ import {
6
+ DEFAULT_STYLE_CONFIG,
7
+ type StyleConfig
8
+ } from '../services/codeStyleService';
9
+
10
+ interface BlockEditorModalProps {
11
+ isOpen: boolean;
12
+ onClose: () => void;
13
+ editor: Editor | null;
14
+ type: 'quote' | 'code';
15
+ }
16
+
17
+ export const BlockEditorModal: React.FC<BlockEditorModalProps> = ({
18
+ isOpen,
19
+ onClose,
20
+ editor,
21
+ type
22
+ }) => {
23
+ const [localConfig, setLocalConfig] = useState<StyleConfig>(DEFAULT_STYLE_CONFIG);
24
+ const [activeTab, setActiveTab] = useState<'code' | 'quote' | 'general'>(type === 'quote' ? 'quote' : 'code');
25
+
26
+ useEffect(() => {
27
+ if (isOpen && editor) {
28
+ // Load current attributes from selection
29
+ const { from, to } = editor.state.selection;
30
+ let node;
31
+
32
+ editor.state.doc.nodesBetween(from, to, (n) => {
33
+ if (n.type.name === 'customBlockquote' && type === 'quote') {
34
+ node = n;
35
+ return false;
36
+ }
37
+ // Add code block support if needed
38
+ return true;
39
+ });
40
+
41
+ if (node && type === 'quote') {
42
+ const attrs = (node as any).attrs;
43
+ setLocalConfig(prev => ({
44
+ ...prev,
45
+ quote: {
46
+ ...prev.quote,
47
+ borderColor: attrs.borderColor || prev.quote.borderColor,
48
+ borderWidth: attrs.borderWidth || prev.quote.borderWidth,
49
+ bgColor: attrs.backgroundColor || prev.quote.bgColor,
50
+ textColor: attrs.textColor || prev.quote.textColor,
51
+ padding: attrs.padding || prev.quote.padding,
52
+ fontSize: attrs.fontSize || prev.quote.fontSize,
53
+ borderRadius: attrs.borderRadius || prev.quote.borderRadius,
54
+ width: attrs.width || prev.quote.width,
55
+ height: attrs.height || prev.quote.height,
56
+ italic: attrs.italic || prev.quote.italic,
57
+ showCopyButton: attrs.showCopyButton || prev.quote.showCopyButton
58
+ }
59
+ }));
60
+ }
61
+ }
62
+ }, [isOpen, editor, type]);
63
+
64
+ const handleUpdateConfig = (newConfig: StyleConfig) => {
65
+ setLocalConfig(newConfig);
66
+ if (editor) {
67
+ if (type === 'quote') {
68
+ editor.chain().focus().updateAttributes('customBlockquote', {
69
+ borderColor: newConfig.quote.borderColor,
70
+ borderWidth: newConfig.quote.borderWidth,
71
+ backgroundColor: newConfig.quote.bgColor,
72
+ textColor: newConfig.quote.textColor,
73
+ padding: newConfig.quote.padding,
74
+ fontSize: newConfig.quote.fontSize,
75
+ borderRadius: newConfig.quote.borderRadius,
76
+ width: newConfig.quote.width,
77
+ height: newConfig.quote.height,
78
+ italic: newConfig.quote.italic,
79
+ showCopyButton: newConfig.quote.showCopyButton
80
+ }).run();
81
+ }
82
+ // Implement code block update if needed
83
+ }
84
+ };
85
+
86
+ if (!isOpen) return null;
87
+
88
+ return (
89
+ <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm animate-fade-in">
90
+ <div className="bg-[#1a1a1a] border border-white/10 rounded-xl shadow-2xl w-[450px] max-h-[85vh] flex flex-col overflow-hidden">
91
+ <div className="p-4 border-b border-white/5 bg-white/5 flex items-center justify-between">
92
+ <h3 className="text-white font-bold flex items-center gap-2">
93
+ Editar Estilo de {type === 'quote' ? 'Cita' : 'Código'}
94
+ </h3>
95
+ <button
96
+ onClick={onClose}
97
+ className="text-gray-500 hover:text-white transition-colors"
98
+ >
99
+ <X size={20} />
100
+ </button>
101
+ </div>
102
+
103
+ <div className="flex-1 overflow-hidden flex flex-col">
104
+ <StyleSettingsPanel
105
+ styleConfig={localConfig}
106
+ onUpdateConfig={handleUpdateConfig}
107
+ activeTab={activeTab}
108
+ onTabChange={(tab) => {
109
+ if (tab === 'general' || tab === type) {
110
+ setActiveTab(tab);
111
+ }
112
+ }}
113
+ onConfirm={onClose}
114
+ onClose={onClose}
115
+ hideTabs={true}
116
+ // Preview content is now handled by the editor itself in the background
117
+ // But StyleSettingsPanel expects a previewContent string.
118
+ // We can pass a dummy string or try to extract text from editor node.
119
+ previewContent="Vista previa en el editor"
120
+ />
121
+ </div>
122
+ </div>
123
+ </div>
124
+ );
125
+ };
components/Button.tsx ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React from 'react';
2
+
3
+ interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
4
+ variant?: 'primary' | 'secondary' | 'danger' | 'ghost' | 'outline';
5
+ isLoading?: boolean;
6
+ }
7
+
8
+ export const Button: React.FC<ButtonProps> = ({
9
+ children,
10
+ variant = 'primary',
11
+ className = '',
12
+ isLoading = false,
13
+ ...props
14
+ }) => {
15
+ const baseStyles = "px-4 py-2 rounded-lg font-medium transition-all duration-200 flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed";
16
+
17
+ const variants = {
18
+ primary: "bg-primary text-background hover:bg-opacity-90 shadow-[0_0_10px_rgba(187,134,252,0.3)]",
19
+ secondary: "bg-surfaceHover text-white hover:bg-white/10 border border-white/10",
20
+ outline: "bg-transparent border border-primary text-primary hover:bg-primary hover:text-background shadow-[0_0_5px_rgba(187,134,252,0.2)]",
21
+ danger: "bg-red-500/10 text-red-400 border border-red-500/20 hover:bg-red-500/20",
22
+ ghost: "text-gray-400 hover:text-white hover:bg-white/5"
23
+ };
24
+
25
+ return (
26
+ <button
27
+ className={`${baseStyles} ${variants[variant]} ${className}`}
28
+ disabled={isLoading || props.disabled}
29
+ {...props}
30
+ >
31
+ {isLoading ? (
32
+ <span className="animate-spin h-4 w-4 border-2 border-current border-t-transparent rounded-full" />
33
+ ) : null}
34
+ {children}
35
+ </button>
36
+ );
37
+ };
components/Card.tsx ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React from 'react';
2
+ import { DataItem } from '../types';
3
+ import { Download, ExternalLink } from 'lucide-react';
4
+ import { getIconComponent } from './IconPicker';
5
+
6
+ interface CardProps {
7
+ item: DataItem;
8
+ onClick: (item: DataItem) => void;
9
+ }
10
+
11
+ export const Card: React.FC<CardProps> = ({ item, onClick }) => {
12
+ console.log('[Card] Rendering item:', item.title, 'Icon:', item.icon);
13
+ const Icon = getIconComponent(item.icon);
14
+ return (
15
+ <div
16
+ onClick={() => onClick(item)}
17
+ className="group bg-surface border border-white/5 hover:border-primary/30 rounded-xl p-3 sm:p-4 cursor-pointer transition-all duration-300 hover:-translate-y-1 hover:shadow-xl flex flex-col h-full min-h-[200px]"
18
+ >
19
+ <div className="mb-2 flex-grow flex flex-col">
20
+ <div className="flex items-start gap-2">
21
+ {Icon && (
22
+ <div className="text-primary shrink-0">
23
+ <Icon size={20} className="sm:w-6 sm:h-6" />
24
+ </div>
25
+ )}
26
+ <h3
27
+ className="text-base sm:text-lg font-bold text-white mb-2 group-hover:text-primary transition-colors line-clamp-2 [&>p]:m-0 [&>p]:inline"
28
+ dangerouslySetInnerHTML={{ __html: item.title }}
29
+ />
30
+ </div>
31
+ <div
32
+ className="text-zinc-400 text-[11px] sm:text-xs leading-normal [&>p]:m-0 [&_img]:w-full [&_img]:h-full [&_img]:object-cover [&_img]:p-0 [&_img]:m-0 [&_img]:rounded-none [&_figure]:p-0 [&_figure]:m-0 [&_figure]:bg-transparent overflow-hidden"
33
+ dangerouslySetInnerHTML={{ __html: item.summary }}
34
+ style={{
35
+ display: '-webkit-box',
36
+ WebkitLineClamp: (item.visitUrl || item.downloadUrl) ? 4 : 7,
37
+ WebkitBoxOrient: 'vertical',
38
+ overflow: 'hidden'
39
+ }}
40
+ />
41
+ </div>
42
+
43
+
44
+
45
+ {/* Buttons Section */}
46
+ {/* Buttons Section */}
47
+ {(item.visitUrl || item.downloadUrl) && (
48
+ <div className="mt-auto flex gap-2 sm:gap-3 pt-2 flex-wrap">
49
+ {item.visitUrl && (
50
+ <a
51
+ href={item.visitUrl}
52
+ target="_blank"
53
+ rel="noopener noreferrer"
54
+ onClick={(e) => e.stopPropagation()}
55
+ className={`flex-1 bg-transparent border border-[#bb86fc] text-[#bb86fc] font-medium py-1.5 px-3 sm:py-2.5 sm:px-4 rounded-lg flex items-center justify-center gap-2 hover:bg-[#bb86fc] hover:text-[#121212] transition-all text-xs sm:text-sm shadow-[0_0_5px_rgba(187,134,252,0.2)] ${!item.downloadUrl ? 'w-full' : 'min-w-[100px]'}`}
56
+ >
57
+ <ExternalLink size={14} className="sm:w-4 sm:h-4" strokeWidth={2.5} />
58
+ Visitar
59
+ </a>
60
+ )}
61
+
62
+ {item.downloadUrl && (
63
+ <a
64
+ href={item.downloadUrl}
65
+ target="_blank"
66
+ rel="noopener noreferrer"
67
+ onClick={(e) => e.stopPropagation()}
68
+ className={`flex-1 bg-transparent border border-[#bb86fc] text-[#bb86fc] font-medium py-1.5 px-3 sm:py-2.5 sm:px-4 rounded-lg flex items-center justify-center gap-2 hover:bg-[#bb86fc] hover:text-[#121212] transition-all text-xs sm:text-sm shadow-[0_0_5px_rgba(187,134,252,0.2)] ${!item.visitUrl ? 'w-full' : 'min-w-[100px]'}`}
69
+ >
70
+ <Download size={14} className="sm:w-4 sm:h-4" strokeWidth={2.5} />
71
+ Descargar
72
+ </a>
73
+ )}
74
+ </div>
75
+ )}
76
+ </div>
77
+ );
78
+ };
components/CodeBlockComponent.tsx ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useState, useEffect, useRef } from 'react';
2
+ import { NodeViewWrapper, NodeViewContent, NodeViewProps } from '@tiptap/react';
3
+ import { Copy, Check, Download, Pencil, ChevronDown, ChevronUp } from 'lucide-react';
4
+
5
+ export const CodeBlockComponent: React.FC<NodeViewProps> = (props) => {
6
+ const [copied, setCopied] = useState(false);
7
+ const { node: { attrs: { language: defaultLanguage, filename: defaultFilename, showLineNumbers, wrapText } }, updateAttributes, extension } = props;
8
+ const [detectedLang, setDetectedLang] = useState(defaultLanguage || 'text');
9
+ const [isEditingName, setIsEditingName] = useState(false);
10
+ const [filename, setFilename] = useState(defaultFilename || '');
11
+ const inputRef = useRef<HTMLInputElement>(null);
12
+ const [isManualExpanded, setIsManualExpanded] = useState(false);
13
+ const contentRef = useRef<HTMLDivElement>(null);
14
+ const [contentHeight, setContentHeight] = useState<string | number>('300px'); // Default max height for collapsed state
15
+
16
+ const handleCopy = () => {
17
+ const text = props.node.textContent;
18
+ navigator.clipboard.writeText(text).then(() => {
19
+ setCopied(true);
20
+ setTimeout(() => setCopied(false), 2000);
21
+ });
22
+ };
23
+
24
+ const detectLanguage = (content: string): string => {
25
+ const c = content.trim();
26
+ if (c.startsWith('npm ') || c.startsWith('yarn ') || c.startsWith('pnpm ') || c.startsWith('npx ') || c.startsWith('git ')) return 'bash';
27
+ if (c.includes('@echo off') || c.startsWith('::') || c.startsWith('REM ') || c.includes('set "PROYECTO=')) return 'batch';
28
+ if ((c.includes('def ') && c.includes(':')) || c.includes('import pandas') || c.includes('print(')) return 'python';
29
+ if (c.includes('public class') || c.includes('System.out.println') || c.includes('public static void')) return 'java';
30
+ if (c.includes('import React') || c.includes('export const') || c.includes('interface ')) return 'typescript';
31
+ if (c.includes('function ') || c.includes('const ') || c.includes('let ') || c.includes('console.log')) return 'javascript';
32
+ if (c.includes('<!DOCTYPE html>') || c.includes('</div>')) return 'html';
33
+ if (c.includes('{') && c.includes('}') && c.includes(':') && c.includes(';')) return 'css';
34
+ return 'text';
35
+ };
36
+
37
+ useEffect(() => {
38
+ const content = props.node.textContent;
39
+ const lang = detectLanguage(content);
40
+ if (lang !== detectedLang && lang !== 'text') {
41
+ setDetectedLang(lang);
42
+ updateAttributes({ language: lang });
43
+ } else if (lang === 'text' && defaultLanguage && defaultLanguage !== 'text') {
44
+ setDetectedLang(defaultLanguage);
45
+ }
46
+
47
+ if (contentRef.current) {
48
+ setContentHeight(contentRef.current.scrollHeight);
49
+ }
50
+
51
+ const handleResize = () => {
52
+ if (contentRef.current) {
53
+ setContentHeight(contentRef.current.scrollHeight);
54
+ }
55
+ };
56
+
57
+ window.addEventListener('resize', handleResize);
58
+ return () => window.removeEventListener('resize', handleResize);
59
+ }, [props.node.textContent, isManualExpanded, showLineNumbers, wrapText]); // Added dependencies
60
+
61
+ useEffect(() => {
62
+ if (isEditingName && inputRef.current) {
63
+ inputRef.current.focus();
64
+ }
65
+ }, [isEditingName]);
66
+
67
+ const handleDownload = () => {
68
+ const text = props.node.textContent;
69
+
70
+ let downloadName = filename;
71
+ if (!downloadName) {
72
+ const extensionMap: Record<string, string> = {
73
+ 'bash': 'sh',
74
+ 'batch': 'bat',
75
+ 'python': 'py',
76
+ 'java': 'java',
77
+ 'typescript': 'ts',
78
+ 'javascript': 'js',
79
+ 'html': 'html',
80
+ 'css': 'css',
81
+ 'text': 'txt'
82
+ };
83
+ const ext = extensionMap[detectedLang] || 'txt';
84
+ downloadName = `code.${ext}`;
85
+ }
86
+
87
+ const blob = new Blob([text], { type: 'text/plain' });
88
+ const url = URL.createObjectURL(blob);
89
+ const a = document.createElement('a');
90
+ a.href = url;
91
+ a.download = downloadName;
92
+ document.body.appendChild(a);
93
+ a.click();
94
+ document.body.removeChild(a);
95
+ URL.revokeObjectURL(url);
96
+ };
97
+
98
+ const handleNameSubmit = () => {
99
+ setIsEditingName(false);
100
+ updateAttributes({ filename });
101
+ };
102
+
103
+ const handleKeyDown = (e: React.KeyboardEvent) => {
104
+ if (e.key === 'Enter') {
105
+ handleNameSubmit();
106
+ }
107
+ };
108
+
109
+ const handleClick = (e: React.MouseEvent) => {
110
+ if (e.detail === 3 && props.editor.isEditable) {
111
+ e.preventDefault();
112
+ const event = new CustomEvent('block-triple-click', {
113
+ detail: { type: 'code', pos: props.getPos() },
114
+ bubbles: true
115
+ });
116
+ props.editor.view.dom.dispatchEvent(event);
117
+ }
118
+ };
119
+
120
+ const toggleExpand = () => {
121
+ setIsManualExpanded(!isManualExpanded);
122
+ };
123
+
124
+ const isCollapsed = props.node.attrs.collapsible && !isManualExpanded;
125
+
126
+ const lineCount = props.node.textContent.split('\n').length;
127
+
128
+ return (
129
+ <NodeViewWrapper
130
+ className="relative group my-6 rounded-xl overflow-hidden bg-[#151515] border border-white/10 shadow-2xl ring-1 ring-white/5 w-full not-prose"
131
+ onClick={handleClick}
132
+ >
133
+ <div className="flex items-center justify-between px-4 py-3 bg-[#202020] border-b border-white/5">
134
+ <div className="flex items-center gap-2">
135
+ <div className="flex gap-1.5">
136
+ <div className="w-3 h-3 rounded-full bg-[#ff5f56] border border-[#e0443e]/50"></div>
137
+ <div className="w-3 h-3 rounded-full bg-[#ffbd2e] border border-[#dea123]/50"></div>
138
+ <div className="w-3 h-3 rounded-full bg-[#27c93f] border border-[#1aab29]/50"></div>
139
+ </div>
140
+
141
+ {isEditingName ? (
142
+ <input
143
+ ref={inputRef}
144
+ type="text"
145
+ value={filename}
146
+ onChange={(e) => setFilename(e.target.value)}
147
+ onBlur={handleNameSubmit}
148
+ onKeyDown={handleKeyDown}
149
+ className="ml-3 text-xs font-medium text-zinc-200 bg-white/10 rounded px-1.5 py-0.5 outline-none border border-white/20 w-32 font-mono"
150
+ placeholder="nombre.ext"
151
+ />
152
+ ) : (
153
+ <span className="ml-3 text-xs font-medium text-zinc-400 uppercase tracking-wider select-none font-mono">
154
+ {filename || detectedLang}
155
+ </span>
156
+ )}
157
+ </div>
158
+ <div className="flex items-center gap-2">
159
+ {props.editor.isEditable && (
160
+ <button
161
+ onClick={() => setIsEditingName(true)}
162
+ contentEditable={false}
163
+ className="p-1.5 rounded-md transition-all duration-200 hover:bg-white/10 text-zinc-400 hover:text-white"
164
+ title="Editar nombre"
165
+ >
166
+ <Pencil size={14} />
167
+ </button>
168
+ )}
169
+ <button
170
+ onClick={handleDownload}
171
+ contentEditable={false}
172
+ className="p-1.5 rounded-md transition-all duration-200 hover:bg-white/10 text-zinc-400 hover:text-white"
173
+ title="Descargar archivo"
174
+ >
175
+ <Download size={14} />
176
+ </button>
177
+ <div className="relative">
178
+ <button
179
+ onClick={handleCopy}
180
+ contentEditable={false}
181
+ className={`p-1.5 rounded-md transition-all duration-200 ${copied
182
+ ? 'bg-green-500/20 text-green-400 scale-110'
183
+ : 'hover:bg-white/10 text-zinc-400 hover:text-white'
184
+ }`}
185
+ title="Copiar código"
186
+ >
187
+ {copied ? <Check size={14} strokeWidth={3} /> : <Copy size={14} />}
188
+ </button>
189
+ {copied && (
190
+ <div className="absolute bottom-full right-0 mb-2 px-2 py-1 bg-[#252525] border border-white/10 text-green-400 text-[10px] font-medium rounded shadow-xl animate-in fade-in slide-in-from-bottom-1 whitespace-nowrap z-50">
191
+ Copiado!
192
+ </div>
193
+ )}
194
+ </div>
195
+ </div>
196
+ </div>
197
+ <div
198
+ ref={contentRef}
199
+ style={{
200
+ maxHeight: props.node.attrs.collapsible
201
+ ? (isCollapsed ? '300px' : `${contentHeight}${typeof contentHeight === 'number' ? 'px' : ''}`)
202
+ : 'none',
203
+ overflow: 'hidden',
204
+ transition: 'max-height 0.5s cubic-bezier(0.4, 0, 0.2, 1)',
205
+ position: 'relative',
206
+ maskImage: isCollapsed ? 'linear-gradient(to bottom, black 60%, transparent 100%)' : 'none',
207
+ WebkitMaskImage: isCollapsed ? 'linear-gradient(to bottom, black 60%, transparent 100%)' : 'none',
208
+ display: 'flex',
209
+ alignItems: 'stretch'
210
+ }}
211
+ >
212
+ {showLineNumbers && !wrapText && (
213
+ <div
214
+ className="flex-none p-5 text-right select-none bg-[#1a1a1a] border-r border-white/5 text-zinc-600 font-mono text-sm leading-relaxed"
215
+ style={{ minWidth: '3rem' }}
216
+ contentEditable={false}
217
+ >
218
+ {Array.from({ length: lineCount }).map((_, i) => (
219
+ <div key={i}>{i + 1}</div>
220
+ ))}
221
+ </div>
222
+ )}
223
+ <pre className={`flex-1 !m-0 !p-5 !bg-[#151515] ${wrapText ? 'whitespace-pre-wrap word-break-all' : 'overflow-x-auto'}`}>
224
+ <NodeViewContent as="code" className="font-mono text-sm text-zinc-300 leading-relaxed block" />
225
+ </pre>
226
+ </div>
227
+
228
+ {props.node.attrs.collapsible && (
229
+ <div className="absolute bottom-2 right-2 z-10">
230
+ <button
231
+ onClick={(e) => {
232
+ e.stopPropagation();
233
+ toggleExpand();
234
+ }}
235
+ contentEditable={false}
236
+ className="text-zinc-400 hover:text-white transition-colors cursor-pointer select-none p-1 bg-[#151515]/80 rounded-full backdrop-blur-sm border border-white/5"
237
+ title={isManualExpanded ? "Contraer" : "Expandir"}
238
+ >
239
+ {isManualExpanded ? (
240
+ <ChevronUp size={16} />
241
+ ) : (
242
+ <ChevronDown size={16} />
243
+ )}
244
+ </button>
245
+ </div>
246
+ )}
247
+ </NodeViewWrapper>
248
+ );
249
+ };
components/ConfirmDialog.tsx ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React from 'react';
2
+ import { AlertTriangle, X } from 'lucide-react';
3
+
4
+ interface ConfirmDialogProps {
5
+ isOpen: boolean;
6
+ onClose: () => void;
7
+ onConfirm: () => void;
8
+ title: string;
9
+ message: string;
10
+ confirmText?: string;
11
+ cancelText?: string;
12
+ variant?: 'danger' | 'warning' | 'info';
13
+ }
14
+
15
+ export const ConfirmDialog: React.FC<ConfirmDialogProps> = ({
16
+ isOpen,
17
+ onClose,
18
+ onConfirm,
19
+ title,
20
+ message,
21
+ confirmText = 'Confirmar',
22
+ cancelText = 'Cancelar',
23
+ variant = 'danger'
24
+ }) => {
25
+ if (!isOpen) return null;
26
+
27
+ return (
28
+ <div className="fixed inset-0 z-[100] flex items-center justify-center bg-black/60 backdrop-blur-sm animate-fade-in">
29
+ <div className="bg-[#1a1a1a] border border-white/10 rounded-xl shadow-2xl w-[400px] max-w-[90vw] overflow-hidden animate-in zoom-in-95 duration-200">
30
+ <div className="p-6">
31
+ <div className="flex items-start gap-4">
32
+ <div className={`p-3 rounded-full ${variant === 'danger' ? 'bg-red-500/10 text-red-500' : 'bg-yellow-500/10 text-yellow-500'}`}>
33
+ <AlertTriangle size={24} />
34
+ </div>
35
+ <div className="flex-1">
36
+ <h3 className="text-lg font-bold text-white mb-2">{title}</h3>
37
+ <p className="text-gray-400 text-sm leading-relaxed">{message}</p>
38
+ </div>
39
+ </div>
40
+ </div>
41
+
42
+ <div className="bg-white/5 px-6 py-4 flex justify-end gap-3 border-t border-white/5">
43
+ <button
44
+ onClick={onClose}
45
+ className="px-4 py-2 rounded-lg text-sm font-medium text-gray-400 hover:text-white hover:bg-white/5 transition-colors"
46
+ >
47
+ {cancelText}
48
+ </button>
49
+ <button
50
+ onClick={() => {
51
+ onConfirm();
52
+ onClose();
53
+ }}
54
+ className={`px-4 py-2 rounded-lg text-sm font-medium text-white transition-colors shadow-lg ${variant === 'danger'
55
+ ? 'bg-red-500 hover:bg-red-600 shadow-red-500/20'
56
+ : 'bg-yellow-500 hover:bg-yellow-600 shadow-yellow-500/20'
57
+ }`}
58
+ >
59
+ {confirmText}
60
+ </button>
61
+ </div>
62
+ </div>
63
+ </div>
64
+ );
65
+ };
components/CopyButton.tsx ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useState } from 'react';
2
+ import { Copy, Check } from 'lucide-react';
3
+
4
+ export const CopyButton = ({ text, className = '' }: { text: string, className?: string }) => {
5
+ const [copied, setCopied] = useState(false);
6
+
7
+ const handleCopy = () => {
8
+ navigator.clipboard.writeText(text);
9
+ setCopied(true);
10
+ setTimeout(() => setCopied(false), 2000);
11
+ };
12
+
13
+ return (
14
+ <button
15
+ onClick={handleCopy}
16
+ className={`p-1.5 bg-[#2d2d2d] border border-white/10 rounded-md text-gray-400 hover:text-white hover:bg-primary/20 transition-all z-10 ${className}`}
17
+ title="Copiar código"
18
+ >
19
+ {copied ? <Check size={14} /> : <Copy size={14} />}
20
+ </button>
21
+ );
22
+ };
components/CustomBlockquote.tsx ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React from 'react';
2
+ import { CopyButton } from './CopyButton';
3
+ import { DownloadButton } from './DownloadButton';
4
+
5
+ interface CustomBlockquoteProps extends React.HTMLAttributes<HTMLQuoteElement> {
6
+ isEditable?: boolean;
7
+ 'data-show-copy'?: string | boolean;
8
+ 'data-show-download'?: string | boolean;
9
+ }
10
+
11
+ export const CustomBlockquote: React.FC<CustomBlockquoteProps> = ({
12
+ children,
13
+ style,
14
+ className = '',
15
+ isEditable,
16
+ 'data-show-copy': showCopyData,
17
+ 'data-show-download': showDownloadData,
18
+ ...props
19
+ }) => {
20
+ // Extract text content for copy button
21
+ const getTextContent = (node: React.ReactNode): string => {
22
+ if (typeof node === 'string') return node;
23
+ if (Array.isArray(node)) return node.map(getTextContent).join('');
24
+ if (React.isValidElement(node)) return getTextContent((node as React.ReactElement<any>).props.children);
25
+ return '';
26
+ };
27
+
28
+ const quoteText = getTextContent(children);
29
+ const showCopyButton = showCopyData === 'true' || showCopyData === true;
30
+ const showDownloadButton = showDownloadData === 'true' || showDownloadData === true;
31
+
32
+ // Ensure we have default styles if not provided, but respect overrides
33
+ const computedStyle: React.CSSProperties = {
34
+ position: 'relative',
35
+ marginBottom: '1rem',
36
+ display: 'flex',
37
+ flexDirection: 'column',
38
+ justifyContent: 'center',
39
+ overflow: 'visible',
40
+ maxWidth: '100%',
41
+ boxSizing: 'border-box',
42
+ ...style, // Allow style prop to override defaults
43
+ };
44
+
45
+ // Handle width specifically to ensure it doesn't break layout
46
+ if (computedStyle.width === 'auto' || !computedStyle.width) {
47
+ computedStyle.width = '100%';
48
+ }
49
+
50
+ return (
51
+ <div className="relative group w-full max-w-full">
52
+ <blockquote
53
+ className={`transition-all duration-200 ease-in-out ${className}`}
54
+ style={computedStyle}
55
+ {...props}
56
+ >
57
+ {children}
58
+ </blockquote>
59
+
60
+ <div className="absolute right-2 top-2 flex gap-2 transition-opacity duration-200 opacity-0 group-hover:opacity-100 z-10">
61
+ {showCopyButton && (
62
+ <CopyButton
63
+ text={quoteText}
64
+ className=""
65
+ />
66
+ )}
67
+ {showDownloadButton && (
68
+ <DownloadButton
69
+ text={quoteText}
70
+ className=""
71
+ />
72
+ )}
73
+ </div>
74
+ </div>
75
+ );
76
+ };
components/CustomButtonComponent.tsx ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useEffect, useState } from 'react';
2
+ import { NodeViewWrapper, NodeViewProps } from '@tiptap/react';
3
+ import { ExternalLink, Download, Github, Send, Twitter, Linkedin, Instagram, Youtube, Facebook, X, Code, Layers, MessageCircle, Globe, Mail, FileText } from 'lucide-react';
4
+ import { TiktokIcon } from './TiktokIcon';
5
+ import { subscribeToStyleConfig, StyleConfig, DEFAULT_STYLE_CONFIG } from '../services/codeStyleService';
6
+
7
+ export const CustomButtonComponent: React.FC<NodeViewProps> = ({ node, getPos, editor }) => {
8
+ const { text, url, variant, backgroundColor, textColor, borderRadius, width, height } = node.attrs;
9
+ // We no longer subscribe to live styleConfig updates to ensure existing buttons don't change
10
+ // when the user adjusts the settings panel. Settings only affect NEW buttons.
11
+ // Falls back to defaults if attributes are missing (legacy buttons).
12
+ const fallbackConfig = DEFAULT_STYLE_CONFIG;
13
+
14
+ const handleClick = (e: React.MouseEvent) => {
15
+ if (editor.isEditable) {
16
+ e.preventDefault();
17
+ }
18
+ // In read-only mode, the <a> tag handles navigation naturally
19
+ };
20
+
21
+ // Use node attributes if available (frozen style), otherwise fallback to DEFAULT config (not live config)
22
+ const activeStyle = {
23
+ width: width || (fallbackConfig.button.width === 'auto' ? 'auto' : fallbackConfig.button.width),
24
+ height: height || (fallbackConfig.button.height === 'auto' ? 'auto' : fallbackConfig.button.height),
25
+ backgroundColor: backgroundColor || fallbackConfig.button.backgroundColor,
26
+ textColor: textColor || fallbackConfig.button.textColor,
27
+ borderRadius: borderRadius || fallbackConfig.button.borderRadius,
28
+ };
29
+
30
+ const buttonStyle = {
31
+ width: activeStyle.width,
32
+ height: activeStyle.height,
33
+ maxWidth: '100%', // Prevent overflow
34
+ backgroundColor: 'transparent',
35
+ color: activeStyle.backgroundColor, // Icon/Text color matches background config? Wait, usually button has background color.
36
+ // The original code used 'color: styleConfig.button.backgroundColor' and 'border: 1px solid ...'.
37
+ // It seems the "backgroundColor" config actually controls the FOREGROUND color (text/icon) and border?
38
+ // Let's verify existing behavior.
39
+ // Original: color: styleConfig.button.backgroundColor, border: 1px solid ...
40
+ // So yes, "backgroundColor" in config is used as the primary color.
41
+
42
+ borderRadius: activeStyle.borderRadius,
43
+ border: `1px solid ${activeStyle.backgroundColor}`,
44
+ boxShadow: `0 0 10px ${activeStyle.backgroundColor}40`, // Glow effect
45
+ };
46
+
47
+ return (
48
+ <NodeViewWrapper className="inline-block mx-1 align-middle" style={{ maxWidth: '100%' }}> {/* Reverted to inline-block to allow typing next to it */}
49
+ <a
50
+ href={url}
51
+ target="_blank"
52
+ rel="noopener noreferrer"
53
+ onClick={handleClick}
54
+ style={buttonStyle}
55
+ className={`
56
+ inline-flex items-center justify-center gap-2 px-4 py-2 border transition-all duration-200 no-underline
57
+ ${editor.isEditable ? 'cursor-default' : 'cursor-pointer'}
58
+ hover:opacity-90
59
+ `}
60
+ >
61
+ {variant === 'visit' ? (
62
+ <ExternalLink size={16} style={{ color: activeStyle.backgroundColor }} />
63
+ ) : variant === 'download' ? (
64
+ <Download size={16} style={{ color: activeStyle.backgroundColor }} />
65
+ ) : variant === 'github' ? (
66
+ <Github size={16} style={{ color: activeStyle.backgroundColor }} />
67
+ ) : variant === 'telegram' ? (
68
+ <Send size={16} style={{ color: activeStyle.backgroundColor }} />
69
+ ) : variant === 'twitter' ? (
70
+ <Twitter size={16} style={{ color: activeStyle.backgroundColor }} />
71
+ ) : variant === 'linkedin' ? (
72
+ <Linkedin size={16} style={{ color: activeStyle.backgroundColor }} />
73
+ ) : variant === 'instagram' ? (
74
+ <Instagram size={16} style={{ color: activeStyle.backgroundColor }} />
75
+ ) : variant === 'youtube' ? (
76
+ <Youtube size={16} style={{ color: activeStyle.backgroundColor }} />
77
+ ) : variant === 'facebook' ? (
78
+ <Facebook size={16} style={{ color: activeStyle.backgroundColor }} />
79
+ ) : variant === 'tiktok' ? (
80
+ <TiktokIcon size={16} style={{ color: activeStyle.backgroundColor }} />
81
+ ) : variant === 'x' ? (
82
+ <X size={16} style={{ color: activeStyle.backgroundColor }} />
83
+ ) : variant === 'code' ? (
84
+ <Code size={16} style={{ color: activeStyle.backgroundColor }} />
85
+ ) : variant === 'layers' ? (
86
+ <Layers size={16} style={{ color: activeStyle.backgroundColor }} />
87
+ ) : variant === 'community' ? (
88
+ <MessageCircle size={16} style={{ color: activeStyle.backgroundColor }} />
89
+ ) : variant === 'globe' ? (
90
+ <Globe size={16} style={{ color: activeStyle.backgroundColor }} />
91
+ ) : variant === 'mail' ? (
92
+ <Mail size={16} style={{ color: activeStyle.backgroundColor }} />
93
+ ) : variant === 'file' ? (
94
+ <FileText size={16} style={{ color: activeStyle.backgroundColor }} />
95
+ ) : (
96
+ <ExternalLink size={16} style={{ color: activeStyle.backgroundColor }} />
97
+ )}
98
+ <span className="font-medium text-sm" style={{ color: activeStyle.textColor }}>{text}</span>
99
+ </a>
100
+ </NodeViewWrapper>
101
+ );
102
+ };
components/DataForm.tsx ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useState } from 'react';
2
+ import { DataItem } from '../types';
3
+ import { Button } from './Button';
4
+ import { IconPicker } from './IconPicker';
5
+ import { Save, X, Link as LinkIcon, Download, Hash, Sparkles, Loader2 } from 'lucide-react';
6
+ import { expandSummary } from '../services/aiService';
7
+
8
+ interface DataFormProps {
9
+ initialData?: DataItem | null;
10
+ onSave: (data: Omit<DataItem, 'id' | 'createdAt'>) => void;
11
+ onCancel: () => void;
12
+ }
13
+
14
+ export const DataForm: React.FC<DataFormProps> = ({ initialData, onSave, onCancel }) => {
15
+ const [title, setTitle] = useState(initialData?.title || '');
16
+ const [icon, setIcon] = useState(initialData?.icon || '');
17
+ const [summary, setSummary] = useState(initialData?.summary || '');
18
+ const [downloadUrl, setDownloadUrl] = useState(initialData?.downloadUrl || '');
19
+ const [visitUrl, setVisitUrl] = useState(initialData?.visitUrl || '');
20
+ const [tagsString, setTagsString] = useState(initialData?.tags.join(', ') || '');
21
+ const [isExpanding, setIsExpanding] = useState(false);
22
+
23
+ const handleSubmit = (e: React.FormEvent) => {
24
+ e.preventDefault();
25
+
26
+ // We only save the metadata here. Blocks are managed independently in DetailView.
27
+ onSave({
28
+ icon: icon || undefined,
29
+ title,
30
+ content: "", // Legacy
31
+ summary,
32
+ downloadUrl: downloadUrl || undefined,
33
+ visitUrl: visitUrl || undefined,
34
+ tags: tagsString.split(',').map(t => t.trim()).filter(Boolean),
35
+ });
36
+ };
37
+
38
+ return (
39
+ <div className="max-w-4xl mx-auto animate-fade-in pb-20">
40
+ <div className="flex items-center justify-between mb-8">
41
+ <h2 className="text-2xl font-bold text-white">
42
+ {initialData ? 'Editar Entrada' : 'Crear Nueva Entrada'}
43
+ </h2>
44
+ <Button variant="ghost" onClick={onCancel} className="text-gray-500 hover:text-white">
45
+ <X size={24} />
46
+ </Button>
47
+ </div>
48
+
49
+ <form onSubmit={handleSubmit} className="space-y-8">
50
+
51
+ {/* MAIN INFO CARD */}
52
+ <div className="bg-surface p-8 rounded-2xl border border-white/5 shadow-xl space-y-6">
53
+ <div>
54
+ <label className="block text-sm font-medium text-gray-400 mb-2">Título</label>
55
+ <div className="flex gap-4 items-start">
56
+ <IconPicker
57
+ selectedIcon={icon}
58
+ onSelect={setIcon}
59
+ />
60
+ <input
61
+ required
62
+ type="text"
63
+ className="w-full bg-background border border-white/10 rounded-lg p-4 text-white text-lg focus:border-primary focus:ring-1 focus:ring-primary outline-none transition-colors"
64
+ value={title}
65
+ onChange={(e) => setTitle(e.target.value)}
66
+ placeholder="Ej: Apuntes de React..."
67
+ />
68
+ </div>
69
+ </div>
70
+
71
+ <div>
72
+ <div className="flex justify-between items-center mb-2">
73
+ <label className="block text-sm font-medium text-gray-400">Resumen / Descripción Principal</label>
74
+ <button
75
+ type="button"
76
+ onClick={async () => {
77
+ if (!summary) return;
78
+ setIsExpanding(true);
79
+ try {
80
+ const expanded = await expandSummary(summary);
81
+ setSummary(expanded);
82
+ } catch (e: any) {
83
+ alert(e.message || "Error al mejorar el resumen.");
84
+ } finally {
85
+ setIsExpanding(false);
86
+ }
87
+ }}
88
+ className="text-xs text-primary hover:text-primary/80 transition-colors flex items-center gap-1 bg-primary/10 px-3 py-1 rounded-lg border border-primary/20"
89
+ title="Mejorar y expandir resumen con IA"
90
+ disabled={!summary || isExpanding}
91
+ >
92
+ {isExpanding ? <Loader2 size={12} className="animate-spin" /> : <Sparkles size={12} />}
93
+ {isExpanding ? 'Mejorando...' : 'Mejorar con IA'}
94
+ </button>
95
+ </div>
96
+ <textarea
97
+ required
98
+ rows={4}
99
+ className="w-full bg-background border border-white/10 rounded-lg p-4 text-white focus:border-primary focus:ring-1 focus:ring-primary outline-none transition-colors resize-y"
100
+ value={summary}
101
+ onChange={(e) => setSummary(e.target.value)}
102
+ placeholder="Descripción principal de la tarjeta..."
103
+ />
104
+ </div>
105
+
106
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-6 p-6 bg-background/30 rounded-xl border border-white/5">
107
+ <div>
108
+ <label className="flex items-center gap-2 text-sm font-medium text-primary mb-2">
109
+ <Download size={16} /> Enlace de Descarga
110
+ </label>
111
+ <input
112
+ type="url"
113
+ className="w-full bg-surface border border-white/10 rounded-lg p-3 text-white focus:border-primary outline-none text-sm placeholder-gray-600"
114
+ value={downloadUrl}
115
+ onChange={(e) => setDownloadUrl(e.target.value)}
116
+ placeholder="https://drive.google.com/..."
117
+ />
118
+ </div>
119
+ <div>
120
+ <label className="flex items-center gap-2 text-sm font-medium text-primary mb-2">
121
+ <LinkIcon size={16} /> Enlace de Visita
122
+ </label>
123
+ <input
124
+ type="url"
125
+ className="w-full bg-surface border border-white/10 rounded-lg p-3 text-white focus:border-primary outline-none text-sm placeholder-gray-600"
126
+ value={visitUrl}
127
+ onChange={(e) => setVisitUrl(e.target.value)}
128
+ placeholder="https://mi-sitio-web.com"
129
+ />
130
+ </div>
131
+ </div>
132
+
133
+ <div>
134
+ <div>
135
+ <label className="block text-sm font-medium text-gray-400 mb-2">Etiquetas</label>
136
+ </div>
137
+ <div className="relative">
138
+ <Hash size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500" />
139
+ <input
140
+ type="text"
141
+ className="w-full bg-background border border-white/10 rounded-lg p-3 pl-10 text-white focus:border-primary outline-none"
142
+ value={tagsString}
143
+ onChange={(e) => setTagsString(e.target.value)}
144
+ placeholder="etiqueta1, etiqueta2..."
145
+ />
146
+ </div>
147
+ <div className="flex justify-end mt-2">
148
+ <button
149
+ type="button"
150
+ onClick={() => {
151
+ const stopWords = new Set([
152
+ 'el', 'la', 'los', 'las', 'un', 'una', 'unos', 'unas', 'y', 'o', 'pero', 'si', 'no',
153
+ 'de', 'del', 'a', 'al', 'en', 'con', 'por', 'para', 'sin', 'sobre', 'entre',
154
+ 'mi', 'tu', 'su', 'nuestro', 'vuestro', 'sus', 'mis', 'tus',
155
+ 'que', 'cual', 'quien', 'donde', 'cuando', 'como', 'porque',
156
+ 'es', 'son', 'fue', 'fueron', 'era', 'eran', 'está', 'están',
157
+ 'este', 'esta', 'ese', 'esa', 'aquel', 'aquella', 'esto', 'eso', 'aquello',
158
+ 'hizo', 'hacer', 'todo', 'toda', 'todos', 'todas', 'muy', 'más', 'tan',
159
+ 'ya', 'hoy', 'ayer', 'ahora', 'después', 'antes', 'mira', 'voy'
160
+ ]);
161
+
162
+ const text = `${title} ${summary}`.toLowerCase();
163
+ // RegEx to remove special chars, keep accents/letters/numbers
164
+ const words = text.replace(/[^\w\sáéíóúñü]/g, '').split(/\s+/);
165
+
166
+ const uniqueKeywords = new Set<string>();
167
+
168
+ words.forEach(word => {
169
+ if (word.length > 2 && !stopWords.has(word)) {
170
+ uniqueKeywords.add(word);
171
+ }
172
+ });
173
+
174
+ // Limit to 15 tags
175
+ const keywordsArray = Array.from(uniqueKeywords).slice(0, 15);
176
+ setTagsString(keywordsArray.join(', '));
177
+ }}
178
+ className="text-xs text-primary hover:text-primary/80 transition-colors flex items-center gap-1 bg-primary/10 px-3 py-1.5 rounded-lg border border-primary/20"
179
+ title="Extraer palabras clave automáticamente"
180
+ disabled={!title && !summary}
181
+ >
182
+ <Sparkles size={14} /> Generar Automáticamente
183
+ </button>
184
+ </div>
185
+ </div>
186
+ </div>
187
+
188
+ {/* ACTION BUTTONS */}
189
+ <div className="flex gap-4 pt-6 border-t border-white/5 sticky bottom-0 bg-[#121212] py-6 z-10">
190
+ <Button type="button" variant="ghost" onClick={onCancel} className="flex-1">
191
+ Cancelar
192
+ </Button>
193
+ <Button type="submit" className="flex-1 py-3 text-lg shadow-[0_0_20px_rgba(187,134,252,0.2)]">
194
+ <Save size={20} /> Guardar Cambios
195
+ </Button>
196
+ </div>
197
+ </form>
198
+ </div>
199
+ );
200
+ };
components/DetailView.tsx ADDED
@@ -0,0 +1,703 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useState, useRef, useEffect } from 'react';
2
+ import { DataItem, ContentBlock } from '../types';
3
+ import { Button } from './Button';
4
+ import { TipTapEditor } from './TipTapEditor';
5
+ import { BlockEditorModal } from './BlockEditorModal';
6
+ import { IconPicker } from './IconPicker';
7
+ import { ArrowLeft, Download, ExternalLink, Trash2, Edit2, Plus, Save, X, Check, Sparkles } from 'lucide-react';
8
+ import { ConfirmDialog } from './ConfirmDialog';
9
+ import { Editor } from '@tiptap/react';
10
+ import { expandSummary, generateFromInstructions } from '../services/aiService';
11
+ import { AIInstructionModal } from './AIInstructionModal';
12
+
13
+ interface DetailViewProps {
14
+ item: DataItem;
15
+ onBack: () => void;
16
+ onUpdate: (data: Omit<DataItem, 'id' | 'createdAt'>) => void;
17
+ onDelete: (id: string) => void;
18
+ isEditable?: boolean;
19
+ }
20
+
21
+ export const DetailView: React.FC<DetailViewProps> = ({ item, onBack, onUpdate, onDelete, isEditable = false }) => {
22
+ const [isEditMode, setIsEditMode] = useState(false);
23
+ const [editedItem, setEditedItem] = useState<DataItem>(item);
24
+ const [editingBlockId, setEditingBlockId] = useState<string | null>(null);
25
+
26
+
27
+
28
+ const [showEditTab, setShowEditTab] = useState(true);
29
+ const [blockEditor, setBlockEditor] = useState<{
30
+ isOpen: boolean;
31
+ type: 'quote' | 'code';
32
+ }>({
33
+ isOpen: false,
34
+ type: 'quote'
35
+ });
36
+
37
+ const activeEditorRef = useRef<Editor | null>(null);
38
+ const summaryEditorRef = useRef<Editor | null>(null);
39
+ const summaryTextareaRef = useRef<HTMLTextAreaElement>(null);
40
+ const [pendingModalOpen, setPendingModalOpen] = useState(false);
41
+
42
+ const getCardClasses = (style?: 'bordered' | 'transparent' | 'filled') => {
43
+ switch (style) {
44
+ case 'filled':
45
+ return 'bg-surface border border-white/5 shadow-xl';
46
+ case 'transparent':
47
+ return 'bg-transparent border-none shadow-none';
48
+ case 'bordered':
49
+ default:
50
+ return 'bg-transparent border border-white/10 shadow-none'; // Default to "bordered" as per latest "transparent" refined look
51
+ }
52
+ };
53
+
54
+ const [confirmDialog, setConfirmDialog] = useState<{
55
+ isOpen: boolean;
56
+ title: string;
57
+ message: string;
58
+ onConfirm: () => void;
59
+ }>({
60
+ isOpen: false,
61
+ title: '',
62
+ message: '',
63
+ onConfirm: () => { }
64
+ });
65
+
66
+ // AI Modal State
67
+ const [aiModal, setAiModal] = useState<{
68
+ isOpen: boolean;
69
+ currentContent: string;
70
+ onGenerate: (content: string) => Promise<void>;
71
+ }>({
72
+ isOpen: false,
73
+ currentContent: '',
74
+ onGenerate: async () => { }
75
+ });
76
+
77
+ // Auto-resize summary textarea
78
+ useEffect(() => {
79
+ if (summaryTextareaRef.current) {
80
+ summaryTextareaRef.current.style.height = 'auto';
81
+ summaryTextareaRef.current.style.height = summaryTextareaRef.current.scrollHeight + 'px';
82
+ }
83
+ }, [editedItem.summary, showEditTab, isEditMode]);
84
+
85
+ // Effect to open modal once editor is ready if pending
86
+ useEffect(() => {
87
+ if (pendingModalOpen && activeEditorRef.current && editingBlockId) {
88
+ setBlockEditor(prev => ({ ...prev, isOpen: true }));
89
+ setPendingModalOpen(false);
90
+ }
91
+ }, [pendingModalOpen, editingBlockId, activeEditorRef.current]);
92
+
93
+ const handleSaveChanges = () => {
94
+ onUpdate({
95
+ icon: editedItem.icon,
96
+ title: editedItem.title,
97
+ summary: editedItem.summary,
98
+ content: editedItem.content || '',
99
+ tags: editedItem.tags,
100
+ blocks: editedItem.blocks,
101
+ visitUrl: editedItem.visitUrl,
102
+ downloadUrl: editedItem.downloadUrl,
103
+ cardStyle: editedItem.cardStyle
104
+ });
105
+ setIsEditMode(false);
106
+ };
107
+
108
+ const handleCancelEdit = () => {
109
+ setEditedItem(item);
110
+ setIsEditMode(false);
111
+ setEditingBlockId(null);
112
+ setEditingBlockId(null);
113
+ };
114
+
115
+ const handleAddBlockImmediately = () => {
116
+ const newBlock: ContentBlock = {
117
+ id: Date.now().toString(),
118
+ type: 'markdown',
119
+ content: {
120
+ type: 'doc',
121
+ content: [
122
+ {
123
+ type: 'paragraph',
124
+ }
125
+ ]
126
+ }
127
+ };
128
+
129
+ setEditedItem(prev => ({
130
+ ...prev,
131
+ blocks: [...(prev.blocks || []), newBlock]
132
+ }));
133
+
134
+ setEditingBlockId(newBlock.id);
135
+ };
136
+
137
+ const handleBlockUpdate = (blockId: string, content: any) => {
138
+ setEditedItem(prev => ({
139
+ ...prev,
140
+ blocks: prev.blocks?.map(b => b.id === blockId ? { ...b, content } : b) || []
141
+ }));
142
+ };
143
+
144
+ const handleDeleteBlock = (blockId: string) => {
145
+ setConfirmDialog({
146
+ isOpen: true,
147
+ title: 'Eliminar Bloque',
148
+ message: '¿Estás seguro de que quieres eliminar este bloque de contenido? Esta acción no se puede deshacer.',
149
+ onConfirm: () => {
150
+ setEditedItem(prev => ({
151
+ ...prev,
152
+ blocks: prev.blocks?.filter(b => b.id !== blockId) || []
153
+ }));
154
+ }
155
+ });
156
+ };
157
+
158
+ const handleBlockDoubleClick = (type: 'code' | 'quote', index: number, blockId: string) => {
159
+ // Switch to edit mode for this block
160
+ const block = editedItem.blocks?.find(b => b.id === blockId);
161
+ if (block) {
162
+ setEditingBlockId(blockId);
163
+ setBlockEditor({ isOpen: false, type }); // Will open in effect
164
+ setPendingModalOpen(true);
165
+ }
166
+ };
167
+
168
+ if (isEditMode) {
169
+ return (
170
+ <div className="max-w-5xl mx-auto animate-fade-in pb-20">
171
+ <div className="flex items-center justify-between mb-6">
172
+ <button
173
+ onClick={handleCancelEdit}
174
+ className="flex items-center gap-2 text-gray-400 hover:text-primary transition-colors text-sm font-medium"
175
+ >
176
+ <ArrowLeft size={18} /> Cancelar
177
+ </button>
178
+ <Button onClick={handleSaveChanges}>
179
+ <Save size={18} /> Guardar Cambios
180
+ </Button>
181
+ </div>
182
+
183
+
184
+
185
+ <div className="flex gap-2 mb-6">
186
+ <button
187
+ onClick={() => setShowEditTab(true)}
188
+ className={`px-4 py-2 rounded-lg font-medium transition-colors ${showEditTab
189
+ ? 'bg-primary text-background'
190
+ : 'bg-white/5 text-gray-400 hover:text-white border border-white/10'
191
+ }`}
192
+ >
193
+ Edit
194
+ </button>
195
+ <button
196
+ onClick={() => setShowEditTab(false)}
197
+ className={`px-4 py-2 rounded-lg font-medium transition-colors ${!showEditTab
198
+ ? 'bg-primary text-background'
199
+ : 'bg-white/5 text-gray-400 hover:text-white border border-white/10'
200
+ }`}
201
+ >
202
+ Preview
203
+ </button>
204
+ </div>
205
+
206
+ <div className="bg-surface rounded-2xl p-6 border border-white/5 shadow-xl space-y-6" style={{ display: showEditTab ? 'block' : 'none' }}>
207
+ <div>
208
+ <label className="block text-sm font-medium text-gray-400 mb-2">Título</label>
209
+ <div className="flex gap-4 items-start">
210
+ <IconPicker
211
+ selectedIcon={editedItem.icon}
212
+ onSelect={(icon) => setEditedItem(prev => ({ ...prev, icon }))}
213
+ />
214
+ <div className="flex-grow bg-background border border-white/10 rounded-lg overflow-hidden focus-within:border-primary focus-within:ring-1 focus-within:ring-primary transition-colors">
215
+ <TipTapEditor
216
+ content={editedItem.title}
217
+ onUpdate={(content) => setEditedItem(prev => ({ ...prev, title: content }))}
218
+ isEditable={true}
219
+ showToolbarOnFocus={true}
220
+ className="px-3 py-2 min-h-[46px]"
221
+ dense={true}
222
+ />
223
+ </div>
224
+ </div>
225
+ </div>
226
+
227
+ <div>
228
+ <div className="flex justify-between items-center mb-2">
229
+ <label className="block text-sm font-medium text-gray-400">Resumen</label>
230
+ <button
231
+ type="button"
232
+ onClick={() => {
233
+ const editor = summaryEditorRef.current;
234
+ if (!editor) return;
235
+
236
+ const { selection, doc } = editor.state;
237
+ const hasSelection = !selection.empty;
238
+ const wholeText = editor.getText();
239
+ const isDocEmpty = wholeText.trim().length === 0;
240
+
241
+ // MODE 1: Edit Selection
242
+ if (hasSelection) {
243
+ const selectedText = editor.state.doc.textBetween(selection.from, selection.to);
244
+ setAiModal({
245
+ isOpen: true,
246
+ currentContent: selectedText, // Pass selected text to be "improved"
247
+ onGenerate: async (instructions) => {
248
+ const result = await generateFromInstructions(selectedText, instructions, wholeText);
249
+ // Replace only the selection
250
+ editor.chain().focus().deleteSelection().insertContent(result).run();
251
+ // Update local state to match editor content
252
+ setEditedItem(prev => ({ ...prev, summary: editor.getHTML() }));
253
+ }
254
+ });
255
+ return;
256
+ }
257
+
258
+ // MODE 2: Append to existing text
259
+ if (!isDocEmpty) {
260
+ setAiModal({
261
+ isOpen: true,
262
+ currentContent: '', // Empty triggers "Creation" prompts in Modal
263
+ onGenerate: async (instructions) => {
264
+ // Pass whole text as context, but empty content to generate NEW text
265
+ const result = await generateFromInstructions('', instructions, wholeText);
266
+ // Append to the end
267
+ editor.chain().focus().insertContentAt(doc.content.size, result).run();
268
+ setEditedItem(prev => ({ ...prev, summary: editor.getHTML() }));
269
+ }
270
+ });
271
+ return;
272
+ }
273
+
274
+ // MODE 3: Create from scratch (Empty doc)
275
+ setAiModal({
276
+ isOpen: true,
277
+ currentContent: '',
278
+ onGenerate: async (instructions) => {
279
+ const result = await generateFromInstructions('', instructions);
280
+ editor.commands.setContent(result);
281
+ setEditedItem(prev => ({ ...prev, summary: result }));
282
+ }
283
+ });
284
+ }}
285
+ className="text-xs text-primary hover:text-primary/80 transition-colors flex items-center gap-1 bg-primary/10 px-3 py-1 rounded-lg border border-primary/20"
286
+ title="Mejorar con IA"
287
+ >
288
+ <Sparkles size={14} /> Mejorar con IA
289
+ </button>
290
+ </div>
291
+ <div className="bg-background border border-white/10 rounded-lg overflow-hidden focus-within:border-primary focus-within:ring-1 focus-within:ring-primary transition-colors">
292
+ <TipTapEditor
293
+ content={editedItem.summary}
294
+ onUpdate={(content) => {
295
+ // Only update state if it comes from internal changes that usually sync automaticallly,
296
+ // but here we just keep the simple binding.
297
+ setEditedItem(prev => ({ ...prev, summary: content }));
298
+ }}
299
+ isEditable={true}
300
+ editorRef={summaryEditorRef}
301
+ showToolbarOnFocus={true}
302
+ className="px-3 py-2 min-h-[40px]"
303
+ dense={true}
304
+ />
305
+ </div>
306
+ </div>
307
+
308
+ <div>
309
+ <label className="block text-sm font-medium text-gray-400 mb-2">Tags</label>
310
+ <input
311
+ type="text"
312
+ value={editedItem.tags.join(', ')}
313
+ onChange={(e) => setEditedItem(prev => ({ ...prev, tags: e.target.value.split(',').map(t => t.trim()).filter(Boolean) }))}
314
+ className="w-full bg-background border border-white/10 rounded-lg p-3 text-white focus:border-primary focus:ring-1 focus:ring-primary outline-none transition-colors"
315
+ placeholder="tag1, tag2, tag3"
316
+ />
317
+ <div className="flex justify-end mt-2">
318
+ <button
319
+ type="button"
320
+ onClick={() => {
321
+ const stopWords = new Set([
322
+ 'el', 'la', 'los', 'las', 'un', 'una', 'unos', 'unas', 'y', 'o', 'pero', 'si', 'no',
323
+ 'de', 'del', 'a', 'al', 'en', 'con', 'por', 'para', 'sin', 'sobre', 'entre',
324
+ 'mi', 'tu', 'su', 'nuestro', 'vuestro', 'sus', 'mis', 'tus',
325
+ 'que', 'cual', 'quien', 'donde', 'cuando', 'como', 'porque',
326
+ 'es', 'son', 'fue', 'fueron', 'era', 'eran', 'está', 'están',
327
+ 'este', 'esta', 'ese', 'esa', 'aquel', 'aquella', 'esto', 'eso', 'aquello',
328
+ 'hizo', 'hacer', 'todo', 'toda', 'todos', 'todas', 'muy', 'más', 'tan',
329
+ 'ya', 'hoy', 'ayer', 'ahora', 'después', 'antes', 'mira', 'voy'
330
+ ]);
331
+
332
+ // Function to strip HTML tags
333
+ const stripHtml = (html: any) => {
334
+ if (typeof html !== 'string') return '';
335
+ const tmp = document.createElement("DIV");
336
+ tmp.innerHTML = html;
337
+ return tmp.textContent || tmp.innerText || "";
338
+ };
339
+
340
+ const titleText = stripHtml(editedItem.title);
341
+ const summaryText = stripHtml(editedItem.summary);
342
+
343
+ const text = `${titleText} ${summaryText}`.toLowerCase();
344
+ const words = text.replace(/[^\w\sáéíóúñü]/g, '').split(/\s+/);
345
+
346
+ const uniqueKeywords = new Set<string>();
347
+
348
+ words.forEach(word => {
349
+ if (word.length > 2 && !stopWords.has(word)) {
350
+ uniqueKeywords.add(word);
351
+ }
352
+ });
353
+
354
+ // Limit to 15 tags
355
+ const keywordsArray = Array.from(uniqueKeywords).slice(0, 15);
356
+ setEditedItem(prev => ({ ...prev, tags: keywordsArray }));
357
+ }}
358
+ className="text-xs text-primary hover:text-primary/80 transition-colors flex items-center gap-1 bg-primary/10 px-3 py-1.5 rounded-lg border border-primary/20"
359
+ title="Extraer palabras clave automáticamente"
360
+ >
361
+ <Sparkles size={14} /> Generar Automáticamente
362
+ </button>
363
+ </div>
364
+ </div>
365
+
366
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
367
+ <div>
368
+ <label className="block text-sm font-medium text-gray-400 mb-2">URL Visitar</label>
369
+ <input
370
+ type="url"
371
+ value={editedItem.visitUrl || ''}
372
+ onChange={(e) => setEditedItem(prev => ({ ...prev, visitUrl: e.target.value }))}
373
+ className="w-full bg-background border border-white/10 rounded-lg p-3 text-white focus:border-primary focus:ring-1 focus:ring-primary outline-none transition-colors"
374
+ placeholder="https://..."
375
+ />
376
+ </div>
377
+
378
+ <div>
379
+ <label className="block text-sm font-medium text-gray-400 mb-2">URL Descargar</label>
380
+ <input
381
+ type="url"
382
+ value={editedItem.downloadUrl || ''}
383
+ onChange={(e) => setEditedItem(prev => ({ ...prev, downloadUrl: e.target.value }))}
384
+ className="w-full bg-background border border-white/10 rounded-lg p-3 text-white focus:border-primary focus:ring-1 focus:ring-primary outline-none transition-colors"
385
+ placeholder="https://..."
386
+ />
387
+ </div>
388
+ </div>
389
+
390
+ <div className="border-t border-white/10 pt-6">
391
+ <div className="flex items-center justify-between mb-4">
392
+ <label className="block text-sm font-medium text-gray-400">Bloques de Contenido</label>
393
+ <button
394
+ onClick={handleAddBlockImmediately}
395
+ className="flex items-center gap-2 text-primary hover:text-white transition-colors text-sm font-medium"
396
+ >
397
+ <Plus size={16} /> Añadir Bloque
398
+ </button>
399
+ </div>
400
+
401
+ <div className="space-y-3">
402
+ {editedItem.blocks && editedItem.blocks.map((block, index) => (
403
+ <div key={block.id} className={`${getCardClasses(editedItem.cardStyle)} rounded-lg overflow-hidden transition-all duration-300`}>
404
+ <div className="flex items-center justify-between px-4 py-2 bg-white/5 border-b border-white/5">
405
+ <div className="flex items-center gap-2">
406
+ <span className="text-xs font-medium text-gray-500">Bloque {index + 1}</span>
407
+ {block.type === 'markdown' && (
408
+ <span className="text-[10px] px-1.5 py-0.5 bg-primary/20 text-primary rounded border border-primary/30">MD</span>
409
+ )}
410
+ </div>
411
+ <div className="flex items-center gap-2">
412
+ {editingBlockId === block.id ? (
413
+ <button
414
+ onClick={() => setEditingBlockId(null)}
415
+ className="text-primary hover:text-white transition-colors p-1"
416
+ title="Terminar edición"
417
+ >
418
+ <Check size={14} />
419
+ </button>
420
+ ) : (
421
+ <button
422
+ onClick={() => setEditingBlockId(block.id)}
423
+ className="text-gray-400 hover:text-white transition-colors p-1"
424
+ title="Editar bloque"
425
+ >
426
+ <Edit2 size={14} />
427
+ </button>
428
+ )}
429
+ <button
430
+ onClick={() => handleDeleteBlock(block.id)}
431
+ className="text-gray-400 hover:text-red-400 transition-colors p-1"
432
+ title="Eliminar bloque"
433
+ >
434
+ <Trash2 size={14} />
435
+ </button>
436
+ </div>
437
+ </div>
438
+ <div className="p-4">
439
+ <TipTapEditor
440
+ content={block.content}
441
+ onUpdate={(content) => handleBlockUpdate(block.id, content)}
442
+ isEditable={editingBlockId === block.id}
443
+ editorRef={editingBlockId === block.id ? activeEditorRef : undefined}
444
+ autoFocus={editingBlockId === block.id}
445
+ showToolbarOnFocus={true}
446
+ onBlockDoubleClick={(type, idx) => handleBlockDoubleClick(type, idx, block.id)}
447
+ dense={true}
448
+ className="min-h-[40px]"
449
+ cardStyle={editedItem.cardStyle || 'bordered'}
450
+ onCardStyleChange={(style) => setEditedItem(prev => ({ ...prev, cardStyle: style }))}
451
+ />
452
+ </div>
453
+ </div>
454
+ ))}
455
+
456
+
457
+ </div>
458
+ </div>
459
+ </div>
460
+
461
+ <div style={{ display: !showEditTab ? 'block' : 'none' }}>
462
+ <div className={`relative mb-8 p-6 rounded-xl ${getCardClasses(editedItem.cardStyle)}`}>
463
+ <div className="absolute top-5 right-5 z-20 flex gap-2">
464
+ <Button
465
+ variant="outline"
466
+ onClick={handleCancelEdit}
467
+ className="!py-1.5 !px-3 text-xs h-8 bg-black/40 hover:bg-black/60 border-white/10"
468
+ >
469
+ <X size={14} /> <span className="hidden sm:inline">Cancelar</span>
470
+
471
+ </Button>
472
+ <Button
473
+ variant="primary"
474
+ onClick={handleSaveChanges}
475
+ className="!py-1.5 !px-3 text-xs h-8"
476
+ >
477
+ <Save size={14} /> <span className="hidden sm:inline">Guardar</span>
478
+ </Button>
479
+ </div>
480
+
481
+ <div className="mb-6">
482
+ <label className="block text-xs font-medium text-gray-500 uppercase mb-2">Icono</label>
483
+ <IconPicker
484
+ selectedIcon={editedItem.icon || 'Layout'}
485
+ onSelect={(icon) => setEditedItem(prev => ({ ...prev, icon }))}
486
+ />
487
+ </div>
488
+
489
+ <div className="mb-6">
490
+ <label className="block text-xs font-medium text-gray-500 uppercase mb-2">Título</label>
491
+ <TipTapEditor
492
+ content={editedItem.title}
493
+ onUpdate={(content) => {
494
+ // Start editing title
495
+ if (typeof content === 'string') {
496
+ setEditedItem(prev => ({ ...prev, title: content }));
497
+ }
498
+ }}
499
+ isEditable={true}
500
+ dense={true}
501
+ className="min-h-[40px] text-2xl font-bold"
502
+ showToolbarOnFocus={true}
503
+ cardStyle={editedItem.cardStyle || 'bordered'}
504
+ onCardStyleChange={(style) => setEditedItem(prev => ({ ...prev, cardStyle: style }))}
505
+ />
506
+ </div>
507
+
508
+ <div className="mb-6">
509
+ <div className="flex justify-between items-center mb-2">
510
+ <label className="block text-xs font-medium text-gray-500 uppercase">Resumen</label>
511
+ </div>
512
+ <TipTapEditor
513
+ content={editedItem.summary}
514
+ onUpdate={(content) => {
515
+ // Update summary
516
+ if (typeof content === 'string') {
517
+ setEditedItem(prev => ({ ...prev, summary: content }));
518
+ }
519
+ }}
520
+ isEditable={true}
521
+ dense={true}
522
+ className="min-h-[80px]"
523
+ showToolbarOnFocus={true}
524
+ cardStyle={editedItem.cardStyle || 'bordered'}
525
+ onCardStyleChange={(style) => setEditedItem(prev => ({ ...prev, cardStyle: style }))}
526
+ />
527
+ </div>
528
+
529
+ {editedItem.tags.length > 0 && (
530
+ <div className="flex flex-wrap items-center gap-2 pt-4 border-t border-white/5">
531
+ {editedItem.tags.map((tag, idx) => (
532
+ <span key={idx} className="text-xs text-gray-500 bg-white/5 px-2 py-0.5 rounded border border-white/5 uppercase tracking-wide">
533
+ {tag}
534
+ </span>
535
+ ))}
536
+ </div>
537
+ )}
538
+ </div>
539
+
540
+ {editedItem.blocks && editedItem.blocks.length > 0 && (
541
+ <div className="space-y-6 mb-8">
542
+ {editedItem.blocks.map((block) => (
543
+ <div key={block.id} className={`${getCardClasses(editedItem.cardStyle)} h-fit rounded-xl overflow-hidden p-6 transition-all duration-300`}>
544
+ <TipTapEditor
545
+ content={block.content}
546
+ onUpdate={() => { }}
547
+ isEditable={false}
548
+ dense={true}
549
+ className="min-h-[40px]"
550
+ />
551
+ </div>
552
+ ))}
553
+ </div>
554
+ )}
555
+ </div>
556
+
557
+ <BlockEditorModal
558
+ isOpen={blockEditor.isOpen}
559
+ onClose={() => setBlockEditor(prev => ({ ...prev, isOpen: false }))}
560
+ editor={activeEditorRef.current}
561
+ type={blockEditor.type}
562
+ />
563
+
564
+ <ConfirmDialog
565
+ isOpen={confirmDialog.isOpen}
566
+ onClose={() => setConfirmDialog(prev => ({ ...prev, isOpen: false }))}
567
+ onConfirm={confirmDialog.onConfirm}
568
+ title={confirmDialog.title}
569
+ message={confirmDialog.message}
570
+ />
571
+
572
+ <AIInstructionModal
573
+ isOpen={aiModal.isOpen}
574
+ onClose={() => setAiModal(prev => ({ ...prev, isOpen: false }))}
575
+ onGenerate={aiModal.onGenerate}
576
+ currentContent={aiModal.currentContent}
577
+ />
578
+
579
+ </div >
580
+
581
+
582
+
583
+ );
584
+ }
585
+
586
+ return (
587
+ <div className="max-w-5xl mx-auto animate-fade-in pb-20">
588
+ <button
589
+ onClick={onBack}
590
+ className="mb-6 flex items-center gap-2 text-gray-400 hover:text-primary transition-colors text-sm font-medium"
591
+ >
592
+ <ArrowLeft size={18} /> Volver al Inicio
593
+ </button>
594
+
595
+ <div className={`${getCardClasses(item.cardStyle)} h-fit rounded-xl p-6 relative mb-8 flex flex-col md:block`}>
596
+ <div className="flex justify-end gap-2 mb-4 md:absolute md:top-5 md:right-5 md:mb-0 z-20">
597
+ {item.visitUrl && (
598
+ <a href={item.visitUrl} target="_blank" rel="noopener noreferrer">
599
+ <Button
600
+ variant="outline"
601
+ className="!py-1.5 !px-3 text-xs h-8"
602
+ >
603
+ <ExternalLink size={14} /> <span className="hidden sm:inline">Visitar</span>
604
+ </Button>
605
+ </a>
606
+ )}
607
+
608
+ {item.downloadUrl && (
609
+ <a href={item.downloadUrl} target="_blank" rel="noopener noreferrer">
610
+ <Button
611
+ variant="outline"
612
+ className="!py-1.5 !px-3 text-xs h-8"
613
+ >
614
+ <Download size={14} /> <span className="hidden sm:inline">Descargar</span>
615
+ </Button>
616
+ </a>
617
+ )}
618
+
619
+ {isEditable && (
620
+ <>
621
+ <Button
622
+ variant="outline"
623
+ onClick={() => setIsEditMode(true)}
624
+ className="!py-1.5 !px-3 text-xs h-8"
625
+ >
626
+ <Edit2 size={14} /> <span className="hidden sm:inline">Editar</span>
627
+ </Button>
628
+ <Button
629
+ variant="danger"
630
+ onClick={() => {
631
+ setConfirmDialog({
632
+ isOpen: true,
633
+ title: 'Eliminar Entrada',
634
+ message: '¿Estás seguro de que deseas eliminar esta entrada permanentemente? Esta acción no se puede deshacer.',
635
+ onConfirm: () => onDelete(item.id)
636
+ });
637
+ }}
638
+ className="!py-1.5 !px-3 h-8"
639
+ >
640
+ <Trash2 size={14} />
641
+ </Button>
642
+ </>
643
+ )}
644
+ </div>
645
+
646
+ <h1
647
+ className="text-2xl md:text-3xl font-bold text-white mb-3 md:pr-32 [&>p]:inline [&>p]:m-0"
648
+ dangerouslySetInnerHTML={{ __html: item.title || 'Título' }}
649
+ />
650
+
651
+ <TipTapEditor
652
+ content={item.summary || '<p>Resumen</p>'}
653
+ onUpdate={() => { }}
654
+ isEditable={false}
655
+ className="text-gray-300 text-base leading-relaxed max-w-4xl mb-4 [&>p]:m-0 min-h-0"
656
+ dense={true}
657
+ />
658
+
659
+ {item.tags.length > 0 && (
660
+ <div className="flex flex-wrap items-center gap-2 pt-4 border-t border-white/5">
661
+ {item.tags.map((tag, idx) => (
662
+ <span key={idx} className="text-xs text-gray-500 bg-white/5 px-2 py-0.5 rounded border border-white/5 uppercase tracking-wide">
663
+ {tag}
664
+ </span>
665
+ ))}
666
+ </div>
667
+ )}
668
+ </div>
669
+
670
+ {item.blocks && item.blocks.length > 0 && (
671
+ <div className="space-y-6 mb-8">
672
+ {item.blocks.map((block) => (
673
+ <div key={block.id} className={`${getCardClasses(item.cardStyle)} h-fit rounded-xl overflow-hidden p-6 transition-all duration-300`}>
674
+ <TipTapEditor
675
+ content={block.content}
676
+ onUpdate={() => { }}
677
+ isEditable={false}
678
+ dense={true}
679
+ className="min-h-[40px]"
680
+ />
681
+ </div>
682
+ ))}
683
+ </div>
684
+ )}
685
+
686
+
687
+ <ConfirmDialog
688
+ isOpen={confirmDialog.isOpen}
689
+ onClose={() => setConfirmDialog(prev => ({ ...prev, isOpen: false }))}
690
+ onConfirm={confirmDialog.onConfirm}
691
+ title={confirmDialog.title}
692
+ message={confirmDialog.message}
693
+ />
694
+
695
+ <AIInstructionModal
696
+ isOpen={aiModal.isOpen}
697
+ onClose={() => setAiModal(prev => ({ ...prev, isOpen: false }))}
698
+ onGenerate={aiModal.onGenerate}
699
+ currentContent={aiModal.currentContent}
700
+ />
701
+ </div>
702
+ );
703
+ };
components/DownloadButton.tsx ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useState } from 'react';
2
+ import { Download, Check } from 'lucide-react';
3
+
4
+ export const DownloadButton = ({ text, filename = 'download.txt', className = '', ...props }: { text: string, filename?: string, className?: string } & React.ButtonHTMLAttributes<HTMLButtonElement>) => {
5
+ const [downloaded, setDownloaded] = useState(false);
6
+
7
+ const handleDownload = () => {
8
+ const element = document.createElement("a");
9
+ const file = new Blob([text], { type: 'text/plain' });
10
+ element.href = URL.createObjectURL(file);
11
+ element.download = filename;
12
+ document.body.appendChild(element); // Required for this to work in FireFox
13
+ element.click();
14
+ document.body.removeChild(element);
15
+
16
+ setDownloaded(true);
17
+ setTimeout(() => setDownloaded(false), 2000);
18
+ };
19
+
20
+ return (
21
+ <button
22
+ onClick={handleDownload}
23
+ className={`p-1.5 bg-[#2d2d2d] border border-white/10 rounded-md text-gray-400 hover:text-white hover:bg-primary/20 transition-all z-10 ${className}`}
24
+ title="Descargar archivo"
25
+ {...props}
26
+ >
27
+ {downloaded ? <Check size={14} /> : <Download size={14} />}
28
+ </button>
29
+ );
30
+ };
components/EditorContextMenu.tsx ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React from 'react';
2
+ import { Editor } from '@tiptap/react';
3
+ import {
4
+ Bold,
5
+ Italic,
6
+ Code,
7
+ List,
8
+ ListOrdered,
9
+ Quote,
10
+ Heading1,
11
+ Heading2,
12
+ Link as LinkIcon,
13
+ Terminal,
14
+ FileCode,
15
+ Eraser,
16
+ AlignLeft,
17
+ AlignCenter,
18
+ AlignRight,
19
+ AlignJustify,
20
+ Settings
21
+ } from 'lucide-react';
22
+
23
+ interface EditorContextMenuProps {
24
+ editor: Editor | null;
25
+ x: number;
26
+ y: number;
27
+ onClose: () => void;
28
+ onOpenSettings: () => void;
29
+ }
30
+
31
+ export const EditorContextMenu: React.FC<EditorContextMenuProps> = ({ editor, x, y, onClose, onOpenSettings }) => {
32
+ if (!editor) return null;
33
+
34
+ const handleAction = (e: React.MouseEvent, action: () => void) => {
35
+ e.preventDefault();
36
+ e.stopPropagation();
37
+ action();
38
+ onClose();
39
+ };
40
+
41
+ const isAlignActive = (align: string) => editor.isActive({ textAlign: align });
42
+
43
+ const MenuItem = ({
44
+ icon: Icon,
45
+ label,
46
+ onClick,
47
+ isActive = false,
48
+ kdb = ''
49
+ }: {
50
+ icon: any,
51
+ label: string,
52
+ onClick: (e: React.MouseEvent) => void,
53
+ isActive?: boolean,
54
+ kdb?: string
55
+ }) => (
56
+ <button
57
+ onMouseDown={onClick}
58
+ className={`w-full flex items-center justify-between px-3 py-2 text-sm transition-colors ${isActive
59
+ ? 'bg-primary/20 text-primary'
60
+ : 'text-gray-300 hover:bg-white/10 hover:text-white'
61
+ }`}
62
+ >
63
+ <div className="flex items-center gap-2">
64
+ <Icon size={16} />
65
+ <span>{label}</span>
66
+ </div>
67
+ {kdb && <span className="text-xs text-gray-500 font-mono ml-4">{kdb}</span>}
68
+ </button>
69
+ );
70
+
71
+ const Divider = () => <div className="h-px bg-white/10 my-1 mx-2" />;
72
+
73
+ return (
74
+ <div
75
+ className="fixed z-[100] w-64 bg-[#1e1e1e] border border-white/10 rounded-lg shadow-2xl overflow-hidden py-1"
76
+ style={{
77
+ top: Math.min(y, window.innerHeight - 400),
78
+ left: Math.min(x, window.innerWidth - 260)
79
+ }}
80
+ onMouseDown={(e) => e.stopPropagation()}
81
+ onContextMenu={(e) => e.preventDefault()}
82
+ >
83
+ <MenuItem
84
+ icon={Heading1}
85
+ label="Título 1"
86
+ onClick={(e) => handleAction(e, () => editor.chain().focus().toggleHeading({ level: 1 }).run())}
87
+ isActive={editor.isActive('heading', { level: 1 })}
88
+ />
89
+ <MenuItem
90
+ icon={Heading2}
91
+ label="Título 2"
92
+ onClick={(e) => handleAction(e, () => editor.chain().focus().toggleHeading({ level: 2 }).run())}
93
+ isActive={editor.isActive('heading', { level: 2 })}
94
+ />
95
+
96
+ <Divider />
97
+
98
+ <MenuItem
99
+ icon={Bold}
100
+ label="Negrita"
101
+ onClick={(e) => handleAction(e, () => editor.chain().focus().toggleBold().run())}
102
+ isActive={editor.isActive('bold')}
103
+ kdb="Ctrl+B"
104
+ />
105
+ <MenuItem
106
+ icon={Italic}
107
+ label="Cursiva"
108
+ onClick={(e) => handleAction(e, () => editor.chain().focus().toggleItalic().run())}
109
+ isActive={editor.isActive('italic')}
110
+ kdb="Ctrl+I"
111
+ />
112
+
113
+ <Divider />
114
+
115
+ <MenuItem
116
+ icon={LinkIcon}
117
+ label="Enlace"
118
+ onClick={(e) => {
119
+ e.preventDefault();
120
+ e.stopPropagation();
121
+ const previousUrl = editor.getAttributes('link').href;
122
+ const url = window.prompt('URL del enlace:', previousUrl);
123
+ if (url === null) return;
124
+ if (url === '') {
125
+ editor.chain().focus().extendMarkRange('link').unsetLink().run();
126
+ return;
127
+ }
128
+ editor.chain().focus().extendMarkRange('link').setLink({ href: url }).run();
129
+ onClose();
130
+ }}
131
+ isActive={editor.isActive('link')}
132
+ />
133
+
134
+ <MenuItem
135
+ icon={Code}
136
+ label="Código Inline"
137
+ onClick={(e) => handleAction(e, () => editor.chain().focus().toggleCode().run())}
138
+ isActive={editor.isActive('code') && editor.getAttributes('code').showBackground !== false}
139
+ />
140
+
141
+ <MenuItem
142
+ icon={Terminal}
143
+ label="Estilo Tarjeta"
144
+ onClick={(e) => handleAction(e, () => {
145
+ const isCodeActive = editor.isActive('code');
146
+ if (isCodeActive) {
147
+ editor.chain().focus().unsetCode().run();
148
+ } else {
149
+ editor.chain().focus().setCode().updateAttributes('code', { showBackground: false }).run();
150
+ }
151
+ })}
152
+ isActive={editor.isActive('code') && editor.getAttributes('code').showBackground === false}
153
+ />
154
+
155
+ <MenuItem
156
+ icon={FileCode}
157
+ label="Bloque de Código"
158
+ onClick={(e) => handleAction(e, () => editor.chain().focus().setCodeBlock({ language: 'text' }).run())}
159
+ isActive={editor.isActive('codeBlock')}
160
+ />
161
+
162
+ <Divider />
163
+
164
+ <MenuItem
165
+ icon={Quote}
166
+ label="Cita"
167
+ onClick={(e) => handleAction(e, () => {
168
+ if (editor.isActive('customBlockquote')) {
169
+ editor.chain().focus().unsetBlockquote().run();
170
+ } else {
171
+ editor.chain().focus().setBlockquote().run();
172
+ }
173
+ })}
174
+ isActive={editor.isActive('customBlockquote')}
175
+ />
176
+
177
+ <MenuItem
178
+ icon={List}
179
+ label="Lista con viñetas"
180
+ onClick={(e) => handleAction(e, () => editor.chain().focus().toggleBulletList().run())}
181
+ isActive={editor.isActive('bulletList')}
182
+ />
183
+ <MenuItem
184
+ icon={ListOrdered}
185
+ label="Lista numerada"
186
+ onClick={(e) => handleAction(e, () => editor.chain().focus().toggleOrderedList().run())}
187
+ isActive={editor.isActive('orderedList')}
188
+ />
189
+
190
+ <Divider />
191
+
192
+ <div className="flex justify-between px-2 py-1">
193
+ <button
194
+ onMouseDown={(e) => handleAction(e, () => editor.chain().focus().setTextAlign('left').run())}
195
+ className={`p-1 rounded hover:bg-white/10 ${isAlignActive('left') ? 'text-primary' : 'text-gray-400'}`}
196
+ >
197
+ <AlignLeft size={16} />
198
+ </button>
199
+ <button
200
+ onMouseDown={(e) => handleAction(e, () => editor.chain().focus().setTextAlign('center').run())}
201
+ className={`p-1 rounded hover:bg-white/10 ${isAlignActive('center') ? 'text-primary' : 'text-gray-400'}`}
202
+ >
203
+ <AlignCenter size={16} />
204
+ </button>
205
+ <button
206
+ onMouseDown={(e) => handleAction(e, () => editor.chain().focus().setTextAlign('right').run())}
207
+ className={`p-1 rounded hover:bg-white/10 ${isAlignActive('right') ? 'text-primary' : 'text-gray-400'}`}
208
+ >
209
+ <AlignRight size={16} />
210
+ </button>
211
+ <button
212
+ onMouseDown={(e) => handleAction(e, () => editor.chain().focus().setTextAlign('justify').run())}
213
+ className={`p-1 rounded hover:bg-white/10 ${isAlignActive('justify') ? 'text-primary' : 'text-gray-400'}`}
214
+ >
215
+ <AlignJustify size={16} />
216
+ </button>
217
+ </div>
218
+
219
+ <Divider />
220
+
221
+ <MenuItem
222
+ icon={Eraser}
223
+ label="Limpiar Formato"
224
+ onClick={(e) => handleAction(e, () => editor.chain().focus().unsetAllMarks().clearNodes().run())}
225
+ />
226
+
227
+ <MenuItem
228
+ icon={Settings}
229
+ label="Configuración"
230
+ onClick={(e) => handleAction(e, onOpenSettings)}
231
+ />
232
+
233
+ </div>
234
+ );
235
+ };
components/EditorSelectionWrapper.tsx ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useState, useRef, useEffect } from 'react';
2
+ import { Editor } from '@tiptap/react';
3
+
4
+ interface EditorSelectionWrapperProps {
5
+ editor: Editor | null;
6
+ children: React.ReactNode;
7
+ onBackgroundClick?: () => void;
8
+ }
9
+
10
+ interface SelectionBox {
11
+ startX: number;
12
+ startY: number;
13
+ endX: number;
14
+ endY: number;
15
+ }
16
+
17
+ export const EditorSelectionWrapper: React.FC<EditorSelectionWrapperProps> = ({ editor, children, onBackgroundClick }) => {
18
+ const [isSelecting, setIsSelecting] = useState(false);
19
+ const [selectionBox, setSelectionBox] = useState<SelectionBox | null>(null);
20
+ const containerRef = useRef<HTMLDivElement>(null);
21
+
22
+ const handleMouseDown = (e: React.MouseEvent) => {
23
+ if (!editor || !containerRef.current) return;
24
+
25
+ // Only start selection if clicking on the container background, not on content
26
+ // We check if the target is the container itself or the ProseMirror editor div (but not its children)
27
+ // A simple heuristic is to check if the target has specific classes or if it's not a text node wrapper
28
+ // But the user specified: "Si el usuario hace clic y arrastra en un área vacía del editor"
29
+
30
+ // Let's check if the click target is the main editor container or the ProseMirror element directly
31
+ const target = e.target as HTMLElement;
32
+ const isContent = target.closest('.ProseMirror > *'); // Clicking on a block
33
+
34
+ if (isContent) {
35
+ return; // Allow normal text selection
36
+ }
37
+
38
+ // Only trigger on double click (and hold)
39
+ if (e.detail !== 2) {
40
+ return;
41
+ }
42
+
43
+ setIsSelecting(true);
44
+ const rect = containerRef.current.getBoundingClientRect();
45
+ const startX = e.clientX - rect.left;
46
+ const startY = e.clientY - rect.top;
47
+
48
+ setSelectionBox({
49
+ startX,
50
+ startY,
51
+ endX: startX,
52
+ endY: startY
53
+ });
54
+ };
55
+
56
+ const handleMouseMove = (e: React.MouseEvent) => {
57
+ if (!isSelecting || !selectionBox || !containerRef.current) return;
58
+
59
+ const rect = containerRef.current.getBoundingClientRect();
60
+ const currentX = e.clientX - rect.left;
61
+ const currentY = e.clientY - rect.top;
62
+
63
+ setSelectionBox({
64
+ ...selectionBox,
65
+ endX: currentX,
66
+ endY: currentY
67
+ });
68
+ };
69
+
70
+ const handleMouseUp = () => {
71
+ if (!isSelecting || !selectionBox || !editor || !containerRef.current) {
72
+ setIsSelecting(false);
73
+ setSelectionBox(null);
74
+ return;
75
+ }
76
+
77
+ // Calculate intersection and select blocks
78
+ const rect = containerRef.current.getBoundingClientRect();
79
+
80
+ // Normalize coordinates
81
+ const left = Math.min(selectionBox.startX, selectionBox.endX);
82
+ const top = Math.min(selectionBox.startY, selectionBox.endY);
83
+ const right = Math.max(selectionBox.startX, selectionBox.endX);
84
+ const bottom = Math.max(selectionBox.startY, selectionBox.endY);
85
+
86
+ // Convert to absolute page coordinates for comparison with getBoundingClientRect
87
+ const absLeft = rect.left + left;
88
+ const absTop = rect.top + top;
89
+ const absRight = rect.left + right;
90
+ const absBottom = rect.top + bottom;
91
+
92
+ const proseMirrorNode = containerRef.current.querySelector('.ProseMirror');
93
+ if (!proseMirrorNode) return;
94
+
95
+ const children = Array.from(proseMirrorNode.children);
96
+ let startPos: number | null = null;
97
+ let endPos: number | null = null;
98
+
99
+ children.forEach((child) => {
100
+ const childRect = child.getBoundingClientRect();
101
+
102
+ // Check intersection
103
+ const intersects = !(
104
+ childRect.right < absLeft ||
105
+ childRect.left > absRight ||
106
+ childRect.bottom < absTop ||
107
+ childRect.top > absBottom
108
+ );
109
+
110
+ if (intersects) {
111
+ try {
112
+ // Get Tiptap position
113
+ // We use editor.view.posAtDOM to find the position of the node
114
+ const pos = editor.view.posAtDOM(child as HTMLElement, 0);
115
+ if (pos >= 0) {
116
+ // For the end position, we need the node size
117
+ // We can find the node at this position
118
+ const node = editor.state.doc.nodeAt(pos);
119
+ if (node) {
120
+ if (startPos === null) startPos = pos;
121
+ endPos = pos + node.nodeSize;
122
+ }
123
+ }
124
+ } catch (err) {
125
+ console.warn('Error getting pos for node', err);
126
+ }
127
+ }
128
+ });
129
+
130
+ if (startPos !== null && endPos !== null) {
131
+ editor.chain().setTextSelection({ from: startPos, to: endPos }).run();
132
+ }
133
+
134
+ setIsSelecting(false);
135
+ setSelectionBox(null);
136
+ };
137
+
138
+ // Global mouse up to handle release outside container
139
+ useEffect(() => {
140
+ const handleGlobalMouseUp = () => {
141
+ if (isSelecting) {
142
+ handleMouseUp();
143
+ }
144
+ };
145
+
146
+ window.addEventListener('mouseup', handleGlobalMouseUp);
147
+ return () => window.removeEventListener('mouseup', handleGlobalMouseUp);
148
+ }, [isSelecting, selectionBox, editor]);
149
+
150
+ const handleClick = (e: React.MouseEvent) => {
151
+ if (e.target === e.currentTarget && onBackgroundClick) {
152
+ e.preventDefault();
153
+ onBackgroundClick();
154
+ }
155
+ };
156
+
157
+ return (
158
+ <div
159
+ ref={containerRef}
160
+ onMouseDown={handleMouseDown}
161
+ onMouseMove={handleMouseMove}
162
+ onClick={handleClick}
163
+ className="relative w-full h-full cursor-text"
164
+ >
165
+ {children}
166
+ {isSelecting && selectionBox && (
167
+ <div
168
+ style={{
169
+ position: 'absolute',
170
+ left: Math.min(selectionBox.startX, selectionBox.endX),
171
+ top: Math.min(selectionBox.startY, selectionBox.endY),
172
+ width: Math.abs(selectionBox.endX - selectionBox.startX),
173
+ height: Math.abs(selectionBox.endY - selectionBox.startY),
174
+ border: '1px solid #a855f7',
175
+ backgroundColor: 'rgba(168, 85, 247, 0.1)',
176
+ pointerEvents: 'none', // Allow events to pass through
177
+ zIndex: 50
178
+ }}
179
+ />
180
+ )}
181
+ </div>
182
+ );
183
+ };
components/EditorToolbar.tsx ADDED
@@ -0,0 +1,792 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useEffect, useState } from 'react';
2
+ import { Editor } from '@tiptap/react';
3
+ import {
4
+ Bold,
5
+ Italic,
6
+ Code,
7
+ Link as LinkIcon,
8
+ Heading1,
9
+ Heading2,
10
+ List,
11
+ ListOrdered,
12
+ Quote,
13
+ Pilcrow,
14
+ Settings,
15
+ Check,
16
+ X,
17
+ Eraser,
18
+ Image as ImageIcon,
19
+ AlignLeft,
20
+ AlignCenter,
21
+ AlignRight,
22
+ AlignJustify,
23
+ Video,
24
+ Terminal,
25
+ FileCode,
26
+ MousePointerClick,
27
+ ExternalLink,
28
+ Download,
29
+ Github,
30
+ Send,
31
+ Twitter,
32
+ Linkedin,
33
+ Instagram,
34
+ Youtube,
35
+ Facebook,
36
+ Layers,
37
+ MessageCircle, // Using MessageCircle as generic community/chat since Discord might be missing
38
+ Globe,
39
+ Mail,
40
+ FileText
41
+ // Music // Proxy for TikTok - Removed in favor of custom icon
42
+ } from 'lucide-react';
43
+ import { TiktokIcon } from './TiktokIcon';
44
+
45
+ import { QuoteStyleConfig, LinkStyleConfig, CodeStyleConfig } from '../services/codeStyleService';
46
+ import { uploadImageToImgBB } from '../services/imageService';
47
+
48
+ interface EditorToolbarProps {
49
+ editor: Editor | null;
50
+ onOpenSettings?: () => void;
51
+ onSave?: () => void;
52
+ defaultQuoteStyles?: QuoteStyleConfig;
53
+ linkStyleConfig?: LinkStyleConfig;
54
+ codeStyleConfig?: CodeStyleConfig;
55
+ buttonStyleConfig?: any;
56
+ minimalMode?: boolean;
57
+ }
58
+
59
+ export const EditorToolbar: React.FC<EditorToolbarProps> = ({
60
+ editor,
61
+ onOpenSettings,
62
+ onSave,
63
+ defaultQuoteStyles,
64
+ linkStyleConfig,
65
+ codeStyleConfig,
66
+ buttonStyleConfig,
67
+ minimalMode = false
68
+ }) => {
69
+ const [hasSelection, setHasSelection] = useState(false);
70
+ const [showLinkInput, setShowLinkInput] = useState(false);
71
+ const [linkUrl, setLinkUrl] = useState('');
72
+ const fileInputRef = React.useRef<HTMLInputElement>(null);
73
+ const [isUploading, setIsUploading] = useState(false);
74
+ const [showVideoInput, setShowVideoInput] = useState(false);
75
+ const [videoUrl, setVideoUrl] = useState('');
76
+ const [showButtonInput, setShowButtonInput] = useState(false);
77
+ const [buttonText, setButtonText] = useState('');
78
+ const [buttonUrl, setButtonUrl] = useState('');
79
+ const [buttonVariant, setButtonVariant] = useState<'visit' | 'download' | 'github' | 'telegram' | 'twitter' | 'linkedin' | 'instagram' | 'youtube' | 'facebook' | 'tiktok' | 'x' | 'code' | 'layers' | 'community' | 'globe' | 'mail' | 'file'>('visit');
80
+
81
+ useEffect(() => {
82
+ if (!editor) return;
83
+
84
+ const updateSelection = () => {
85
+ setHasSelection(!editor.state.selection.empty);
86
+ };
87
+
88
+ // Initial check
89
+ updateSelection();
90
+
91
+ editor.on('selectionUpdate', updateSelection);
92
+ editor.on('update', updateSelection);
93
+
94
+ return () => {
95
+ editor.off('selectionUpdate', updateSelection);
96
+ editor.off('update', updateSelection);
97
+ };
98
+ }, [editor]);
99
+
100
+ if (!editor) return null;
101
+
102
+ const handleAction = (e: React.MouseEvent, action: () => void) => {
103
+ e.preventDefault();
104
+ action();
105
+ };
106
+
107
+ const handleLink = (e: React.MouseEvent) => {
108
+ e.preventDefault();
109
+
110
+ if (editor.state.selection.empty && !editor.isActive('image')) {
111
+ return;
112
+ }
113
+
114
+ let previousUrl = '';
115
+ if (editor.isActive('image')) {
116
+ previousUrl = editor.getAttributes('image').href;
117
+ } else {
118
+ previousUrl = editor.getAttributes('link').href;
119
+ }
120
+
121
+ setLinkUrl(previousUrl || '');
122
+ setShowLinkInput(!showLinkInput);
123
+ };
124
+
125
+ const saveLink = () => {
126
+ if (editor.isActive('image')) {
127
+ if (linkUrl === '') {
128
+ editor.chain().focus().updateAttributes('image', { href: null }).run();
129
+ } else {
130
+ editor.chain().focus().updateAttributes('image', { href: linkUrl }).run();
131
+ }
132
+ } else {
133
+ if (linkUrl === '') {
134
+ editor.chain().focus().extendMarkRange('link').unsetLink().run();
135
+ } else {
136
+ const attributes: any = { href: linkUrl };
137
+ // Check if underline should be disabled
138
+ if (linkStyleConfig && !linkStyleConfig.underlineEnabled) {
139
+ attributes.class = 'no-underline-link';
140
+ }
141
+ editor.chain().focus().extendMarkRange('link').setLink(attributes).run();
142
+ }
143
+ }
144
+ setShowLinkInput(false);
145
+ setLinkUrl('');
146
+ };
147
+
148
+ const handleQuoteClick = (e: React.MouseEvent) => {
149
+ e.preventDefault();
150
+
151
+ // Allow quote creation even with empty selection (it will wrap the current block)
152
+
153
+ if (editor.isActive('customBlockquote')) {
154
+ editor.chain().focus().unsetBlockquote().run();
155
+ } else {
156
+ console.log('Creating quote with styles:', defaultQuoteStyles);
157
+ // Create with default styles if available
158
+ // Map QuoteStyleConfig properties to CustomBlockquote attributes
159
+ const attributes = defaultQuoteStyles ? {
160
+ ...defaultQuoteStyles,
161
+ backgroundColor: defaultQuoteStyles.bgColor, // Map bgColor to backgroundColor
162
+ // Ensure all other properties are passed correctly
163
+ borderColor: defaultQuoteStyles.borderColor,
164
+ borderWidth: defaultQuoteStyles.borderWidth,
165
+ textColor: defaultQuoteStyles.textColor,
166
+ padding: defaultQuoteStyles.padding,
167
+ fontSize: defaultQuoteStyles.fontSize,
168
+ borderRadius: defaultQuoteStyles.borderRadius,
169
+ width: defaultQuoteStyles.width,
170
+ height: defaultQuoteStyles.height,
171
+ italic: defaultQuoteStyles.italic,
172
+ showCopyButton: defaultQuoteStyles.showCopyButton,
173
+ showDownloadButton: defaultQuoteStyles.showDownloadButton,
174
+ collapsible: defaultQuoteStyles.collapsible,
175
+ fontFamily: defaultQuoteStyles.fontFamily,
176
+ isCodeFont: defaultQuoteStyles.isCodeFont
177
+ } : {};
178
+
179
+ editor.chain().focus().wrapIn('customBlockquote', attributes).run();
180
+ }
181
+ };
182
+
183
+ const handleCodeClick = (e: React.MouseEvent) => {
184
+ e.preventDefault();
185
+
186
+ // Allow toggle for typing
187
+ // if (editor.state.selection.empty) {
188
+ // return;
189
+ // }
190
+
191
+ const isCodeActive = editor.isActive('code');
192
+ const currentAttributes = editor.getAttributes('code');
193
+ const wantsBackground = codeStyleConfig?.showBackground ?? true;
194
+
195
+ if (isCodeActive) {
196
+ const currentShowBackground = currentAttributes.showBackground ?? true;
197
+
198
+ // If the current state doesn't match the preference, update it
199
+ if (currentShowBackground !== wantsBackground) {
200
+ editor.chain().focus().updateAttributes('code', { showBackground: wantsBackground }).run();
201
+ } else {
202
+ // If it matches, toggle it off (remove mark)
203
+ editor.chain().focus().unsetMark('code').run();
204
+ }
205
+ } else {
206
+ editor.chain().focus().setMark('code', { showBackground: wantsBackground }).run();
207
+ }
208
+
209
+ (editor.commands as any).removeStoredMark('code');
210
+ };
211
+
212
+ const handleCardCodeClick = (e: React.MouseEvent) => {
213
+ e.preventDefault();
214
+
215
+ // Allow toggle for typing
216
+ // if (editor.state.selection.empty) {
217
+ // return;
218
+ // }
219
+
220
+ const isCodeActive = editor.isActive('code');
221
+ const currentAttributes = editor.getAttributes('code');
222
+
223
+ if (isCodeActive) {
224
+ if (currentAttributes.showBackground !== false) {
225
+ // Switch to card style code
226
+ editor.chain().focus().updateAttributes('code', { showBackground: false }).run();
227
+ } else {
228
+ // Toggle off
229
+ editor.chain().focus().unsetMark('code').run();
230
+ }
231
+ } else {
232
+ editor.chain().focus().setMark('code', { showBackground: false }).run();
233
+ }
234
+
235
+ (editor.commands as any).removeStoredMark('code');
236
+ };
237
+
238
+
239
+
240
+ const handleClearFormatting = (e: React.MouseEvent) => {
241
+ e.preventDefault();
242
+ editor.chain().focus().unsetAllMarks().unsetBlockquote().clearNodes().setParagraph().run();
243
+ };
244
+
245
+ const handleImageUploadClick = () => {
246
+ fileInputRef.current?.click();
247
+ };
248
+
249
+ const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
250
+ const file = e.target.files?.[0];
251
+ if (!file) return;
252
+
253
+ setIsUploading(true);
254
+ try {
255
+ const url = await uploadImageToImgBB(file);
256
+ if (editor) {
257
+ editor.chain().focus().setImage({ src: url }).run();
258
+ }
259
+ } catch (error) {
260
+ console.error('Failed to upload image:', error);
261
+ alert('Error al subir la imagen. Por favor intenta de nuevo.');
262
+ } finally {
263
+ setIsUploading(false);
264
+ if (fileInputRef.current) {
265
+ fileInputRef.current.value = '';
266
+ }
267
+ }
268
+ };
269
+
270
+ const handleVideoClick = (e: React.MouseEvent) => {
271
+ e.preventDefault();
272
+ setShowVideoInput(!showVideoInput);
273
+ setShowLinkInput(false); // Cierra el input de links si estaba abierto
274
+ };
275
+
276
+ const saveVideo = () => {
277
+ if (videoUrl && editor) {
278
+ // Validamos si es YouTube y aseguramos el protocolo
279
+ let finalUrl = videoUrl.trim();
280
+ const youtubeRegex = /^(https?:\/\/)?(www\.)?(youtube\.com|youtu\.be)\/.+$/;
281
+
282
+ if (youtubeRegex.test(finalUrl)) {
283
+ if (!finalUrl.match(/^https?:\/\//)) {
284
+ finalUrl = `https://${finalUrl}`;
285
+ }
286
+ } else if (!finalUrl.match(/^https?:\/\//) && !finalUrl.startsWith('data:')) {
287
+ finalUrl = `https://${finalUrl}`;
288
+ }
289
+
290
+ editor.chain().focus().insertContent({ type: 'universalVideo', attrs: { src: finalUrl } }).run();
291
+ }
292
+ setShowVideoInput(false);
293
+ setVideoUrl('');
294
+ };
295
+
296
+ const handleButtonClick = (e: React.MouseEvent) => {
297
+ e.preventDefault();
298
+ setShowButtonInput(!showButtonInput);
299
+ setShowLinkInput(false);
300
+ setShowVideoInput(false);
301
+ };
302
+
303
+ const saveButton = () => {
304
+ if (buttonText && buttonUrl && editor) {
305
+ let finalUrl = buttonUrl.trim();
306
+ if (!finalUrl.match(/^https?:\/\//) && !finalUrl.startsWith('mailto:') && !finalUrl.startsWith('/')) {
307
+ finalUrl = `https://${finalUrl}`;
308
+ }
309
+
310
+ (editor.commands as any).setCustomButton({
311
+ text: buttonText,
312
+ url: finalUrl,
313
+ variant: buttonVariant,
314
+ backgroundColor: buttonStyleConfig?.backgroundColor,
315
+ textColor: buttonStyleConfig?.textColor,
316
+ borderRadius: buttonStyleConfig?.borderRadius,
317
+ width: buttonStyleConfig?.width,
318
+ height: buttonStyleConfig?.height
319
+ });
320
+ }
321
+ setShowButtonInput(false);
322
+ setButtonText('');
323
+ setButtonUrl('');
324
+ setButtonVariant('visit');
325
+ };
326
+
327
+ const handleAlign = (alignment: 'left' | 'center' | 'right' | 'justify') => {
328
+ if (!editor) return;
329
+
330
+ if (editor.isActive('universalVideo')) {
331
+ editor.chain().focus().updateAttributes('universalVideo', { align: alignment }).run();
332
+ } else if (editor.isActive('image')) {
333
+ editor.chain().focus().updateAttributes('image', { align: alignment }).run();
334
+ } else {
335
+ editor.chain().focus().setTextAlign(alignment).run();
336
+ }
337
+ };
338
+
339
+ const isAlignActive = (alignment: 'left' | 'center' | 'right' | 'justify') => {
340
+ if (!editor) return false;
341
+
342
+ if (editor.isActive('universalVideo')) {
343
+ return editor.getAttributes('universalVideo').align === alignment;
344
+ }
345
+ if (editor.isActive('image')) {
346
+ return editor.getAttributes('image').align === alignment;
347
+ }
348
+ return editor.isActive({ textAlign: alignment });
349
+ };
350
+
351
+
352
+
353
+ return (
354
+ <>
355
+ <div className="fixed bottom-10 left-1/2 -translate-x-1/2 z-50 flex items-center gap-2 rounded-full bg-zinc-900/90 backdrop-blur-md border border-white/10 shadow-2xl px-4 py-2 transition-all duration-300 ease-in-out max-w-[95vw] overflow-x-auto">
356
+
357
+ <div
358
+ className={`flex items-center gap-2 overflow-hidden transition-all duration-500 ease-in-out ${minimalMode ? 'w-0 opacity-0 pointer-events-none' : 'w-auto opacity-100'
359
+ }`}
360
+ >
361
+ <ToolbarButton
362
+ onMouseDown={(e) => handleAction(e, () => editor.chain().focus().toggleHeading({ level: 1 }).run())}
363
+ isActive={editor.isActive('heading', { level: 1 })}
364
+ icon={<Heading1 size={18} />}
365
+ title="Título 1"
366
+ />
367
+ <ToolbarButton
368
+ onMouseDown={(e) => handleAction(e, () => editor.chain().focus().toggleHeading({ level: 2 }).run())}
369
+ isActive={editor.isActive('heading', { level: 2 })}
370
+ icon={<Heading2 size={18} />}
371
+ title="Título 2"
372
+ />
373
+ <ToolbarButton
374
+ onMouseDown={(e) => handleAction(e, () => editor.chain().focus().setParagraph().run())}
375
+ isActive={editor.isActive('paragraph')}
376
+ icon={<Pilcrow size={18} />}
377
+ title="Párrafo"
378
+ />
379
+
380
+ <div className="w-px h-4 bg-white/10 mx-1 shrink-0" />
381
+
382
+ <ToolbarButton
383
+ onMouseDown={(e) => handleAction(e, () => editor.chain().focus().toggleBold().run())}
384
+ isActive={editor.isActive('bold')}
385
+ icon={<Bold size={18} />}
386
+ title="Negrita"
387
+ />
388
+ <ToolbarButton
389
+ onMouseDown={(e) => handleAction(e, () => editor.chain().focus().toggleItalic().run())}
390
+ isActive={editor.isActive('italic')}
391
+ icon={<Italic size={18} />}
392
+ title="Cursiva"
393
+ />
394
+ <ToolbarButton
395
+ onMouseDown={handleLink}
396
+ isActive={editor.isActive('link') || (editor.isActive('image') && !!editor.getAttributes('image').href)}
397
+ disabled={!hasSelection && !editor.isActive('image')}
398
+ icon={<LinkIcon size={18} />}
399
+ title="Enlace"
400
+ />
401
+ <ToolbarButton
402
+ onMouseDown={handleCodeClick}
403
+ isActive={editor.isActive('code') && editor.getAttributes('code').showBackground !== false}
404
+ icon={<Code size={18} />}
405
+ title="Código Inline"
406
+ />
407
+ <ToolbarButton
408
+ onMouseDown={handleCardCodeClick}
409
+ isActive={editor.isActive('code') && editor.getAttributes('code').showBackground === false}
410
+ icon={<Terminal size={18} />}
411
+ title="Texto Estilo Tarjeta"
412
+ />
413
+ <ToolbarButton
414
+ onMouseDown={(e) => {
415
+ e.preventDefault();
416
+ editor.chain().focus().setCodeBlock({
417
+ language: 'text' // Set a default language if required or just keep it simple
418
+ }).updateAttributes('codeBlock', {
419
+ collapsible: codeStyleConfig?.collapsible ?? true,
420
+ showLineNumbers: codeStyleConfig?.showLineNumbers ?? false,
421
+ wrapText: codeStyleConfig?.wrapText ?? false
422
+ }).run();
423
+ }}
424
+ isActive={editor.isActive('codeBlock')}
425
+ icon={<FileCode size={18} />}
426
+ title="Bloque de Código"
427
+ />
428
+
429
+ <ToolbarButton
430
+ onMouseDown={handleClearFormatting}
431
+ isActive={false}
432
+ icon={<Eraser size={18} />}
433
+ title="Limpiar Formato"
434
+ />
435
+
436
+ <div className="w-px h-4 bg-white/10 mx-1 shrink-0" />
437
+
438
+ <ToolbarButton
439
+ onMouseDown={(e) => { e.preventDefault(); handleImageUploadClick(); }}
440
+ isActive={false}
441
+ icon={isUploading ? <div className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" /> : <ImageIcon size={18} />}
442
+ title="Subir Imagen"
443
+ />
444
+ <input
445
+ type="file"
446
+ ref={fileInputRef}
447
+ onChange={handleFileChange}
448
+ accept="image/*"
449
+ className="hidden"
450
+ />
451
+
452
+ <ToolbarButton
453
+ onMouseDown={handleVideoClick}
454
+ isActive={false}
455
+ icon={<Video size={18} />}
456
+ title="Insertar Video de YouTube"
457
+ />
458
+
459
+ <ToolbarButton
460
+ onMouseDown={handleButtonClick}
461
+ isActive={false}
462
+ icon={<MousePointerClick size={18} />}
463
+ title="Insertar Botón de Acción"
464
+ />
465
+
466
+ <div className="w-px h-4 bg-white/10 mx-1 shrink-0" />
467
+
468
+ <ToolbarButton
469
+ onMouseDown={(e) => handleAction(e, () => handleAlign('left'))}
470
+ isActive={isAlignActive('left')}
471
+ icon={<AlignLeft size={18} />}
472
+ title="Alinear a la izquierda"
473
+ />
474
+ <ToolbarButton
475
+ onMouseDown={(e) => handleAction(e, () => handleAlign('center'))}
476
+ isActive={isAlignActive('center')}
477
+ icon={<AlignCenter size={18} />}
478
+ title="Centrar"
479
+ />
480
+ <ToolbarButton
481
+ onMouseDown={(e) => handleAction(e, () => handleAlign('right'))}
482
+ isActive={isAlignActive('right')}
483
+ icon={<AlignRight size={18} />}
484
+ title="Alinear a la derecha"
485
+ />
486
+ <ToolbarButton
487
+ onMouseDown={(e) => handleAction(e, () => handleAlign('justify'))}
488
+ isActive={isAlignActive('justify')}
489
+ icon={<AlignJustify size={18} />}
490
+ title="Justificar"
491
+ />
492
+
493
+ <div className="w-px h-4 bg-white/10 mx-1 shrink-0" />
494
+
495
+ <ToolbarButton
496
+ onMouseDown={(e) => handleAction(e, () => editor.chain().focus().toggleBulletList().run())}
497
+ isActive={editor.isActive('bulletList')}
498
+ icon={<List size={18} />}
499
+ title="Lista con viñetas"
500
+ />
501
+ <ToolbarButton
502
+ onMouseDown={(e) => handleAction(e, () => editor.chain().focus().toggleOrderedList().run())}
503
+ isActive={editor.isActive('orderedList')}
504
+ icon={<ListOrdered size={18} />}
505
+ title="Lista numerada"
506
+ />
507
+
508
+ <div className="w-px h-4 bg-white/10 mx-1 shrink-0" />
509
+
510
+ <ToolbarButton
511
+ onMouseDown={handleQuoteClick}
512
+ isActive={editor.isActive('customBlockquote')}
513
+ icon={<Quote size={18} />}
514
+ title="Cita Personalizada"
515
+ />
516
+
517
+ </div>
518
+
519
+ {onOpenSettings && (
520
+ <>
521
+ <div className={`w-px h-4 bg-white/10 mx-1 shrink-0 transition-opacity duration-300 ${minimalMode ? 'opacity-0' : 'opacity-100'}`} />
522
+ <ToolbarButton
523
+ onMouseDown={(e) => {
524
+ e.preventDefault();
525
+ onOpenSettings();
526
+ }}
527
+ isActive={false}
528
+ icon={<Settings size={18} />}
529
+ title="Configurar Estilo"
530
+ />
531
+ </>
532
+ )}
533
+ </div>
534
+
535
+ {
536
+ showLinkInput && (
537
+ <div className="fixed bottom-24 left-1/2 -translate-x-1/2 z-50 flex items-center gap-2 p-2 rounded-xl bg-[#1a1a1a] border border-white/10 shadow-2xl animate-fade-in">
538
+ <input
539
+ type="url"
540
+ value={linkUrl}
541
+ onChange={(e) => setLinkUrl(e.target.value)}
542
+ placeholder="https://ejemplo.com"
543
+ className="bg-transparent border border-white/10 rounded-lg px-3 py-1.5 text-sm text-white placeholder-zinc-500 focus:outline-none focus:border-primary min-w-[200px]"
544
+ onKeyDown={(e) => {
545
+ if (e.key === 'Enter') saveLink();
546
+ if (e.key === 'Escape') setShowLinkInput(false);
547
+ }}
548
+ onMouseDown={(e) => e.stopPropagation()}
549
+ onClick={(e) => e.stopPropagation()}
550
+ />
551
+ <button
552
+ onClick={(e) => { e.stopPropagation(); saveLink(); }}
553
+ className="p-1.5 rounded-lg bg-primary text-background hover:opacity-90 transition-opacity"
554
+ title="Guardar enlace"
555
+ >
556
+ <Check size={16} strokeWidth={2.5} />
557
+ </button>
558
+ <button
559
+ onClick={(e) => { e.stopPropagation(); setShowLinkInput(false); }}
560
+ className="p-1.5 rounded-lg hover:bg-white/10 text-zinc-400 hover:text-white transition-colors"
561
+ title="Cancelar"
562
+ >
563
+ <X size={16} />
564
+ </button>
565
+ </div>
566
+ )
567
+ }
568
+
569
+ {showVideoInput && (
570
+ <div
571
+ className="fixed bottom-24 left-1/2 -translate-x-1/2 z-50 flex items-center gap-2 p-2 rounded-xl bg-[#1a1a1a] border border-white/10 shadow-2xl animate-fade-in"
572
+ onMouseDown={(e) => e.stopPropagation()}
573
+ >
574
+ <input
575
+ type="url"
576
+ value={videoUrl}
577
+ onChange={(e) => setVideoUrl(e.target.value)}
578
+ placeholder="https://www.youtube.com/watch?v=..."
579
+ className="bg-transparent border border-white/10 rounded-lg px-3 py-1.5 text-sm text-white placeholder-zinc-500 focus:outline-none focus:border-primary min-w-[250px]"
580
+ onKeyDown={(e) => {
581
+ if (e.key === 'Enter') saveVideo();
582
+ if (e.key === 'Escape') setShowVideoInput(false);
583
+ }}
584
+ onMouseDown={(e) => e.stopPropagation()}
585
+ onClick={(e) => e.stopPropagation()}
586
+ autoFocus
587
+ />
588
+ <button
589
+ onClick={(e) => { e.stopPropagation(); saveVideo(); }}
590
+ className="p-1.5 rounded-lg bg-primary text-background hover:opacity-90 transition-opacity"
591
+ title="Confirmar video"
592
+ >
593
+ <Check size={16} strokeWidth={2.5} />
594
+ </button>
595
+ <button
596
+ onClick={(e) => { e.stopPropagation(); setShowVideoInput(false); }}
597
+ className="p-1.5 rounded-lg hover:bg-white/10 text-zinc-400 hover:text-white transition-colors"
598
+ title="Cancelar"
599
+ >
600
+ <X size={16} />
601
+ </button>
602
+ </div>
603
+ )}
604
+
605
+ {showButtonInput && (
606
+ <div
607
+ className="fixed bottom-24 left-1/2 -translate-x-1/2 z-50 flex flex-col gap-2 p-2 rounded-xl bg-[#1a1a1a] border border-white/10 shadow-2xl animate-fade-in w-[240px]"
608
+ onMouseDown={(e) => e.stopPropagation()}
609
+ >
610
+ <input
611
+ type="text"
612
+ value={buttonText}
613
+ onChange={(e) => setButtonText(e.target.value)}
614
+ placeholder="Texto"
615
+ className="bg-transparent border border-white/10 rounded-lg px-2 py-1.5 text-xs text-white placeholder-zinc-500 focus:outline-none focus:border-primary w-full"
616
+ onMouseDown={(e) => e.stopPropagation()}
617
+ onClick={(e) => e.stopPropagation()}
618
+ autoFocus
619
+ />
620
+ <input
621
+ type="url"
622
+ value={buttonUrl}
623
+ onChange={(e) => setButtonUrl(e.target.value)}
624
+ placeholder="URL"
625
+ className="bg-transparent border border-white/10 rounded-lg px-2 py-1.5 text-xs text-white placeholder-zinc-500 focus:outline-none focus:border-primary w-full"
626
+ onMouseDown={(e) => e.stopPropagation()}
627
+ onClick={(e) => e.stopPropagation()}
628
+ />
629
+ <div className="grid grid-cols-4 gap-1">
630
+ <button
631
+ onClick={() => setButtonVariant('visit')}
632
+ className={`flex justify-center items-center py-1.5 rounded-md border transition-colors ${buttonVariant === 'visit' ? 'bg-primary/20 border-primary text-primary' : 'border-white/10 text-zinc-400 hover:bg-white/5'}`}
633
+ title="Visitar"
634
+ >
635
+ <ExternalLink size={14} />
636
+ </button>
637
+ <button
638
+ onClick={() => setButtonVariant('download')}
639
+ className={`flex justify-center items-center py-1.5 rounded-md border transition-colors ${buttonVariant === 'download' ? 'bg-primary/20 border-primary text-primary' : 'border-white/10 text-zinc-400 hover:bg-white/5'}`}
640
+ title="Descargar"
641
+ >
642
+ <Download size={14} />
643
+ </button>
644
+ <button
645
+ onClick={() => setButtonVariant('github')}
646
+ className={`flex justify-center items-center py-1.5 rounded-md border transition-colors ${buttonVariant === 'github' ? 'bg-primary/20 border-primary text-primary' : 'border-white/10 text-zinc-400 hover:bg-white/5'}`}
647
+ title="GitHub"
648
+ >
649
+ <Github size={14} />
650
+ </button>
651
+ <button
652
+ onClick={() => setButtonVariant('telegram')}
653
+ className={`flex justify-center items-center py-1.5 rounded-md border transition-colors ${buttonVariant === 'telegram' ? 'bg-primary/20 border-primary text-primary' : 'border-white/10 text-zinc-400 hover:bg-white/5'}`}
654
+ title="Telegram"
655
+ >
656
+ <Send size={14} />
657
+ </button>
658
+ <button
659
+ onClick={() => setButtonVariant('twitter')}
660
+ className={`flex justify-center items-center py-1.5 rounded-md border transition-colors ${buttonVariant === 'twitter' ? 'bg-primary/20 border-primary text-primary' : 'border-white/10 text-zinc-400 hover:bg-white/5'}`}
661
+ title="Twitter"
662
+ >
663
+ <Twitter size={14} />
664
+ </button>
665
+ <button
666
+ onClick={() => setButtonVariant('linkedin')}
667
+ className={`flex justify-center items-center py-1.5 rounded-md border transition-colors ${buttonVariant === 'linkedin' ? 'bg-primary/20 border-primary text-primary' : 'border-white/10 text-zinc-400 hover:bg-white/5'}`}
668
+ title="LinkedIn"
669
+ >
670
+ <Linkedin size={14} />
671
+ </button>
672
+ <button
673
+ onClick={() => setButtonVariant('instagram')}
674
+ className={`flex justify-center items-center py-1.5 rounded-md border transition-colors ${buttonVariant === 'instagram' ? 'bg-primary/20 border-primary text-primary' : 'border-white/10 text-zinc-400 hover:bg-white/5'}`}
675
+ title="Instagram"
676
+ >
677
+ <Instagram size={14} />
678
+ </button>
679
+ <button
680
+ onClick={() => setButtonVariant('youtube')}
681
+ className={`flex justify-center items-center py-1.5 rounded-md border transition-colors ${buttonVariant === 'youtube' ? 'bg-primary/20 border-primary text-primary' : 'border-white/10 text-zinc-400 hover:bg-white/5'}`}
682
+ title="YouTube"
683
+ >
684
+ <Youtube size={14} />
685
+ </button>
686
+ <button
687
+ onClick={() => setButtonVariant('facebook')}
688
+ className={`flex justify-center items-center py-1.5 rounded-md border transition-colors ${buttonVariant === 'facebook' ? 'bg-primary/20 border-primary text-primary' : 'border-white/10 text-zinc-400 hover:bg-white/5'}`}
689
+ title="Facebook"
690
+ >
691
+ <Facebook size={14} />
692
+ </button>
693
+ <button
694
+ onClick={() => setButtonVariant('tiktok')}
695
+ className={`flex justify-center items-center py-1.5 rounded-md border transition-colors ${buttonVariant === 'tiktok' ? 'bg-primary/20 border-primary text-primary' : 'border-white/10 text-zinc-400 hover:bg-white/5'}`}
696
+ title="TikTok"
697
+ >
698
+ <TiktokIcon size={14} />
699
+ </button>
700
+ <button
701
+ onClick={() => setButtonVariant('x')}
702
+ className={`flex justify-center items-center py-1.5 rounded-md border transition-colors ${buttonVariant === 'x' ? 'bg-primary/20 border-primary text-primary' : 'border-white/10 text-zinc-400 hover:bg-white/5'}`}
703
+ title="X"
704
+ >
705
+ <X size={14} />
706
+ </button>
707
+ <button
708
+ onClick={() => setButtonVariant('code')}
709
+ className={`flex justify-center items-center py-1.5 rounded-md border transition-colors ${buttonVariant === 'code' ? 'bg-primary/20 border-primary text-primary' : 'border-white/10 text-zinc-400 hover:bg-white/5'}`}
710
+ title="Código"
711
+ >
712
+ <Code size={14} />
713
+ </button>
714
+ <button
715
+ onClick={() => setButtonVariant('layers')}
716
+ className={`flex justify-center items-center py-1.5 rounded-md border transition-colors ${buttonVariant === 'layers' ? 'bg-primary/20 border-primary text-primary' : 'border-white/10 text-zinc-400 hover:bg-white/5'}`}
717
+ title="Capas"
718
+ >
719
+ <Layers size={14} />
720
+ </button>
721
+ <button
722
+ onClick={() => setButtonVariant('community')}
723
+ className={`flex justify-center items-center py-1.5 rounded-md border transition-colors ${buttonVariant === 'community' ? 'bg-primary/20 border-primary text-primary' : 'border-white/10 text-zinc-400 hover:bg-white/5'}`}
724
+ title="Comunidad"
725
+ >
726
+ <MessageCircle size={14} />
727
+ </button>
728
+ <button
729
+ onClick={() => setButtonVariant('globe')}
730
+ className={`flex justify-center items-center py-1.5 rounded-md border transition-colors ${buttonVariant === 'globe' ? 'bg-primary/20 border-primary text-primary' : 'border-white/10 text-zinc-400 hover:bg-white/5'}`}
731
+ title="Web"
732
+ >
733
+ <Globe size={14} />
734
+ </button>
735
+ <button
736
+ onClick={() => setButtonVariant('mail')}
737
+ className={`flex justify-center items-center py-1.5 rounded-md border transition-colors ${buttonVariant === 'mail' ? 'bg-primary/20 border-primary text-primary' : 'border-white/10 text-zinc-400 hover:bg-white/5'}`}
738
+ title="Email"
739
+ >
740
+ <Mail size={14} />
741
+ </button>
742
+ <button
743
+ onClick={() => setButtonVariant('file')}
744
+ className={`flex justify-center items-center py-1.5 rounded-md border transition-colors ${buttonVariant === 'file' ? 'bg-primary/20 border-primary text-primary' : 'border-white/10 text-zinc-400 hover:bg-white/5'}`}
745
+ title="Documento"
746
+ >
747
+ <FileText size={14} />
748
+ </button>
749
+ </div>
750
+ <div className="flex justify-end gap-1 mt-1">
751
+ <button
752
+ onClick={() => setShowButtonInput(false)}
753
+ className="px-2 py-1 rounded-md hover:bg-white/10 text-zinc-400 hover:text-white transition-colors text-[10px]"
754
+ >
755
+ Cancelar
756
+ </button>
757
+ <button
758
+ onClick={saveButton}
759
+ className="px-2 py-1 rounded-md bg-primary text-background hover:opacity-90 transition-opacity text-[10px] font-medium"
760
+ >
761
+ Insertar
762
+ </button>
763
+ </div>
764
+ </div>
765
+ )}
766
+
767
+
768
+ </>
769
+ );
770
+ };
771
+
772
+ interface ToolbarButtonProps {
773
+ onMouseDown: (e: React.MouseEvent) => void;
774
+ isActive?: boolean;
775
+ disabled?: boolean;
776
+ icon: React.ReactNode;
777
+ title: string;
778
+ }
779
+
780
+ const ToolbarButton: React.FC<ToolbarButtonProps> = ({ onMouseDown, isActive, disabled, icon, title }) => (
781
+ <button
782
+ onMouseDown={onMouseDown}
783
+ disabled={disabled}
784
+ title={title}
785
+ className={`p-2 rounded-full transition-colors ${isActive
786
+ ? 'bg-white text-black'
787
+ : 'text-zinc-400 hover:text-white hover:bg-white/10'
788
+ } ${disabled ? 'opacity-40 cursor-not-allowed' : 'opacity-100 cursor-pointer'}`}
789
+ >
790
+ {icon}
791
+ </button>
792
+ );
components/IconPicker.tsx ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useState, useRef, useEffect } from 'react';
2
+ import {
3
+ Github, Twitter, Globe, Download, Youtube, Twitch,
4
+ Linkedin, Facebook, Instagram, Code, Terminal, Database,
5
+ Server, Smartphone, Monitor, Cpu, FileText, Image,
6
+ Music, Video, Box, Layers, Zap, Activity,
7
+ Award, Bookmark, Calendar, Camera, Check, Clock,
8
+ Cloud, Command, Compass, Copy, CreditCard, Flag,
9
+ Folder, Gift, Heart, Home, Key, Link as LinkIcon,
10
+ Lock, Mail, Map, MapPin, MessageCircle, MessageSquare,
11
+ Mic, Moon, Mouse, Package, Paperclip, Phone,
12
+ Play, Plus, Power, Printer, Radio, RotateCw,
13
+ Save, Search, Send, Settings, Share, Shield,
14
+ ShoppingBag, ShoppingCart, Info, Star, Sun, Tag,
15
+ ThumbsUp, PenTool, Trash, Truck, Tv, Unlock,
16
+ Upload, User, Users, Wifi, X
17
+ } from 'lucide-react';
18
+
19
+ interface IconPickerProps {
20
+ selectedIcon?: string;
21
+ onSelect: (iconName: string) => void;
22
+ }
23
+
24
+ const ICON_MAP: Record<string, React.FC<any>> = {
25
+ 'github': Github,
26
+ 'twitter': Twitter,
27
+ 'globe': Globe,
28
+ 'download': Download,
29
+ 'youtube': Youtube,
30
+ 'twitch': Twitch,
31
+ 'linkedin': Linkedin,
32
+ 'facebook': Facebook,
33
+ 'instagram': Instagram,
34
+ 'code': Code,
35
+ 'terminal': Terminal,
36
+ 'database': Database,
37
+ 'server': Server,
38
+ 'smartphone': Smartphone,
39
+ 'monitor': Monitor,
40
+ 'cpu': Cpu,
41
+ 'file-text': FileText,
42
+ 'image': Image,
43
+ 'music': Music,
44
+ 'video': Video,
45
+ 'box': Box,
46
+ 'layers': Layers,
47
+ 'zap': Zap,
48
+ 'activity': Activity,
49
+ 'award': Award,
50
+ 'bookmark': Bookmark,
51
+ 'calendar': Calendar,
52
+ 'camera': Camera,
53
+ 'check': Check,
54
+ 'clock': Clock,
55
+ 'cloud': Cloud,
56
+ 'command': Command,
57
+ 'compass': Compass,
58
+ 'copy': Copy,
59
+ 'credit-card': CreditCard,
60
+ 'flag': Flag,
61
+ 'folder': Folder,
62
+ 'gift': Gift,
63
+ 'heart': Heart,
64
+ 'home': Home,
65
+ 'key': Key,
66
+ 'link': LinkIcon,
67
+ 'lock': Lock,
68
+ 'mail': Mail,
69
+ 'map': Map,
70
+ 'map-pin': MapPin,
71
+ 'message-circle': MessageCircle,
72
+ 'message-square': MessageSquare,
73
+ 'mic': Mic,
74
+ 'moon': Moon,
75
+ 'mouse': Mouse,
76
+ 'package': Package,
77
+ 'paperclip': Paperclip,
78
+ 'phone': Phone,
79
+ 'play': Play,
80
+ 'plus': Plus,
81
+ 'power': Power,
82
+ 'printer': Printer,
83
+ 'radio': Radio,
84
+ 'rotate-cw': RotateCw,
85
+ 'save': Save,
86
+ 'search': Search,
87
+ 'send': Send,
88
+ 'settings': Settings,
89
+ 'share': Share,
90
+ 'shield': Shield,
91
+ 'shopping-bag': ShoppingBag,
92
+ 'shopping-cart': ShoppingCart,
93
+ 'info': Info,
94
+ 'star': Star,
95
+ 'sun': Sun,
96
+ 'tag': Tag,
97
+ 'thumbs-up': ThumbsUp,
98
+ 'tool': PenTool,
99
+ 'trash': Trash,
100
+ 'truck': Truck,
101
+ 'tv': Tv,
102
+ 'unlock': Unlock,
103
+ 'upload': Upload,
104
+ 'user': User,
105
+ 'users': Users,
106
+ 'wifi': Wifi,
107
+ 'x': X,
108
+ };
109
+
110
+ export const getIconComponent = (iconName?: string) => {
111
+ if (!iconName) return null;
112
+ return ICON_MAP[iconName] || null;
113
+ };
114
+
115
+ export const IconPicker: React.FC<IconPickerProps> = ({ selectedIcon, onSelect }) => {
116
+ const [isOpen, setIsOpen] = useState(false);
117
+ const [searchTerm, setSearchTerm] = useState('');
118
+ const wrapperRef = useRef<HTMLDivElement>(null);
119
+
120
+ useEffect(() => {
121
+ function handleClickOutside(event: MouseEvent) {
122
+ if (wrapperRef.current && !wrapperRef.current.contains(event.target as Node)) {
123
+ setIsOpen(false);
124
+ }
125
+ }
126
+ document.addEventListener("mousedown", handleClickOutside);
127
+ return () => {
128
+ document.removeEventListener("mousedown", handleClickOutside);
129
+ };
130
+ }, [wrapperRef]);
131
+
132
+ const filteredIcons = Object.keys(ICON_MAP).filter(name =>
133
+ name.toLowerCase().includes(searchTerm.toLowerCase())
134
+ );
135
+
136
+ const SelectedIconComponent = getIconComponent(selectedIcon);
137
+
138
+ return (
139
+ <div className="relative" ref={wrapperRef}>
140
+ <button
141
+ type="button"
142
+ onClick={() => setIsOpen(!isOpen)}
143
+ className="w-12 h-[46px] rounded-lg border border-white/10 bg-background hover:bg-white/5 flex items-center justify-center transition-colors text-gray-400 hover:text-white focus:outline-none focus:ring-1 focus:ring-primary focus:border-primary"
144
+ title="Seleccionar icono"
145
+ >
146
+ {SelectedIconComponent ? (
147
+ <SelectedIconComponent size={20} className="text-primary" />
148
+ ) : (
149
+ <Box size={20} />
150
+ )}
151
+ </button>
152
+
153
+ {isOpen && (
154
+ <div className="absolute top-full left-0 mt-2 z-50 w-72 bg-surface border border-white/10 rounded-xl shadow-2xl overflow-hidden animate-in fade-in zoom-in-95 duration-200">
155
+ <div className="p-3 border-b border-white/10">
156
+ <div className="relative">
157
+ <Search className="absolute left-2.5 top-1/2 -translate-y-1/2 text-gray-500" size={14} />
158
+ <input
159
+ type="text"
160
+ placeholder="Buscar icono..."
161
+ value={searchTerm}
162
+ onChange={(e) => setSearchTerm(e.target.value)}
163
+ className="w-full bg-background border border-white/10 rounded-lg py-1.5 pl-8 pr-3 text-sm text-gray-200 outline-none focus:border-primary"
164
+ autoFocus
165
+ />
166
+ </div>
167
+ </div>
168
+
169
+ <div className="p-2 grid grid-cols-5 gap-1 max-h-64 overflow-y-auto custom-scrollbar">
170
+ {filteredIcons.map((iconName) => {
171
+ const Icon = ICON_MAP[iconName];
172
+ const isSelected = selectedIcon === iconName;
173
+
174
+ return (
175
+ <button
176
+ key={iconName}
177
+ type="button"
178
+ onClick={() => {
179
+ onSelect(iconName);
180
+ setIsOpen(false);
181
+ }}
182
+ className={`p-2 rounded-lg flex items-center justify-center transition-all ${isSelected
183
+ ? 'bg-primary/20 text-primary'
184
+ : 'text-gray-400 hover:bg-white/5 hover:text-white'
185
+ }`}
186
+ title={iconName}
187
+ >
188
+ <Icon size={20} />
189
+ </button>
190
+ );
191
+ })}
192
+
193
+ {filteredIcons.length === 0 && (
194
+ <div className="col-span-5 py-4 text-center text-xs text-gray-500">
195
+ No se encontraron iconos
196
+ </div>
197
+ )}
198
+ </div>
199
+ </div>
200
+ )}
201
+ </div>
202
+ );
203
+ };
components/MarkdownRenderer.tsx ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useState, useEffect, useRef } from 'react';
2
+ import ReactMarkdown from 'react-markdown';
3
+ import remarkGfm from 'remark-gfm';
4
+ import rehypeRaw from 'rehype-raw';
5
+ import rehypeSanitize from 'rehype-sanitize';
6
+ import { Copy, Check, Edit2 } from 'lucide-react';
7
+ import { subscribeToStyleConfig } from '../services/codeStyleService';
8
+ import { CopyButton } from './CopyButton';
9
+ import { CustomBlockquote } from './CustomBlockquote';
10
+
11
+ interface MarkdownRendererProps {
12
+ content: string;
13
+ onBlockDoubleClick?: (type: 'code' | 'quote', index: number) => void;
14
+ }
15
+
16
+ export const MarkdownRenderer: React.FC<MarkdownRendererProps> = ({ content, onBlockDoubleClick }) => {
17
+ const [showCopyButton, setShowCopyButton] = useState(false);
18
+ const [copied, setCopied] = useState(false);
19
+ const containerRef = useRef<HTMLDivElement>(null);
20
+
21
+ useEffect(() => {
22
+ const unsubscribe = subscribeToStyleConfig((config) => {
23
+ setShowCopyButton(config.showCopyButton);
24
+ });
25
+ return () => unsubscribe();
26
+ }, []);
27
+
28
+ const handleCopy = () => {
29
+ navigator.clipboard.writeText(content);
30
+ setCopied(true);
31
+ setTimeout(() => setCopied(false), 2000);
32
+ };
33
+
34
+ const handleBlockDoubleClick = (e: React.MouseEvent, type: 'code' | 'quote') => {
35
+ if (!onBlockDoubleClick || !containerRef.current) return;
36
+
37
+ e.stopPropagation(); // Prevent bubbling
38
+
39
+ const wrapper = e.currentTarget as HTMLElement;
40
+ const selector = type === 'quote' ? 'blockquote' : 'pre';
41
+ const block = wrapper.querySelector(selector);
42
+
43
+ if (!block) return;
44
+
45
+ const allBlocks = Array.from(containerRef.current.querySelectorAll(selector));
46
+ const index = allBlocks.indexOf(block as any);
47
+
48
+ if (index !== -1) {
49
+ onBlockDoubleClick(type, index);
50
+ }
51
+ };
52
+
53
+ return (
54
+ <div ref={containerRef} className="markdown-content relative group">
55
+ {showCopyButton && (
56
+ <button
57
+ onClick={handleCopy}
58
+ className="absolute -top-2 -right-2 p-2 bg-surface border border-white/10 rounded-lg opacity-0 group-hover:opacity-100 transition-opacity hover:bg-primary hover:text-background z-10"
59
+ title="Copiar contenido"
60
+ >
61
+ {copied ? <Check size={16} /> : <Copy size={16} />}
62
+ </button>
63
+ )}
64
+ <ReactMarkdown
65
+ remarkPlugins={[remarkGfm]}
66
+ rehypePlugins={[rehypeRaw]}
67
+ components={{
68
+ h1: ({ children }) => (
69
+ <h1 className="text-3xl font-bold text-white mb-4 pb-2 border-b border-white/10">
70
+ {children}
71
+ </h1>
72
+ ),
73
+ h2: ({ children }) => (
74
+ <h2 className="text-2xl font-bold text-white mb-3 pb-2 border-b border-white/10 mt-6">
75
+ {children}
76
+ </h2>
77
+ ),
78
+ h3: ({ children }) => (
79
+ <h3 className="text-xl font-bold text-white mb-2 mt-4">
80
+ {children}
81
+ </h3>
82
+ ),
83
+ h4: ({ children }) => (
84
+ <h4 className="text-lg font-semibold text-white mb-2 mt-3">
85
+ {children}
86
+ </h4>
87
+ ),
88
+ h5: ({ children }) => (
89
+ <h5 className="text-base font-semibold text-white mb-2 mt-3">
90
+ {children}
91
+ </h5>
92
+ ),
93
+ h6: ({ children }) => (
94
+ <h6 className="text-sm font-semibold text-gray-300 mb-2 mt-3">
95
+ {children}
96
+ </h6>
97
+ ),
98
+ p: ({ children }) => (
99
+ <p className="text-gray-300 mb-4 leading-relaxed">
100
+ {children}
101
+ </p>
102
+ ),
103
+ ul: ({ children }) => (
104
+ <ul className="list-disc list-inside text-gray-300 mb-4 space-y-1 ml-4">
105
+ {children}
106
+ </ul>
107
+ ),
108
+ ol: ({ children }) => (
109
+ <ol className="list-decimal list-inside text-gray-300 mb-4 space-y-1 ml-4">
110
+ {children}
111
+ </ol>
112
+ ),
113
+ li: ({ children }) => (
114
+ <li className="text-gray-300">
115
+ {children}
116
+ </li>
117
+ ),
118
+ blockquote: ({ children, ...props }) => (
119
+ <div
120
+ onDoubleClick={(e) => handleBlockDoubleClick(e, 'quote')}
121
+ >
122
+ <CustomBlockquote isEditable={!!onBlockDoubleClick} {...props}>{children}</CustomBlockquote>
123
+ </div>
124
+ ),
125
+ code: ({ inline, children, className, style, ...props }: any) => {
126
+ const codeString = String(children).replace(/\n$/, '');
127
+
128
+ if (inline) {
129
+ return (
130
+ <code className={className} style={style} {...props}>
131
+ {children}
132
+ </code>
133
+ );
134
+ }
135
+
136
+ return (
137
+ <code className="text-gray-300 font-mono text-sm leading-relaxed">
138
+ {codeString.split('\n').map((line, i) => {
139
+ const highlighted = line
140
+ .replace(/(\b(?:const|let|var|function|return|if|else|for|while|class|import|export|from|default|async|await|try|catch|throw|new)\b)/g, '<span class="text-[#569cd6]">$1</span>')
141
+ .replace(/(['"`].*?['"`])/g, '<span class="text-[#ce9178]">$1</span>')
142
+ .replace(/(\b\d+\b)/g, '<span class="text-[#b5cea8]">$1</span>')
143
+ .replace(/(\/\/.*$)/g, '<span class="text-[#6a9955]">$1</span>')
144
+ .replace(/([{}()[\];,.])/g, '<span class="text-gray-400">$1</span>');
145
+
146
+ return (
147
+ <div key={i} className="leading-6" dangerouslySetInnerHTML={{ __html: highlighted || ' ' }} />
148
+ );
149
+ })}
150
+ </code>
151
+ );
152
+ },
153
+ pre: ({ children, ...props }: any) => {
154
+ // Extract text content from the code block for the copy button
155
+ let codeText = '';
156
+ const childProps = (children as any)?.props;
157
+ if (React.isValidElement(children) && childProps && childProps.children) {
158
+ codeText = String(childProps.children);
159
+ }
160
+
161
+ const showCopy = props['data-show-copy'] === 'true' || (props['data-show-copy'] === undefined && showCopyButton);
162
+
163
+ return (
164
+ <div
165
+ className="relative group mb-4"
166
+ onDoubleClick={(e) => handleBlockDoubleClick(e, 'code')}
167
+ >
168
+ <pre className="overflow-x-auto bg-[#1a1a1a] border border-white/10 rounded-lg p-4" {...props}>
169
+ {children}
170
+ </pre>
171
+ <div className={`absolute top-2 right-2 flex gap-2 opacity-0 group-hover:opacity-100 transition-opacity`}>
172
+ {showCopy && <CopyButton text={codeText} className="" />}
173
+ </div>
174
+ </div>
175
+ );
176
+ },
177
+ a: ({ href, children }) => (
178
+ <a
179
+ href={href}
180
+ target="_blank"
181
+ rel="noopener noreferrer"
182
+ className="text-primary hover:underline"
183
+ >
184
+ {children}
185
+ </a>
186
+ ),
187
+ hr: () => (
188
+ <hr className="border-white/10 my-6" />
189
+ ),
190
+ table: ({ children }) => (
191
+ <div className="overflow-x-auto mb-4">
192
+ <table className="min-w-full border border-white/10 rounded-lg overflow-hidden">
193
+ {children}
194
+ </table>
195
+ </div>
196
+ ),
197
+ thead: ({ children }) => (
198
+ <thead className="bg-white/5">
199
+ {children}
200
+ </thead>
201
+ ),
202
+ tbody: ({ children }) => (
203
+ <tbody className="divide-y divide-white/10">
204
+ {children}
205
+ </tbody>
206
+ ),
207
+ tr: ({ children }) => (
208
+ <tr>
209
+ {children}
210
+ </tr>
211
+ ),
212
+ th: ({ children }) => (
213
+ <th className="px-4 py-2 text-left text-white font-semibold border border-white/10">
214
+ {children}
215
+ </th>
216
+ ),
217
+ td: ({ children }) => (
218
+ <td className="px-4 py-2 text-gray-300 border border-white/10">
219
+ {children}
220
+ </td>
221
+ ),
222
+ img: ({ src, alt }) => (
223
+ <img
224
+ src={src}
225
+ alt={alt}
226
+ className="max-w-full h-auto rounded-lg my-4 border border-white/10"
227
+ />
228
+ ),
229
+ }}
230
+ >
231
+ {content}
232
+ </ReactMarkdown>
233
+ </div>
234
+ );
235
+ };
components/QuoteBlock.tsx ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useState, useEffect } from 'react';
2
+ import { subscribeToStyleConfig, DEFAULT_QUOTE_STYLE, QuoteStyleConfig } from '../services/codeStyleService';
3
+ import { CopyButton } from './CopyButton';
4
+ import { Edit2 } from 'lucide-react';
5
+
6
+ interface QuoteBlockProps extends React.HTMLAttributes<HTMLElement> {
7
+ children: React.ReactNode;
8
+ 'data-show-copy'?: string;
9
+ isEditable?: boolean;
10
+ }
11
+
12
+ export const QuoteBlock: React.FC<QuoteBlockProps> = ({ children, style, isEditable, ...props }) => {
13
+ const [quoteStyle, setQuoteStyle] = useState<QuoteStyleConfig>(DEFAULT_QUOTE_STYLE);
14
+ const [quoteText, setQuoteText] = useState('');
15
+
16
+ useEffect(() => {
17
+ const unsubscribe = subscribeToStyleConfig((config) => {
18
+ setQuoteStyle(config.quote);
19
+ });
20
+ return () => unsubscribe();
21
+ }, []);
22
+
23
+ useEffect(() => {
24
+ let text = '';
25
+ if (Array.isArray(children)) {
26
+ text = children
27
+ .map((child) => {
28
+ if (typeof child === 'string') return child;
29
+ if (React.isValidElement(child) && (child.props as any).children) {
30
+ return String((child.props as any).children);
31
+ }
32
+ return '';
33
+ })
34
+ .join('\n');
35
+ } else if (typeof children === 'string') {
36
+ text = children;
37
+ }
38
+ setQuoteText(text);
39
+ }, [children]);
40
+
41
+ // Merge global styles with inline styles (inline takes precedence)
42
+ const containerStyle: React.CSSProperties = {
43
+ backgroundColor: quoteStyle.bgColor,
44
+ color: quoteStyle.textColor,
45
+ borderLeft: `${quoteStyle.borderWidth} solid ${quoteStyle.borderColor}`,
46
+ padding: quoteStyle.padding,
47
+ fontSize: quoteStyle.fontSize,
48
+ borderRadius: quoteStyle.borderRadius,
49
+ fontStyle: quoteStyle.italic ? 'italic' : 'normal',
50
+ width: (quoteStyle.width !== 'auto' && quoteStyle.width) ? quoteStyle.width : '100%',
51
+ height: quoteStyle.height !== 'auto' ? quoteStyle.height : undefined,
52
+ minHeight: 0,
53
+ overflow: 'visible',
54
+ position: 'relative',
55
+ maxWidth: '100%',
56
+ boxSizing: 'border-box',
57
+ marginBottom: '1rem',
58
+ transition: 'all 0.2s ease-in-out',
59
+ display: 'flex',
60
+ flexDirection: 'column',
61
+ justifyContent: 'center',
62
+ ...style, // Override with inline styles
63
+ };
64
+
65
+ // Ensure inline style width is also respected or defaults to 100% if auto/undefined
66
+ if (containerStyle.width === 'auto' || !containerStyle.width) {
67
+ containerStyle.width = '100%';
68
+ }
69
+
70
+ const showCopyButton = props['data-show-copy'] === 'true' || (props['data-show-copy'] === undefined && quoteStyle.showCopyButton);
71
+
72
+ const heightVal = style?.height || quoteStyle.height;
73
+ const isSmallHeight = heightVal !== 'auto' && parseInt(String(heightVal)) < 40;
74
+ const buttonPosition = isSmallHeight ? 'top-1/2 -translate-y-1/2' : 'top-2';
75
+
76
+ return (
77
+ <div className="relative group mb-4">
78
+ <blockquote style={containerStyle} className="quote-block" {...props}>
79
+ {children}
80
+ </blockquote>
81
+ <div className={`absolute right-2 flex gap-2 transition-opacity duration-200 ${isSmallHeight ? 'top-1/2 -translate-y-1/2' : 'top-2'} opacity-0 group-hover:opacity-100`}>
82
+ {showCopyButton && (
83
+ <CopyButton
84
+ text={quoteText}
85
+ className=""
86
+ />
87
+ )}
88
+ </div>
89
+ </div>
90
+ );
91
+ };
components/QuoteComponent.tsx ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useState, useRef, useEffect } from 'react';
2
+ import { NodeViewWrapper, NodeViewContent, NodeViewProps } from '@tiptap/react';
3
+ import { Copy, Check, Download, ChevronDown, ChevronUp } from 'lucide-react';
4
+ import { DownloadButton } from './DownloadButton';
5
+
6
+ export const QuoteComponent: React.FC<NodeViewProps> = (props) => {
7
+ const [copied, setCopied] = useState(false);
8
+ const [isManualExpanded, setIsManualExpanded] = useState(false);
9
+ const { node } = props;
10
+ const { attrs } = node;
11
+ const contentRef = useRef<HTMLDivElement>(null);
12
+ const [contentHeight, setContentHeight] = useState<number>(0);
13
+
14
+ useEffect(() => {
15
+ if (contentRef.current) {
16
+ setContentHeight(contentRef.current.scrollHeight);
17
+ }
18
+
19
+ const handleResize = () => {
20
+ if (contentRef.current) {
21
+ setContentHeight(contentRef.current.scrollHeight);
22
+ }
23
+ };
24
+
25
+ window.addEventListener('resize', handleResize);
26
+ return () => window.removeEventListener('resize', handleResize);
27
+ }, [node.textContent, isManualExpanded]);
28
+
29
+ const toggleExpand = () => {
30
+ setIsManualExpanded(!isManualExpanded);
31
+ };
32
+
33
+ const handleCopy = () => {
34
+ const text = node.textContent;
35
+ navigator.clipboard.writeText(text).then(() => {
36
+ setCopied(true);
37
+ setTimeout(() => setCopied(false), 2000);
38
+ });
39
+ };
40
+
41
+ const handleDownload = () => {
42
+ const text = node.textContent;
43
+ const element = document.createElement("a");
44
+ const file = new Blob([text], { type: 'text/plain' });
45
+ element.href = URL.createObjectURL(file);
46
+ element.download = 'cita.txt';
47
+ document.body.appendChild(element);
48
+ element.click();
49
+ document.body.removeChild(element);
50
+ };
51
+
52
+ // Construct dynamic styles from attributes
53
+ const dynamicStyles: React.CSSProperties = {
54
+ borderLeftColor: attrs.borderColor || 'gray',
55
+ borderLeftWidth: attrs.borderWidth || '4px',
56
+ backgroundColor: attrs.backgroundColor || 'transparent',
57
+ color: attrs.textColor || 'inherit',
58
+ padding: attrs.padding || '4px',
59
+ fontSize: attrs.fontSize || 'inherit',
60
+ borderRadius: attrs.borderRadius || '0px',
61
+ width: attrs.width || '100%',
62
+ minHeight: attrs.height || 'auto',
63
+ fontFamily: attrs.isCodeFont ? 'monospace' : (attrs.fontFamily || 'inherit'),
64
+ fontStyle: attrs.italic ? 'italic' : 'normal',
65
+ borderLeftStyle: 'solid', // Ensure border style is solid
66
+ wordBreak: 'break-word',
67
+ display: 'flex',
68
+ flexDirection: 'column',
69
+ justifyContent: 'center',
70
+ position: 'relative', // Ensure relative positioning for absolute children
71
+ lineHeight: '1.5', // Enforce consistent line height
72
+ };
73
+
74
+ const handleClick = (e: React.MouseEvent) => {
75
+ if (e.detail === 3 && props.editor.isEditable) {
76
+ e.preventDefault();
77
+ const event = new CustomEvent('block-triple-click', {
78
+ detail: { type: 'quote', pos: props.getPos() },
79
+ bubbles: true
80
+ });
81
+ props.editor.view.dom.dispatchEvent(event);
82
+ }
83
+ };
84
+
85
+ const isEditing = props.editor.isEditable;
86
+ const isCollapsed = attrs.collapsible && !isManualExpanded;
87
+
88
+ return (
89
+ <NodeViewWrapper
90
+ style={dynamicStyles}
91
+ className="group my-4 rounded-sm transition-all [&_p]:m-0"
92
+ onClick={handleClick}
93
+ >
94
+ {(attrs.showCopyButton || attrs.showDownloadButton) && (
95
+ <div className="absolute top-2 right-2 z-10 flex gap-2">
96
+ {attrs.showCopyButton && (
97
+ <button
98
+ onClick={handleCopy}
99
+ contentEditable={false} // Important: prevent editor focus issues
100
+ className="p-1 bg-zinc-800/50 rounded text-zinc-300 hover:text-white transition-all backdrop-blur-sm"
101
+ title="Copiar texto"
102
+ >
103
+ {copied ? <Check size={14} /> : <Copy size={14} />}
104
+ </button>
105
+ )}
106
+ {attrs.showDownloadButton && (
107
+ <button
108
+ onClick={handleDownload}
109
+ contentEditable={false}
110
+ className="p-1 bg-zinc-800/50 rounded text-zinc-300 hover:text-white transition-all backdrop-blur-sm"
111
+ title="Descargar"
112
+ >
113
+ <Download size={14} />
114
+ </button>
115
+ )}
116
+ </div>
117
+ )}
118
+
119
+ {/* --- Contenedor de Contenido con Lógica de Colapsado --- */}
120
+ <div
121
+ ref={contentRef}
122
+ style={{
123
+ // Si está colapsado, forzamos una altura máxima (aprox 3 líneas)
124
+ // Si NO es colapsable (feature disabled), usamos 'none' para que crezca automático
125
+ // Si es colapsable pero expandido, usamos la altura calculada para animar
126
+ maxHeight: isCollapsed
127
+ ? '4.5em'
128
+ : (attrs.collapsible ? `${contentHeight}px` : 'none'),
129
+ overflow: 'hidden',
130
+ position: 'relative',
131
+ transition: 'max-height 0.5s cubic-bezier(0.4, 0, 0.2, 1)', // Smooth slide animation
132
+ // Opcional: Un pequeño gradiente para suavizar el corte si está colapsado
133
+ maskImage: isCollapsed ? 'linear-gradient(to bottom, black 60%, transparent 100%)' : 'none',
134
+ WebkitMaskImage: isCollapsed ? 'linear-gradient(to bottom, black 60%, transparent 100%)' : 'none'
135
+ }}
136
+ >
137
+ <NodeViewContent />
138
+ </div>
139
+
140
+ {/* --- Botón de Leer Más (Solo Icono) --- */}
141
+ {attrs.collapsible && (
142
+ <div className="mt-1 flex justify-end">
143
+ <button
144
+ onClick={toggleExpand}
145
+ contentEditable={false} // ¡CRUCIAL PARA QUE FUNCIONE EL CLIC!
146
+ className="text-zinc-400 hover:text-white transition-colors cursor-pointer select-none p-1"
147
+ title={isManualExpanded ? "Contraer" : "Expandir"}
148
+ >
149
+ {isManualExpanded ? (
150
+ <ChevronUp size={16} />
151
+ ) : (
152
+ <ChevronDown size={16} />
153
+ )}
154
+ </button>
155
+ </div>
156
+ )}
157
+ </NodeViewWrapper>
158
+ );
159
+ };
components/StyleSettingsPanel.tsx ADDED
@@ -0,0 +1,817 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React from 'react';
2
+ import { Settings, X, Check, Save } from 'lucide-react';
3
+ import { StyleConfig } from '../services/codeStyleService';
4
+ import { CustomBlockquote } from './CustomBlockquote';
5
+
6
+ interface StyleSettingsPanelProps {
7
+ styleConfig: StyleConfig;
8
+ onUpdateConfig: (newConfig: StyleConfig) => void;
9
+ activeTab: 'code' | 'quote' | 'link' | 'general' | 'button' | 'codeblock';
10
+ onTabChange: (tab: 'code' | 'quote' | 'link' | 'general' | 'button' | 'codeblock') => void;
11
+
12
+ onClose: () => void;
13
+ onConfirm?: (config: StyleConfig) => void;
14
+ previewContent?: string;
15
+ hideTabs?: boolean;
16
+ cardStyle?: 'bordered' | 'transparent' | 'filled';
17
+ onCardStyleChange?: (style: 'bordered' | 'transparent' | 'filled') => void;
18
+ }
19
+
20
+ export const StyleSettingsPanel: React.FC<StyleSettingsPanelProps> = ({
21
+ styleConfig,
22
+ onUpdateConfig,
23
+ activeTab,
24
+ onTabChange,
25
+ onClose,
26
+ onConfirm,
27
+ previewContent,
28
+ hideTabs = false,
29
+ cardStyle,
30
+ onCardStyleChange
31
+ }) => {
32
+ console.log('[StyleSettingsPanel] Render. onCardStyleChange present?', !!onCardStyleChange, 'activeTab:', activeTab, 'cardStyle:', cardStyle);
33
+
34
+ const [localConfig, setLocalConfig] = React.useState<StyleConfig>(styleConfig);
35
+
36
+ // Update local config when prop changes, but only if not dirty?
37
+ // Actually, usually we want to reset if the prop changes from outside.
38
+ React.useEffect(() => {
39
+ setLocalConfig(styleConfig);
40
+ }, [styleConfig]);
41
+
42
+ if (!localConfig || !localConfig.general || !localConfig.quote || !localConfig.code || !localConfig.button) {
43
+ return null;
44
+ }
45
+
46
+ const rgbToHex = (rgba: string): string => {
47
+ const match = rgba.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
48
+ if (!match) return '#555555';
49
+ const r = parseInt(match[1]);
50
+ const g = parseInt(match[2]);
51
+ const b = parseInt(match[3]);
52
+ return '#' + [r, g, b].map(x => {
53
+ const hex = x.toString(16);
54
+ return hex.length === 1 ? '0' + hex : hex;
55
+ }).join('');
56
+ };
57
+
58
+ const handleQuoteBgColorChange = (color: string) => {
59
+ // Extract current opacity from current bg color
60
+ const currentBg = localConfig.quote.bgColor;
61
+ let opacity = 1;
62
+ const rgbaMatch = currentBg.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);
63
+ if (rgbaMatch && rgbaMatch[4]) {
64
+ opacity = parseFloat(rgbaMatch[4]);
65
+ }
66
+
67
+ const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(color);
68
+ if (result) {
69
+ const r = parseInt(result[1], 16);
70
+ const g = parseInt(result[2], 16);
71
+ const b = parseInt(result[3], 16);
72
+ const newBgColor = `rgba(${r}, ${g}, ${b}, ${opacity})`;
73
+
74
+ setLocalConfig({
75
+ ...localConfig,
76
+ quote: { ...localConfig.quote, bgColor: newBgColor }
77
+ });
78
+ }
79
+ };
80
+
81
+ const handleQuoteOpacityChange = (opacity: number) => {
82
+ const currentBg = localConfig.quote.bgColor;
83
+ const rgbaMatch = currentBg.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
84
+
85
+ let r = 0, g = 0, b = 0;
86
+
87
+ if (rgbaMatch) {
88
+ r = parseInt(rgbaMatch[1]);
89
+ g = parseInt(rgbaMatch[2]);
90
+ b = parseInt(rgbaMatch[3]);
91
+ } else {
92
+ // Fallback if it was hex or something else, though we try to keep it rgba
93
+ // Try to parse hex if needed, or default to gray
94
+ r = 85; g = 85; b = 85;
95
+ }
96
+
97
+ const newBgColor = `rgba(${r}, ${g}, ${b}, ${opacity})`;
98
+ setLocalConfig({
99
+ ...localConfig,
100
+ quote: { ...localConfig.quote, bgColor: newBgColor }
101
+ });
102
+ };
103
+
104
+ const getQuoteOpacity = (): number => {
105
+ const match = localConfig.quote.bgColor.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);
106
+ if (match && match[4]) {
107
+ return parseFloat(match[4]);
108
+ }
109
+ return 1;
110
+ };
111
+
112
+
113
+ return (
114
+ <div className="flex flex-col h-full overflow-hidden">
115
+ <div className="p-4 border-b border-white/5 bg-white/5 flex items-center justify-between">
116
+ <h3 className="text-white font-bold flex items-center gap-2 text-sm">
117
+ <Settings size={16} className="text-primary" />
118
+ Configuración de Estilos
119
+ </h3>
120
+ <button
121
+ type="button"
122
+ onClick={onClose}
123
+ className="text-gray-500 hover:text-white transition-colors"
124
+ >
125
+ <X size={16} />
126
+ </button>
127
+ </div>
128
+
129
+ {!hideTabs && (
130
+ <div className="flex border-b border-white/5 overflow-x-auto custom-scrollbar">
131
+ <button
132
+ onClick={() => onTabChange('general')}
133
+ className={`flex-1 px-4 py-3 text-sm font-medium transition-colors whitespace-nowrap ${activeTab === 'general'
134
+ ? 'bg-primary/10 text-primary border-b-2 border-primary'
135
+ : 'text-gray-400 hover:text-white hover:bg-white/5'
136
+ }`}
137
+ >
138
+ General
139
+ </button>
140
+ <button
141
+ onClick={() => onTabChange('code')}
142
+ className={`flex-1 px-4 py-3 text-sm font-medium transition-colors whitespace-nowrap ${activeTab === 'code'
143
+ ? 'bg-primary/10 text-primary border-b-2 border-primary'
144
+ : 'text-gray-400 hover:text-white hover:bg-white/5'
145
+ }`}
146
+ >
147
+ Código
148
+ </button>
149
+ <button
150
+ onClick={() => onTabChange('codeblock')}
151
+ className={`flex-1 px-4 py-3 text-sm font-medium transition-colors whitespace-nowrap ${activeTab === 'codeblock'
152
+ ? 'bg-primary/10 text-primary border-b-2 border-primary'
153
+ : 'text-gray-400 hover:text-white hover:bg-white/5'
154
+ }`}
155
+ >
156
+ Bloque de Código
157
+ </button>
158
+ <button
159
+ onClick={() => onTabChange('quote')}
160
+ className={`flex-1 px-4 py-3 text-sm font-medium transition-colors whitespace-nowrap ${activeTab === 'quote'
161
+ ? 'bg-primary/10 text-primary border-b-2 border-primary'
162
+ : 'text-gray-400 hover:text-white hover:bg-white/5'
163
+ }`}
164
+ >
165
+ Citas
166
+ </button>
167
+ <button
168
+ onClick={() => onTabChange('link')}
169
+ className={`flex-1 px-4 py-3 text-sm font-medium transition-colors whitespace-nowrap ${activeTab === 'link'
170
+ ? 'bg-primary/10 text-primary border-b-2 border-primary'
171
+ : 'text-gray-400 hover:text-white hover:bg-white/5'
172
+ }`}
173
+ >
174
+ Enlaces
175
+ </button>
176
+ <button
177
+ onClick={() => onTabChange('button')}
178
+ className={`flex-1 px-4 py-3 text-sm font-medium transition-colors whitespace-nowrap ${activeTab === 'button'
179
+ ? 'bg-primary/10 text-primary border-b-2 border-primary'
180
+ : 'text-gray-400 hover:text-white hover:bg-white/5'
181
+ }`}
182
+ >
183
+ Botones
184
+ </button>
185
+ </div>
186
+ )}
187
+
188
+ <div className="overflow-y-auto flex-1 p-5 space-y-5 custom-scrollbar pb-10">
189
+
190
+
191
+ {activeTab === 'general' && (
192
+ <div className="space-y-6">
193
+ {/* Card Style Config */}
194
+ <div className="bg-white/5 rounded-lg p-4 border border-white/5">
195
+ <h4 className="text-sm font-medium text-white mb-2">Estilo de Tarjeta</h4>
196
+ <p className="text-xs text-gray-400 mb-4">
197
+ Personaliza la apariencia de esta tarjeta.
198
+ </p>
199
+
200
+ {!onCardStyleChange && (
201
+ <div className="mb-3 p-2 bg-yellow-500/10 border border-yellow-500/20 rounded text-xs text-yellow-500">
202
+ Esta opción no está disponible en este contexto.
203
+ </div>
204
+ )}
205
+
206
+ <div className="grid grid-cols-1 gap-3">
207
+ <label className={`flex items-center justify-between p-3 rounded-lg border transition-all ${!onCardStyleChange ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'} ${cardStyle === 'bordered'
208
+ ? 'bg-primary/10 border-primary'
209
+ : 'bg-black/20 border-white/5 hover:bg-white/5'
210
+ }`}>
211
+ <div className="flex flex-col">
212
+ <span className={`text-sm font-medium ${cardStyle === 'bordered' ? 'text-white' : 'text-gray-300'}`}>Borde y Sin Fondo</span>
213
+ <span className="text-[10px] text-gray-500">Solo borde visible, fondo transparente.</span>
214
+ </div>
215
+ <input
216
+ type="radio"
217
+ name="cardStyle"
218
+ value="bordered"
219
+ checked={cardStyle === 'bordered'}
220
+ onChange={() => onCardStyleChange && onCardStyleChange('bordered')}
221
+ disabled={!onCardStyleChange}
222
+ className="w-4 h-4 accent-primary"
223
+ />
224
+ </label>
225
+
226
+ <label className={`flex items-center justify-between p-3 rounded-lg border transition-all ${!onCardStyleChange ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'} ${cardStyle === 'transparent'
227
+ ? 'bg-primary/10 border-primary'
228
+ : 'bg-black/20 border-white/5 hover:bg-white/5'
229
+ }`}>
230
+ <div className="flex flex-col">
231
+ <span className={`text-sm font-medium ${cardStyle === 'transparent' ? 'text-white' : 'text-gray-300'}`}>Sin Fondo</span>
232
+ <span className="text-[10px] text-gray-500">Completamente transparente, sin borde.</span>
233
+ </div>
234
+ <input
235
+ type="radio"
236
+ name="cardStyle"
237
+ value="transparent"
238
+ checked={cardStyle === 'transparent'}
239
+ onChange={() => onCardStyleChange && onCardStyleChange('transparent')}
240
+ disabled={!onCardStyleChange}
241
+ className="w-4 h-4 accent-primary"
242
+ />
243
+ </label>
244
+
245
+ <label className={`flex items-center justify-between p-3 rounded-lg border transition-all ${!onCardStyleChange ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'} ${cardStyle === 'filled'
246
+ ? 'bg-primary/10 border-primary'
247
+ : 'bg-black/20 border-white/5 hover:bg-white/5'
248
+ }`}>
249
+ <div className="flex flex-col">
250
+ <span className={`text-sm font-medium ${cardStyle === 'filled' ? 'text-white' : 'text-gray-300'}`}>Con Fondo</span>
251
+ <span className="text-[10px] text-gray-500">Fondo sólido visible.</span>
252
+ </div>
253
+ <input
254
+ type="radio"
255
+ name="cardStyle"
256
+ value="filled"
257
+ checked={cardStyle === 'filled'}
258
+ onChange={() => onCardStyleChange && onCardStyleChange('filled')}
259
+ disabled={!onCardStyleChange}
260
+ className="w-4 h-4 accent-primary"
261
+ />
262
+ </label>
263
+ </div>
264
+ </div>
265
+
266
+
267
+ </div>
268
+ )}
269
+
270
+ {activeTab === 'code' && (
271
+ <>
272
+ {/* Code tab content omitted for brevity as we are focusing on Quote tab improvements requested by user.
273
+ In a real scenario we would keep it or refactor.
274
+ For this task, I will assume we keep the existing code tab logic but using localConfig.
275
+ However, since I'm replacing the whole component body, I need to be careful.
276
+ The user asked to update the component. I should probably keep the code tab functional.
277
+ */}
278
+ <div className="space-y-2">
279
+ <label className="block text-[10px] text-gray-500 uppercase tracking-widest font-semibold">Vista Previa</label>
280
+ <div className="bg-[#121212] rounded-lg p-4 border border-white/5 text-sm text-gray-300 leading-relaxed">
281
+ {previewContent ? (
282
+ <code style={{
283
+ backgroundColor: localConfig.code.bgColor,
284
+ color: localConfig.code.textColor,
285
+ fontSize: localConfig.code.fontSize,
286
+ borderRadius: localConfig.code.borderRadius,
287
+ padding: '0px 2px',
288
+ minWidth: localConfig.code.width !== 'auto' ? localConfig.code.width : undefined,
289
+ maxWidth: '100%',
290
+ minHeight: localConfig.code.height !== 'auto' ? localConfig.code.height : undefined,
291
+ display: 'inline-flex',
292
+ alignItems: 'center',
293
+ justifyContent: 'center',
294
+ border: '1px solid rgba(255,255,255,0.05)',
295
+ fontFamily: localConfig.code.fontFamily || "'Consolas', 'Monaco', monospace",
296
+ lineHeight: 1,
297
+ margin: '0 1px'
298
+ }}>{previewContent}</code>
299
+ ) : (
300
+ <span>Vista previa de código...</span>
301
+ )}
302
+ </div>
303
+ </div>
304
+
305
+ <div className="space-y-4 mt-4">
306
+ <div className="flex items-center justify-between p-3 bg-white/5 rounded-lg border border-white/5">
307
+ <div className="flex flex-col">
308
+ <span className="text-sm text-gray-300 font-medium">Mostrar fondo</span>
309
+ <span className="text-[10px] text-gray-500">Aplica solo a nuevos bloques de código</span>
310
+ </div>
311
+ <button
312
+ onClick={() => setLocalConfig({
313
+ ...localConfig,
314
+ code: { ...localConfig.code, showBackground: !localConfig.code.showBackground }
315
+ })}
316
+ className={`w-12 h-6 rounded-full transition-colors relative ${localConfig.code.showBackground ? 'bg-primary' : 'bg-white/10'}`}
317
+ >
318
+ <span className={`absolute top-1 left-1 w-4 h-4 rounded-full bg-white transition-transform ${localConfig.code.showBackground ? 'translate-x-6' : 'translate-x-0'}`} />
319
+ </button>
320
+ </div>
321
+ </div>
322
+ <div className="text-gray-500 text-xs italic mt-4">Configuración para código inline.</div>
323
+ </>
324
+ )}
325
+
326
+ {activeTab === 'codeblock' && (
327
+ <>
328
+ {console.log('StyleSettingsPanel Render. onCardStyleChange:', !!onCardStyleChange, onCardStyleChange)}
329
+ <div className="space-y-4 mt-4">
330
+ <h4 className="text-sm font-medium text-white mb-2">Comportamiento de Bloques de Código</h4>
331
+ <div className="flex items-center justify-between p-3 bg-white/5 rounded-lg border border-white/5">
332
+ <div className="flex flex-col">
333
+ <span className="text-sm text-gray-300 font-medium">Colapsar texto largo</span>
334
+ <span className="text-[10px] text-gray-500">Aplica solo a nuevos bloques de código</span>
335
+ </div>
336
+ <button
337
+ onClick={() => setLocalConfig({
338
+ ...localConfig,
339
+ code: { ...localConfig.code, collapsible: !localConfig.code.collapsible }
340
+ })}
341
+ className={`w-12 h-6 rounded-full transition-colors relative ${localConfig.code.collapsible ? 'bg-primary' : 'bg-white/10'}`}
342
+ >
343
+ <span className={`absolute top-1 left-1 w-4 h-4 rounded-full bg-white transition-transform ${localConfig.code.collapsible ? 'translate-x-6' : 'translate-x-0'}`} />
344
+ </button>
345
+ </div>
346
+
347
+
348
+ <div className="flex items-center justify-between p-3 bg-white/5 rounded-lg border border-white/5">
349
+ <div className="flex flex-col">
350
+ <span className="text-sm text-gray-300 font-medium">Números de línea</span>
351
+ <span className="text-[10px] text-gray-500">Mostrar números de línea en el margen izquierdo</span>
352
+ </div>
353
+ <button
354
+ onClick={() => setLocalConfig({
355
+ ...localConfig,
356
+ code: { ...localConfig.code, showLineNumbers: !localConfig.code.showLineNumbers }
357
+ })}
358
+ className={`w-12 h-6 rounded-full transition-colors relative ${localConfig.code.showLineNumbers ? 'bg-primary' : 'bg-white/10'}`}
359
+ >
360
+ <span className={`absolute top-1 left-1 w-4 h-4 rounded-full bg-white transition-transform ${localConfig.code.showLineNumbers ? 'translate-x-6' : 'translate-x-0'}`} />
361
+ </button>
362
+ </div>
363
+
364
+ <div className="flex items-center justify-between p-3 bg-white/5 rounded-lg border border-white/5">
365
+ <div className="flex flex-col">
366
+ <span className="text-sm text-gray-300 font-medium">Ajuste de línea</span>
367
+ <span className="text-[10px] text-gray-500">Ver todo el código sin scroll horizontal</span>
368
+ </div>
369
+ <button
370
+ onClick={() => setLocalConfig({
371
+ ...localConfig,
372
+ code: { ...localConfig.code, wrapText: !localConfig.code.wrapText }
373
+ })}
374
+ className={`w-12 h-6 rounded-full transition-colors relative ${localConfig.code.wrapText ? 'bg-primary' : 'bg-white/10'}`}
375
+ >
376
+ <span className={`absolute top-1 left-1 w-4 h-4 rounded-full bg-white transition-transform ${localConfig.code.wrapText ? 'translate-x-6' : 'translate-x-0'}`} />
377
+ </button>
378
+ </div>
379
+ </div>
380
+ <div className="text-gray-500 text-xs italic mt-4">Configuración para bloques de código largos.</div>
381
+ </>
382
+ )}
383
+
384
+ {activeTab === 'quote' && (
385
+ <>
386
+ <div className="space-y-2">
387
+ <label className="block text-[10px] text-gray-500 uppercase tracking-widest font-semibold">Vista Previa</label>
388
+ <div className="bg-[#121212] rounded-lg p-4 border border-white/5 text-sm text-gray-300 leading-relaxed">
389
+ <CustomBlockquote
390
+ key={JSON.stringify(localConfig.quote)}
391
+ style={{
392
+ backgroundColor: localConfig.quote.bgColor,
393
+ color: localConfig.quote.textColor,
394
+ borderLeftWidth: localConfig.quote.borderWidth,
395
+ borderLeftStyle: 'solid',
396
+ borderLeftColor: localConfig.quote.borderColor,
397
+ padding: localConfig.quote.padding,
398
+ fontSize: localConfig.quote.fontSize,
399
+ borderRadius: localConfig.quote.borderRadius,
400
+ fontFamily: localConfig.quote.isCodeFont ? 'monospace' : (localConfig.quote.fontFamily || 'inherit'),
401
+ fontStyle: localConfig.quote.italic ? 'italic' : 'normal',
402
+ width: localConfig.quote.width !== 'auto' ? localConfig.quote.width : '100%',
403
+ maxWidth: '100%',
404
+ minHeight: localConfig.quote.height !== 'auto' ? localConfig.quote.height : undefined,
405
+ overflow: 'visible',
406
+ position: 'relative',
407
+ marginBottom: '1rem',
408
+ display: 'flex',
409
+ flexDirection: 'column',
410
+ justifyContent: 'center',
411
+ wordBreak: 'break-word'
412
+ }}
413
+ data-show-copy={localConfig.quote.showCopyButton}
414
+ data-show-download={localConfig.quote.showDownloadButton}
415
+ >
416
+ {previewContent || 'Esta es una cita de ejemplo que muestra el estilo configurado.'}
417
+ </CustomBlockquote>
418
+ </div>
419
+ </div>
420
+
421
+ <div className="grid grid-cols-2 gap-4">
422
+ <div>
423
+ <label className="block text-[10px] text-gray-500 uppercase tracking-widest font-semibold mb-2">Color Texto</label>
424
+ <div className="flex items-center gap-2 bg-white/5 p-1 rounded-lg border border-white/5">
425
+ <input
426
+ type="color"
427
+ value={localConfig.quote.textColor}
428
+ onChange={(e) => setLocalConfig({
429
+ ...localConfig,
430
+ quote: { ...localConfig.quote, textColor: e.target.value }
431
+ })}
432
+ className="w-8 h-8 rounded cursor-pointer bg-transparent border-none p-0"
433
+ />
434
+ <span className="text-xs text-gray-400 font-mono">{localConfig.quote.textColor}</span>
435
+ </div>
436
+ </div>
437
+ <div>
438
+ <label className="block text-[10px] text-gray-500 uppercase tracking-widest font-semibold mb-2">Color Fondo</label>
439
+ <div className="flex items-center gap-2 bg-white/5 p-1 rounded-lg border border-white/5">
440
+ <input
441
+ type="color"
442
+ value={rgbToHex(localConfig.quote.bgColor)}
443
+ onChange={(e) => handleQuoteBgColorChange(e.target.value)}
444
+ className="w-8 h-8 rounded cursor-pointer bg-transparent border-none p-0"
445
+ />
446
+ <span className="text-xs text-gray-400 font-mono">{rgbToHex(localConfig.quote.bgColor)}</span>
447
+ </div>
448
+ </div>
449
+ </div>
450
+
451
+ <div>
452
+ <div className="flex justify-between mb-2">
453
+ <label className="text-[10px] text-gray-500 uppercase tracking-widest font-semibold">Opacidad Fondo</label>
454
+ <span className="text-xs text-primary font-mono">{Math.round(getQuoteOpacity() * 100)}%</span>
455
+ </div>
456
+ <input
457
+ type="range"
458
+ min="0"
459
+ max="1"
460
+ step="0.01"
461
+ value={getQuoteOpacity()}
462
+ onChange={(e) => handleQuoteOpacityChange(parseFloat(e.target.value))}
463
+ className="w-full h-1 bg-white/10 rounded-lg appearance-none cursor-pointer accent-primary"
464
+ />
465
+ </div>
466
+
467
+ <div className="grid grid-cols-2 gap-4">
468
+ <div>
469
+ <label className="block text-[10px] text-gray-500 uppercase tracking-widest font-semibold mb-2">Color Borde</label>
470
+ <div className="flex items-center gap-2 bg-white/5 p-1 rounded-lg border border-white/5">
471
+ <input
472
+ type="color"
473
+ value={localConfig.quote.borderColor}
474
+ onChange={(e) => setLocalConfig({
475
+ ...localConfig,
476
+ quote: { ...localConfig.quote, borderColor: e.target.value }
477
+ })}
478
+ className="w-8 h-8 rounded cursor-pointer bg-transparent border-none p-0"
479
+ />
480
+ <span className="text-xs text-gray-400 font-mono">{localConfig.quote.borderColor}</span>
481
+ </div>
482
+ </div>
483
+ <div>
484
+ <div className="flex justify-between mb-2">
485
+ <label className="text-[10px] text-gray-500 uppercase tracking-widest font-semibold">Grosor Borde</label>
486
+ <span className="text-xs text-primary font-mono">{localConfig.quote.borderWidth}</span>
487
+ </div>
488
+ <input
489
+ type="range"
490
+ min="0"
491
+ max="20"
492
+ value={parseInt(localConfig.quote.borderWidth) || 0}
493
+ onChange={(e) => {
494
+ const val = parseInt(e.target.value);
495
+ setLocalConfig({
496
+ ...localConfig,
497
+ quote: { ...localConfig.quote, borderWidth: `${val}px` }
498
+ });
499
+ }}
500
+ className="w-full h-1 bg-white/10 rounded-lg appearance-none cursor-pointer accent-primary"
501
+ />
502
+ </div>
503
+ </div>
504
+
505
+ <div>
506
+ <div className="flex justify-between mb-2">
507
+ <label className="text-[10px] text-gray-500 uppercase tracking-widest font-semibold">Padding</label>
508
+ <span className="text-xs text-primary font-mono">{localConfig.quote.padding}</span>
509
+ </div>
510
+ <input
511
+ type="range"
512
+ min="0"
513
+ max="50"
514
+ value={parseInt(localConfig.quote.padding) || 0}
515
+ onChange={(e) => {
516
+ const val = parseInt(e.target.value);
517
+ setLocalConfig({
518
+ ...localConfig,
519
+ quote: { ...localConfig.quote, padding: `${val}px` }
520
+ });
521
+ }}
522
+ className="w-full h-1 bg-white/10 rounded-lg appearance-none cursor-pointer accent-primary"
523
+ />
524
+ </div>
525
+
526
+ <div>
527
+ <div className="flex justify-between mb-2">
528
+ <label className="text-[10px] text-gray-500 uppercase tracking-widest font-semibold">Borde Redondeado</label>
529
+ <span className="text-xs text-primary font-mono">{localConfig.quote.borderRadius}</span>
530
+ </div>
531
+ <input
532
+ type="range"
533
+ min="0"
534
+ max="20"
535
+ value={parseInt(localConfig.quote.borderRadius) || 0}
536
+ onChange={(e) => {
537
+ const val = parseInt(e.target.value);
538
+ setLocalConfig({
539
+ ...localConfig,
540
+ quote: { ...localConfig.quote, borderRadius: `${val}px` }
541
+ });
542
+ }}
543
+ className="w-full h-1 bg-white/10 rounded-lg appearance-none cursor-pointer accent-primary"
544
+ />
545
+ </div>
546
+
547
+
548
+
549
+ <div>
550
+ <div className="flex justify-between mb-2">
551
+ <label className="text-[10px] text-gray-500 uppercase tracking-widest font-semibold">Tamaño Fuente</label>
552
+ <span className="text-xs text-primary font-mono">{localConfig.quote.fontSize}</span>
553
+ </div>
554
+ <input
555
+ type="range"
556
+ min="0.5"
557
+ max="2"
558
+ step="0.05"
559
+ value={parseFloat(localConfig.quote.fontSize) || 1}
560
+ onChange={(e) => {
561
+ const val = parseFloat(e.target.value);
562
+ setLocalConfig({
563
+ ...localConfig,
564
+ quote: { ...localConfig.quote, fontSize: `${val}em` }
565
+ });
566
+ }}
567
+ className="w-full h-1 bg-white/10 rounded-lg appearance-none cursor-pointer accent-primary"
568
+ />
569
+ </div>
570
+
571
+ <div className="grid grid-cols-2 gap-4">
572
+ <div>
573
+ <div className="flex justify-between mb-2">
574
+ <label className="text-[10px] text-gray-500 uppercase tracking-widest font-semibold">Ancho</label>
575
+ <span className="text-xs text-primary font-mono">{localConfig.quote.width || '100%'}</span>
576
+ </div>
577
+ <input
578
+ type="range"
579
+ min="20"
580
+ max="100"
581
+ step="5"
582
+ value={parseInt(localConfig.quote.width) || 100}
583
+ onChange={(e) => setLocalConfig({
584
+ ...localConfig,
585
+ quote: { ...localConfig.quote, width: `${e.target.value}%` }
586
+ })}
587
+ className="w-full h-1 bg-white/10 rounded-lg appearance-none cursor-pointer accent-primary"
588
+ />
589
+ </div>
590
+ <div>
591
+ <div className="flex justify-between mb-2">
592
+ <label className="text-[10px] text-gray-500 uppercase tracking-widest font-semibold">Alto</label>
593
+ <span className="text-xs text-primary font-mono">{localConfig.quote.height === 'auto' ? 'Auto' : localConfig.quote.height}</span>
594
+ </div>
595
+ <input
596
+ type="range"
597
+ min="0"
598
+ max="500"
599
+ step="1"
600
+ value={localConfig.quote.height === 'auto' ? 0 : parseInt(localConfig.quote.height) || 0}
601
+ onChange={(e) => {
602
+ const val = parseInt(e.target.value);
603
+ setLocalConfig({
604
+ ...localConfig,
605
+ quote: { ...localConfig.quote, height: val === 0 ? 'auto' : `${val}px` }
606
+ });
607
+ }}
608
+ className="w-full h-1 bg-white/10 rounded-lg appearance-none cursor-pointer accent-primary"
609
+ />
610
+ </div>
611
+ </div>
612
+
613
+ <div className="grid grid-cols-2 gap-4">
614
+
615
+ <div className="flex items-center justify-between p-3 bg-white/5 rounded-lg border border-white/5">
616
+ <label className="text-sm text-gray-300 font-medium">Tipografía Código</label>
617
+ <button
618
+ onClick={() => setLocalConfig({
619
+ ...localConfig,
620
+ quote: { ...localConfig.quote, isCodeFont: !localConfig.quote.isCodeFont }
621
+ })}
622
+ className={`w-12 h-6 rounded-full transition-colors relative ${localConfig.quote.isCodeFont ? 'bg-primary' : 'bg-white/10'}`}
623
+ >
624
+ <span className={`absolute top-1 left-1 w-4 h-4 rounded-full bg-white transition-transform ${localConfig.quote.isCodeFont ? 'translate-x-6' : 'translate-x-0'}`} />
625
+ </button>
626
+ </div>
627
+ <div className="flex items-center justify-between p-3 bg-white/5 rounded-lg border border-white/5">
628
+ <label className="text-sm text-gray-300 font-medium">Botón Copiar</label>
629
+ <button
630
+ onClick={() => setLocalConfig({
631
+ ...localConfig,
632
+ quote: { ...localConfig.quote, showCopyButton: !localConfig.quote.showCopyButton }
633
+ })}
634
+ className={`w-12 h-6 rounded-full transition-colors relative ${localConfig.quote.showCopyButton ? 'bg-primary' : 'bg-white/10'}`}
635
+ >
636
+ <span className={`absolute top-1 left-1 w-4 h-4 rounded-full bg-white transition-transform ${localConfig.quote.showCopyButton ? 'translate-x-6' : 'translate-x-0'}`} />
637
+ </button>
638
+ </div>
639
+ <div className="flex items-center justify-between p-3 bg-white/5 rounded-lg border border-white/5">
640
+ <label className="text-sm text-gray-300 font-medium">Botón Descargar</label>
641
+ <button
642
+ onClick={() => setLocalConfig({
643
+ ...localConfig,
644
+ quote: { ...localConfig.quote, showDownloadButton: !localConfig.quote.showDownloadButton }
645
+ })}
646
+ className={`w-12 h-6 rounded-full transition-colors relative ${localConfig.quote.showDownloadButton ? 'bg-primary' : 'bg-white/10'}`}
647
+ >
648
+ <span className={`absolute top-1 left-1 w-4 h-4 rounded-full bg-white transition-transform ${localConfig.quote.showDownloadButton ? 'translate-x-6' : 'translate-x-0'}`} />
649
+ </button>
650
+ </div>
651
+ <div className="flex items-center justify-between p-3 bg-white/5 rounded-lg border border-white/5">
652
+ <label className="text-sm text-gray-300 font-medium">Colapsar texto largo</label>
653
+ <button
654
+ onClick={() => setLocalConfig({
655
+ ...localConfig,
656
+ quote: { ...localConfig.quote, collapsible: !localConfig.quote.collapsible }
657
+ })}
658
+ className={`w-12 h-6 rounded-full transition-colors relative ${localConfig.quote.collapsible ? 'bg-primary' : 'bg-white/10'}`}
659
+ >
660
+ <span className={`absolute top-1 left-1 w-4 h-4 rounded-full bg-white transition-transform ${localConfig.quote.collapsible ? 'translate-x-6' : 'translate-x-0'}`} />
661
+ </button>
662
+ </div>
663
+ </div>
664
+
665
+ </>
666
+ )}
667
+
668
+ {activeTab === 'link' && (
669
+ <div className="space-y-6">
670
+ <div className="bg-white/5 rounded-lg p-4 border border-white/5">
671
+ <h4 className="text-sm font-medium text-white mb-2">Comportamiento de Enlaces</h4>
672
+ <p className="text-xs text-gray-400 mb-4">
673
+ Configura cómo se comportan los enlaces al crearlos.
674
+ </p>
675
+
676
+ <div className="flex items-center justify-between p-3 bg-black/20 rounded-lg border border-white/5">
677
+ <div className="flex flex-col">
678
+ <span className="text-sm text-gray-200 font-medium">Subrayar enlaces por defecto</span>
679
+ <span className="text-[10px] text-gray-500">Si está desactivado, los nuevos enlaces no tendrán subrayado.</span>
680
+ </div>
681
+ <button
682
+ onClick={() => setLocalConfig({
683
+ ...localConfig,
684
+ link: { ...localConfig.link, underlineEnabled: !localConfig.link?.underlineEnabled }
685
+ })}
686
+ className={`w-12 h-6 rounded-full transition-colors relative ${localConfig.link?.underlineEnabled ? 'bg-primary' : 'bg-white/10'}`}
687
+ >
688
+ <span className={`absolute top-1 left-1 w-4 h-4 rounded-full bg-white transition-transform ${localConfig.link?.underlineEnabled ? 'translate-x-6' : 'translate-x-0'}`} />
689
+ </button>
690
+ </div>
691
+ </div>
692
+ </div>
693
+ )}
694
+
695
+ {activeTab === 'button' && (
696
+ <div className="space-y-6">
697
+ <div className="space-y-2">
698
+ <label className="block text-[10px] text-gray-500 uppercase tracking-widest font-semibold">Vista Previa</label>
699
+ <div className="bg-[#121212] rounded-lg p-8 border border-white/5 flex justify-center items-center">
700
+ <button
701
+ style={{
702
+ width: localConfig.button?.width === 'auto' ? 'auto' : localConfig.button?.width,
703
+ maxWidth: '100%', // Prevent overflow
704
+ height: localConfig.button?.height === 'auto' ? 'auto' : localConfig.button?.height,
705
+ backgroundColor: 'transparent',
706
+ color: localConfig.button?.backgroundColor,
707
+ borderRadius: localConfig.button?.borderRadius,
708
+ border: `1px solid ${localConfig.button?.backgroundColor}`,
709
+ boxShadow: `0 0 10px ${localConfig.button?.backgroundColor}40`,
710
+ padding: '8px 16px',
711
+ cursor: 'default'
712
+ }}
713
+ className="font-medium text-sm transition-all duration-200"
714
+ >
715
+ Botón de Ejemplo
716
+ </button>
717
+ </div>
718
+ </div>
719
+
720
+ <div className="grid grid-cols-2 gap-4">
721
+ <div>
722
+ <div className="flex justify-between mb-2">
723
+ <label className="text-[10px] text-gray-500 uppercase tracking-widest font-semibold">Ancho</label>
724
+ <span className="text-xs text-primary font-mono">{localConfig.button?.width || 'Auto'}</span>
725
+ </div>
726
+ <input
727
+ type="range"
728
+ min="0"
729
+ max="1000"
730
+ step="10"
731
+ value={localConfig.button?.width === 'auto' ? 0 : parseInt(localConfig.button?.width) || 0}
732
+ onChange={(e) => {
733
+ const val = parseInt(e.target.value);
734
+ setLocalConfig({
735
+ ...localConfig,
736
+ button: { ...localConfig.button, width: val === 0 ? 'auto' : `${val}px` }
737
+ });
738
+ }}
739
+ className="w-full h-1 bg-white/10 rounded-lg appearance-none cursor-pointer accent-primary"
740
+ />
741
+ </div>
742
+ <div>
743
+ <div className="flex justify-between mb-2">
744
+ <label className="text-[10px] text-gray-500 uppercase tracking-widest font-semibold">Alto</label>
745
+ <span className="text-xs text-primary font-mono">{localConfig.button?.height || 'Auto'}</span>
746
+ </div>
747
+ <input
748
+ type="range"
749
+ min="0"
750
+ max="100"
751
+ step="2"
752
+ value={localConfig.button?.height === 'auto' ? 0 : parseInt(localConfig.button?.height) || 0}
753
+ onChange={(e) => {
754
+ const val = parseInt(e.target.value);
755
+ setLocalConfig({
756
+ ...localConfig,
757
+ button: { ...localConfig.button, height: val === 0 ? 'auto' : `${val}px` }
758
+ });
759
+ }}
760
+ className="w-full h-1 bg-white/10 rounded-lg appearance-none cursor-pointer accent-primary"
761
+ />
762
+ </div>
763
+ </div>
764
+
765
+ <div className="grid grid-cols-2 gap-4">
766
+ <div>
767
+ <label className="block text-[10px] text-gray-500 uppercase tracking-widest font-semibold mb-2">Color Borde</label>
768
+ <div className="flex items-center gap-2 bg-white/5 p-1 rounded-lg border border-white/5">
769
+ <input
770
+ type="color"
771
+ value={localConfig.button?.backgroundColor || '#bb86fc'}
772
+ onChange={(e) => setLocalConfig({
773
+ ...localConfig,
774
+ button: { ...localConfig.button, backgroundColor: e.target.value }
775
+ })}
776
+ className="w-8 h-8 rounded cursor-pointer bg-transparent border-none p-0"
777
+ />
778
+ <span className="text-xs text-gray-400 font-mono">{localConfig.button?.backgroundColor}</span>
779
+ </div>
780
+ </div>
781
+ <div>
782
+ <label className="block text-[10px] text-gray-500 uppercase tracking-widest font-semibold mb-2">Color Texto</label>
783
+ <div className="flex items-center gap-2 bg-white/5 p-1 rounded-lg border border-white/5">
784
+ <input
785
+ type="color"
786
+ value={localConfig.button?.textColor || '#ffffff'}
787
+ onChange={(e) => setLocalConfig({
788
+ ...localConfig,
789
+ button: { ...localConfig.button, textColor: e.target.value }
790
+ })}
791
+ className="w-8 h-8 rounded cursor-pointer bg-transparent border-none p-0"
792
+ />
793
+ <span className="text-xs text-gray-400 font-mono">{localConfig.button?.textColor}</span>
794
+ </div>
795
+ </div>
796
+ </div>
797
+ </div>
798
+ )}
799
+ </div>
800
+
801
+ <div className="border-t border-white/10 p-4 bg-white/5">
802
+ <button
803
+ onClick={() => {
804
+ onUpdateConfig(localConfig);
805
+ if (onConfirm) onConfirm(localConfig);
806
+ onClose();
807
+ }}
808
+ className="w-full py-3 px-4 bg-purple-600 hover:bg-purple-700 text-white font-bold rounded-lg transition-colors flex items-center justify-center gap-2 shadow-lg"
809
+ >
810
+ <Save size={20} />
811
+ Guardar Configuración
812
+ </button>
813
+ </div>
814
+ </div>
815
+ );
816
+ };
817
+
components/TextFormatToolbar.tsx ADDED
@@ -0,0 +1,507 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useState, useEffect, useRef, forwardRef, useImperativeHandle } from 'react';
2
+ import {
3
+ Bold, Italic, List, ListOrdered, Quote, Code,
4
+ Type, Palette, Layout, Settings, X, Check, Copy,
5
+ AlignLeft, AlignCenter, AlignRight, Maximize2, Minimize2
6
+ } from 'lucide-react';
7
+ import {
8
+ DEFAULT_STYLE_CONFIG,
9
+ subscribeToStyleConfig,
10
+ saveStyleConfigToCloud,
11
+ type StyleConfig,
12
+ type CodeStyleConfig,
13
+ type QuoteStyleConfig
14
+ } from '../services/codeStyleService';
15
+ import { StyleSettingsPanel } from './StyleSettingsPanel';
16
+
17
+ interface TextFormatToolbarProps {
18
+ textareaRef: React.RefObject<HTMLTextAreaElement>;
19
+ onApplyFormat: (start: number, end: number, formatted: string) => void;
20
+ }
21
+
22
+ export interface TextFormatToolbarRef {
23
+ openSettings: (tab: 'code' | 'quote') => void;
24
+ syncStylesFromSelection: () => void;
25
+ }
26
+
27
+ type FormatType = 'bold' | 'italic' | 'code' | 'quote' | 'uppercase' | 'lowercase' | 'plain';
28
+ type SettingsTab = 'code' | 'quote' | 'general' | 'link';
29
+
30
+ export const TextFormatToolbar = forwardRef<TextFormatToolbarRef, TextFormatToolbarProps>(({ textareaRef, onApplyFormat }, ref) => {
31
+ const [selectedText, setSelectedText] = useState('');
32
+ const [selectedRange, setSelectedRange] = useState<{ start: number; end: number } | null>(null);
33
+ const [activeFormats, setActiveFormats] = useState<Set<FormatType>>(new Set());
34
+ const [showSettings, setShowSettings] = useState(false);
35
+ const [settingsTab, setSettingsTab] = useState<SettingsTab>('code');
36
+
37
+ const [localStyleConfig, setLocalStyleConfig] = useState<StyleConfig>(DEFAULT_STYLE_CONFIG);
38
+ // Estado temporal para la configuración (borrador)
39
+ const [tempStyleConfig, setTempStyleConfig] = useState<StyleConfig | null>(null);
40
+ const toolbarRef = useRef<HTMLDivElement>(null);
41
+
42
+ // Expose methods via ref
43
+ useImperativeHandle(ref, () => ({
44
+ openSettings: (tab) => {
45
+ setShowSettings(true);
46
+ setSettingsTab(tab);
47
+ // Inicializar el borrador con la configuración actual
48
+ setTempStyleConfig(localStyleConfig);
49
+ },
50
+ syncStylesFromSelection: () => {
51
+ checkSelectionFormat();
52
+ }
53
+ }));
54
+
55
+ useEffect(() => {
56
+ const unsubscribe = subscribeToStyleConfig((config) => {
57
+ setLocalStyleConfig(config);
58
+ });
59
+ return () => unsubscribe();
60
+ }, []);
61
+
62
+ // Usar tempStyleConfig si existe (modo edición), sino localStyleConfig
63
+ const styleConfig = tempStyleConfig || localStyleConfig;
64
+
65
+ // Helper to update style config (Draft logic)
66
+ const handleConfigUpdate = (newConfig: StyleConfig) => {
67
+ // Solo actualizamos el estado temporal, no aplicamos cambios al texto ni a la nube todavía
68
+ setTempStyleConfig(newConfig);
69
+ };
70
+
71
+ const handleConfirmSettings = () => {
72
+ if (!tempStyleConfig) return;
73
+
74
+ // Aplicar cambios permanentemente
75
+ setLocalStyleConfig(tempStyleConfig);
76
+
77
+ // Guardar en la nube y aplicar al texto seleccionado
78
+ const newConfig = tempStyleConfig;
79
+
80
+ const textarea = textareaRef.current;
81
+ if (!textarea) {
82
+ saveStyleConfigToCloud(newConfig);
83
+ setShowSettings(false);
84
+ setTempStyleConfig(null);
85
+ return;
86
+ }
87
+
88
+ const cursor = textarea.selectionStart;
89
+ const text = textarea.value;
90
+
91
+ let isInBlock = false;
92
+
93
+ // Check for Blockquote
94
+ const quoteRegex = /<blockquote[^>]*>([\s\S]*?)<\/blockquote>/g;
95
+ let match;
96
+ while ((match = quoteRegex.exec(text)) !== null) {
97
+ if (cursor >= match.index && cursor <= match.index + match[0].length) {
98
+ isInBlock = true;
99
+ const newStyle = getQuoteStyleString(newConfig.quote);
100
+ const openTagRegex = /<blockquote[^>]*>/;
101
+ const openTagMatch = openTagRegex.exec(match[0]);
102
+
103
+ if (openTagMatch) {
104
+ const newOpenTag = `<blockquote style="${newStyle}" data-show-copy="${newConfig.quote.showCopyButton}">`;
105
+ const newFullBlock = match[0].replace(openTagMatch[0], newOpenTag);
106
+ setTimeout(() => {
107
+ onApplyFormat(match.index, match.index + match[0].length, newFullBlock);
108
+ }, 0);
109
+ }
110
+ break;
111
+ }
112
+ }
113
+
114
+ // Check for Code if not in quote
115
+ if (!isInBlock) {
116
+ const codeRegex = /<code[^>]*>([\s\S]*?)<\/code>/g;
117
+ while ((match = codeRegex.exec(text)) !== null) {
118
+ if (cursor >= match.index && cursor <= match.index + match[0].length) {
119
+ isInBlock = true;
120
+ const newStyle = getCodeStyleString(newConfig.code);
121
+ const openTagRegex = /<code[^>]*>/;
122
+ const openTagMatch = openTagRegex.exec(match[0]);
123
+
124
+ if (openTagMatch) {
125
+ const newOpenTag = `<code style="${newStyle}">`;
126
+ const newFullBlock = match[0].replace(openTagMatch[0], newOpenTag);
127
+ setTimeout(() => {
128
+ onApplyFormat(match.index, match.index + match[0].length, newFullBlock);
129
+ }, 0);
130
+ }
131
+ break;
132
+ }
133
+ }
134
+ }
135
+
136
+ // If NOT in a block, update global config
137
+ if (!isInBlock) {
138
+ saveStyleConfigToCloud(newConfig);
139
+ }
140
+
141
+ setShowSettings(false);
142
+ setTempStyleConfig(null);
143
+ };
144
+
145
+ const handleCancelSettings = () => {
146
+ // Descartar cambios
147
+ setTempStyleConfig(null);
148
+ setShowSettings(false);
149
+ };
150
+
151
+ const checkSelectionFormat = () => {
152
+ // Placeholder for now, can be implemented to read styles from selection
153
+ // For now, double click just opens the settings
154
+ };
155
+
156
+ const updateSelectionState = () => {
157
+ const textarea = textareaRef.current;
158
+ if (!textarea) return;
159
+
160
+ const start = textarea.selectionStart;
161
+ const end = textarea.selectionEnd;
162
+ const text = textarea.value.substring(start, end);
163
+
164
+ setSelectedText(text);
165
+ setSelectedRange({ start, end });
166
+ };
167
+
168
+ useEffect(() => {
169
+ const textarea = textareaRef.current;
170
+ if (!textarea) return;
171
+
172
+ textarea.addEventListener('mouseup', updateSelectionState);
173
+ textarea.addEventListener('keyup', updateSelectionState);
174
+ textarea.addEventListener('click', updateSelectionState);
175
+ textarea.addEventListener('select', updateSelectionState);
176
+ textarea.addEventListener('focus', updateSelectionState);
177
+
178
+ return () => {
179
+ textarea.removeEventListener('mouseup', updateSelectionState);
180
+ textarea.removeEventListener('keyup', updateSelectionState);
181
+ textarea.removeEventListener('click', updateSelectionState);
182
+ textarea.removeEventListener('select', updateSelectionState);
183
+ textarea.removeEventListener('focus', updateSelectionState);
184
+ };
185
+ }, [textareaRef]);
186
+
187
+
188
+ useEffect(() => {
189
+ const style = document.createElement('style');
190
+ style.id = 'dynamic-style-config';
191
+
192
+ const codeStyle = styleConfig.code;
193
+ const quoteStyle = styleConfig.quote;
194
+
195
+ const rgbaMatch = codeStyle.bgColor.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*[\d.]+)?\)/);
196
+ let bgColorWithOpacity = codeStyle.bgColor;
197
+
198
+ if (rgbaMatch) {
199
+ const [_, r, g, b] = rgbaMatch;
200
+ bgColorWithOpacity = `rgba(${r}, ${g}, ${b}, ${codeStyle.opacity / 100})`;
201
+ }
202
+
203
+ const widthValue = codeStyle.width === 'auto' ? 0 : parseFloat(codeStyle.width) || 0;
204
+ const heightValue = codeStyle.height === 'auto' ? 0 : parseFloat(codeStyle.height) || 0;
205
+
206
+ style.innerHTML = `
207
+ :not(pre) > code {
208
+ background-color: ${bgColorWithOpacity} !important;
209
+ color: ${codeStyle.textColor} !important;
210
+ font-size: ${codeStyle.fontSize} !important;
211
+ border-radius: ${codeStyle.borderRadius} !important;
212
+
213
+ padding: 0px 2px !important;
214
+
215
+ ${codeStyle.width !== 'auto' && widthValue > 0 ? `min-width: ${codeStyle.width} !important;` : ''}
216
+ ${codeStyle.height !== 'auto' && heightValue > 0 ? `min-height: ${codeStyle.height} !important;` : ''}
217
+
218
+ display: inline-flex !important;
219
+ align-items: center !important;
220
+ justify-content: center !important;
221
+
222
+ vertical-align: middle !important;
223
+ border: 1px solid rgba(255,255,255,0.05) !important;
224
+ font-family: 'Consolas', 'Monaco', monospace !important;
225
+ line-height: 1 !important;
226
+ margin: 0 1px !important;
227
+ }
228
+
229
+ blockquote {
230
+ background-color: ${quoteStyle.bgColor} !important;
231
+ color: ${quoteStyle.textColor} !important;
232
+ border-left: ${quoteStyle.borderWidth} solid ${quoteStyle.borderColor} !important;
233
+ padding: ${quoteStyle.padding} !important;
234
+ font-size: ${quoteStyle.fontSize} !important;
235
+ border-radius: ${quoteStyle.borderRadius} !important;
236
+ font-style: ${quoteStyle.italic ? 'italic' : 'normal'} !important;
237
+
238
+ ${quoteStyle.width !== 'auto' ? `width: ${quoteStyle.width} !important;` : ''}
239
+ ${quoteStyle.height !== 'auto' ? `min-height: ${quoteStyle.height} !important;` : ''}
240
+
241
+ overflow: visible !important;
242
+ position: relative !important;
243
+ margin-bottom: 1rem !important;
244
+ display: flex !important;
245
+ flex-direction: column !important;
246
+ justify-content: center !important;
247
+ word-break: break-word !important;
248
+ }
249
+
250
+ button code, a code, .btn code {
251
+ background: transparent !important;
252
+ padding: 0 !important;
253
+ color: inherit !important;
254
+ border: none !important;
255
+ margin: 0 !important;
256
+ }
257
+ `;
258
+
259
+ const existingStyle = document.getElementById('dynamic-style-config');
260
+ if (existingStyle) {
261
+ existingStyle.remove();
262
+ }
263
+
264
+ document.head.appendChild(style);
265
+
266
+ return () => {
267
+ style.remove();
268
+ };
269
+ }, [styleConfig]);
270
+
271
+ const applyFormat = (format: FormatType) => {
272
+ let currentStart = selectedRange?.start || 0;
273
+ let currentEnd = selectedRange?.end || 0;
274
+ let currentText = selectedText;
275
+
276
+ if (!selectedRange && textareaRef.current) {
277
+ currentStart = textareaRef.current.selectionStart;
278
+ currentEnd = textareaRef.current.selectionEnd;
279
+ currentText = textareaRef.current.value.substring(currentStart, currentEnd);
280
+ }
281
+
282
+ if (textareaRef.current) {
283
+ currentStart = textareaRef.current.selectionStart;
284
+ currentEnd = textareaRef.current.selectionEnd;
285
+ currentText = textareaRef.current.value.substring(currentStart, currentEnd);
286
+ }
287
+
288
+ let formatted = currentText;
289
+
290
+ switch (format) {
291
+ case 'bold':
292
+ formatted = `**${currentText}**`;
293
+ break;
294
+ case 'italic':
295
+ formatted = `*${currentText}*`;
296
+ break;
297
+ case 'code':
298
+ formatted = `\`${currentText}\``;
299
+ break;
300
+ case 'quote':
301
+ const lines = currentText.split('\n');
302
+ const quotedLines = lines.map(line => `> ${line}`);
303
+ formatted = quotedLines.join('\n') + '\n\n';
304
+ break;
305
+ case 'uppercase':
306
+ formatted = currentText.toUpperCase();
307
+ break;
308
+ case 'lowercase':
309
+ formatted = currentText.toLowerCase();
310
+ break;
311
+ case 'plain':
312
+ formatted = currentText
313
+ .replace(/\*\*/g, '')
314
+ .replace(/\*/g, '')
315
+ .replace(/`/g, '')
316
+ .replace(/<[^>]+>/g, ''); // Remove HTML tags
317
+ break;
318
+ }
319
+
320
+ onApplyFormat(currentStart, currentEnd, formatted);
321
+ setSelectedText(formatted);
322
+
323
+ const newActiveFormats = new Set(activeFormats);
324
+
325
+ // Code format is transient/stateless for this toolbar
326
+ if (format === 'code') {
327
+ // Do nothing to activeFormats, or remove if it was there (though it shouldn't be)
328
+ if (newActiveFormats.has('code')) {
329
+ newActiveFormats.delete('code');
330
+ }
331
+ } else {
332
+ if (newActiveFormats.has(format)) {
333
+ newActiveFormats.delete(format);
334
+ } else {
335
+ if (['uppercase', 'lowercase', 'plain'].includes(format)) {
336
+ newActiveFormats.clear();
337
+ }
338
+ newActiveFormats.add(format);
339
+ }
340
+ }
341
+ setActiveFormats(newActiveFormats);
342
+ };
343
+
344
+ const getCodeStyleString = (config: CodeStyleConfig) => {
345
+ const rgbaMatch = config.bgColor.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*[\d.]+)?\)/);
346
+ let bgColor = config.bgColor;
347
+ if (rgbaMatch) {
348
+ const [_, r, g, b] = rgbaMatch;
349
+ bgColor = `rgba(${r}, ${g}, ${b}, ${config.opacity / 100})`;
350
+ }
351
+
352
+ return [
353
+ `background-color: ${bgColor}`,
354
+ `color: ${config.textColor}`,
355
+ `font-size: ${config.fontSize}`,
356
+ `border-radius: ${config.borderRadius}`,
357
+ `padding: 0px 2px`,
358
+ config.width !== 'auto' ? `min-width: ${config.width}` : '',
359
+ config.height !== 'auto' ? `min-height: ${config.height}` : '',
360
+ 'display: inline-flex',
361
+ 'align-items: center',
362
+ 'justify-content: center',
363
+ 'vertical-align: middle',
364
+ 'border: 1px solid rgba(255,255,255,0.05)',
365
+ "font-family: 'Consolas', 'Monaco', monospace",
366
+ 'line-height: 1',
367
+ 'margin: 0 1px'
368
+ ].filter(Boolean).join('; ');
369
+ };
370
+
371
+ const getQuoteStyleString = (config: QuoteStyleConfig) => {
372
+ return [
373
+ `background-color: ${config.bgColor}`,
374
+ `color: ${config.textColor}`,
375
+ `border-left: ${config.borderWidth} solid ${config.borderColor}`,
376
+ `padding: ${config.padding}`,
377
+ `font-size: ${config.fontSize}`,
378
+ `border-radius: ${config.borderRadius}`,
379
+ config.italic ? 'font-style: italic' : 'font-style: normal',
380
+ config.width !== 'auto' ? `width: ${config.width}` : '',
381
+ config.height !== 'auto' ? `height: ${config.height}` : '',
382
+ 'overflow: visible',
383
+ 'position: relative',
384
+ 'margin-bottom: 1rem',
385
+ 'display: flex',
386
+ 'flex-direction: column',
387
+ 'justify-content: center'
388
+ ].filter(Boolean).join('; ');
389
+ };
390
+
391
+ return (
392
+ <>
393
+ <div
394
+ ref={toolbarRef}
395
+ className="fixed bottom-8 left-1/2 -translate-x-1/2 flex items-center gap-1 bg-surface/95 backdrop-blur-sm border border-white/10 rounded-xl p-1.5 shadow-[0_4px_20px_rgba(0,0,0,0.4)] z-50 pointer-events-auto animate-fade-in transition-all duration-300"
396
+ style={{ position: 'fixed', bottom: '3rem', left: '50%', transform: 'translateX(-50%)' }}
397
+ >
398
+ <button
399
+ type="button"
400
+ onClick={() => applyFormat('bold')}
401
+ className={`p-2 rounded-lg transition-all ${activeFormats.has('bold')
402
+ ? 'bg-primary text-background shadow-md'
403
+ : 'hover:bg-white/10 text-gray-400 hover:text-white'
404
+ }`}
405
+ title="Negrita"
406
+ >
407
+ <Bold size={18} strokeWidth={2.5} />
408
+ </button>
409
+
410
+ <button
411
+ type="button"
412
+ onClick={() => applyFormat('italic')}
413
+ className={`p-2 rounded-lg transition-all ${activeFormats.has('italic')
414
+ ? 'bg-primary text-background shadow-md'
415
+ : 'hover:bg-white/10 text-gray-400 hover:text-white'
416
+ }`}
417
+ title="Cursiva"
418
+ >
419
+ <Italic size={18} strokeWidth={2.5} />
420
+ </button>
421
+
422
+ <button
423
+ type="button"
424
+ onClick={() => applyFormat('code')}
425
+ className={`p-2 rounded-lg transition-all ${activeFormats.has('code')
426
+ ? 'bg-primary text-background shadow-md'
427
+ : 'hover:bg-white/10 text-gray-400 hover:text-white'
428
+ }`}
429
+ title="Código Inline"
430
+ >
431
+ <Code size={18} strokeWidth={2.5} />
432
+ </button>
433
+
434
+ <button
435
+ type="button"
436
+ onClick={() => applyFormat('quote')}
437
+ className={`p-2 rounded-lg transition-all ${activeFormats.has('quote')
438
+ ? 'bg-primary text-background shadow-md'
439
+ : 'hover:bg-white/10 text-gray-400 hover:text-white'
440
+ }`}
441
+ title="Citar"
442
+ >
443
+ <Quote size={18} strokeWidth={2.5} />
444
+ </button>
445
+
446
+ <div className="w-px h-6 bg-white/10 mx-1"></div>
447
+
448
+ <button
449
+ type="button"
450
+ onClick={() => applyFormat('uppercase')}
451
+ className="p-2 rounded-lg hover:bg-white/10 text-gray-400 hover:text-white transition-all text-xs font-bold"
452
+ title="MAYÚSCULAS"
453
+ >
454
+ AA
455
+ </button>
456
+
457
+ <button
458
+ type="button"
459
+ onClick={() => applyFormat('lowercase')}
460
+ className="p-2 rounded-lg hover:bg-white/10 text-gray-400 hover:text-white transition-all text-xs font-bold"
461
+ title="minúsculas"
462
+ >
463
+ aa
464
+ </button>
465
+
466
+ <button
467
+ type="button"
468
+ onClick={() => applyFormat('plain')}
469
+ className="p-2 rounded-lg hover:bg-white/10 text-gray-400 hover:text-red-400 transition-all"
470
+ title="Limpiar Formato"
471
+ >
472
+ <X size={18} />
473
+ </button>
474
+
475
+ <div className="w-px h-6 bg-white/10 mx-1"></div>
476
+
477
+ <button
478
+ type="button"
479
+ onClick={() => setShowSettings(!showSettings)}
480
+ className={`p-2 rounded-lg transition-all ${showSettings
481
+ ? 'bg-primary text-background shadow-md'
482
+ : 'hover:bg-white/10 text-gray-400 hover:text-white'
483
+ }`}
484
+ title="Configuración"
485
+ >
486
+ <Settings size={18} strokeWidth={2.5} />
487
+ </button>
488
+ </div>
489
+
490
+ {showSettings && (
491
+ <div
492
+ className="fixed bottom-24 left-1/2 -translate-x-1/2 bg-[#1a1a1a] border border-white/10 rounded-xl shadow-[0_0_40px_rgba(0,0,0,0.6)] z-50 w-[380px] flex flex-col max-h-[75vh] animate-fade-in overflow-hidden"
493
+ style={{ position: 'fixed', bottom: '7rem', left: '50%', transform: 'translateX(-50%)' }}
494
+ >
495
+ <StyleSettingsPanel
496
+ styleConfig={styleConfig}
497
+ onUpdateConfig={handleConfigUpdate}
498
+ activeTab={settingsTab}
499
+ onTabChange={setSettingsTab}
500
+ onClose={handleCancelSettings}
501
+ onConfirm={handleConfirmSettings}
502
+ />
503
+ </div>
504
+ )}
505
+ </>
506
+ );
507
+ });
components/TiktokIcon.tsx ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React from 'react';
2
+
3
+ interface TiktokIconProps {
4
+ size?: number;
5
+ style?: React.CSSProperties;
6
+ color?: string;
7
+ className?: string; // Add className prop
8
+ }
9
+
10
+ export const TiktokIcon: React.FC<TiktokIconProps> = ({ size = 24, style, color = 'currentColor', className }) => {
11
+ return (
12
+ <svg
13
+ xmlns="http://www.w3.org/2000/svg"
14
+ width={size}
15
+ height={size}
16
+ viewBox="0 0 24 24"
17
+ fill="none"
18
+ stroke={color}
19
+ strokeWidth="2"
20
+ strokeLinecap="round"
21
+ strokeLinejoin="round"
22
+ style={style}
23
+ className={className} // Pass className to svg
24
+ >
25
+ <path d="M9 12a4 4 0 1 0 4 4V4a5 5 0 0 0 5 5" />
26
+ </svg>
27
+ );
28
+ };
components/TipTapEditor.tsx ADDED
@@ -0,0 +1,494 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useEffect, useState } from 'react';
2
+ import { useEditor, EditorContent, Editor, mergeAttributes, Extension } from '@tiptap/react';
3
+ import StarterKit from '@tiptap/starter-kit';
4
+ import Heading from '@tiptap/extension-heading';
5
+ import Link from '@tiptap/extension-link';
6
+ import TextAlign from '@tiptap/extension-text-align';
7
+ import Code from '@tiptap/extension-code';
8
+ import HorizontalRule from '@tiptap/extension-horizontal-rule';
9
+ import { CustomBlockquote } from './extensions/CustomBlockquote';
10
+ import { CustomImageExtension } from './extensions/CustomImageExtension';
11
+ import { UniversalVideoExtension } from './extensions/UniversalVideoExtension';
12
+ import { CustomCodeBlock } from './extensions/CustomCodeBlock';
13
+ import { CustomButton } from './extensions/CustomButton';
14
+ import { EditorToolbar } from './EditorToolbar';
15
+ import { StyleSettingsPanel } from './StyleSettingsPanel';
16
+ import { EditorSelectionWrapper } from './EditorSelectionWrapper';
17
+ import { QuoteStyleConfig, DEFAULT_QUOTE_STYLE, DEFAULT_CODE_STYLE, StyleConfig, saveStyleConfigToCloud, DEFAULT_STYLE_CONFIG, subscribeToStyleConfig } from '../services/codeStyleService';
18
+
19
+ interface TipTapEditorProps {
20
+ content: any; // JSON content or string (for initial load)
21
+ onUpdate: (content: any) => void; // Returns JSON
22
+ isEditable?: boolean;
23
+ editorRef?: React.MutableRefObject<Editor | null>;
24
+ onBlockDoubleClick?: (type: 'code' | 'quote', index: number) => void;
25
+ onSave?: () => void;
26
+ autoFocus?: boolean;
27
+ showToolbarOnFocus?: boolean;
28
+ className?: string;
29
+ extensions?: Extension[];
30
+ dense?: boolean;
31
+ cardStyle?: 'bordered' | 'transparent' | 'filled';
32
+ onCardStyleChange?: (style: 'bordered' | 'transparent' | 'filled') => void;
33
+ }
34
+
35
+ export const TipTapEditor: React.FC<TipTapEditorProps> = ({
36
+ content,
37
+ onUpdate,
38
+ isEditable = true,
39
+ editorRef,
40
+ onBlockDoubleClick,
41
+ onSave,
42
+ autoFocus = false,
43
+ showToolbarOnFocus = false,
44
+ className = '',
45
+ extensions = [],
46
+ dense = false,
47
+ cardStyle,
48
+ onCardStyleChange
49
+ }) => {
50
+ // Custom extension to handle ArrowDown at the end of the document
51
+ const ArrowDownHandler = Extension.create({
52
+ name: 'arrowDownHandler',
53
+ addKeyboardShortcuts() {
54
+ return {
55
+ ArrowDown: () => {
56
+ const { state, commands } = this.editor;
57
+ const { selection, doc } = state;
58
+ const { empty, $head } = selection;
59
+
60
+ // Check if we are at the end of the document
61
+ // The document size includes the opening and closing tags of the doc itself.
62
+ // The last valid cursor position inside the last block is usually doc.content.size - 1
63
+ if (empty && $head.pos === doc.content.size - 1) {
64
+ return commands.insertContent('<p></p>');
65
+ }
66
+ return false;
67
+ },
68
+ };
69
+ },
70
+ });
71
+
72
+ const [styleConfig, setStyleConfig] = useState<StyleConfig>(DEFAULT_STYLE_CONFIG);
73
+ const [activeTab, setActiveTab] = useState<'code' | 'quote' | 'link' | 'general' | 'button' | 'codeblock'>('quote');
74
+ const [isSettingsOpen, setIsSettingsOpen] = useState(false);
75
+ const [editingBlockIndex, setEditingBlockIndex] = useState<number | null>(null);
76
+ const [isFocused, setIsFocused] = useState(false);
77
+ const [toolbarVisible, setToolbarVisible] = useState(!showToolbarOnFocus);
78
+ // contextMenuPos state removed as context menu is disabled
79
+
80
+ useEffect(() => {
81
+ if (!showToolbarOnFocus) {
82
+ setToolbarVisible(true);
83
+ }
84
+ }, [showToolbarOnFocus]);
85
+
86
+ useEffect(() => {
87
+ if (showToolbarOnFocus) {
88
+ if (isFocused) {
89
+ setToolbarVisible(true);
90
+ } else {
91
+ setToolbarVisible(false);
92
+ }
93
+ }
94
+ }, [isFocused, showToolbarOnFocus]);
95
+
96
+ const handleFocus = () => {
97
+ setIsFocused(true);
98
+ if (showToolbarOnFocus) setToolbarVisible(true);
99
+ };
100
+
101
+ const handleBlur = (e: React.FocusEvent) => {
102
+ // Check if the new focus is still within the editor container
103
+ const currentTarget = e.currentTarget;
104
+
105
+ // Give a small timeout to allow focus to settle (e.g. clicking a button)
106
+ requestAnimationFrame(() => {
107
+ if (!currentTarget.contains(document.activeElement)) {
108
+ setIsFocused(false);
109
+ if (showToolbarOnFocus) setToolbarVisible(false);
110
+ }
111
+ });
112
+ };
113
+
114
+
115
+
116
+ // Close context menu on click anywhere
117
+
118
+ const editor = useEditor({
119
+
120
+ extensions: [
121
+ StarterKit.configure({
122
+ heading: false, // Disable default heading to use custom configuration
123
+ code: false, // Disable default code to use custom configuration
124
+ codeBlock: false, // Disable default codeBlock to use custom configuration
125
+ horizontalRule: false, // Disable default horizontalRule to use custom configuration
126
+ blockquote: false, // Disable default blockquote to use custom configuration
127
+ }),
128
+ Heading.configure({
129
+ levels: [1, 2, 3],
130
+ }).extend({
131
+ renderHTML({ node, HTMLAttributes }) {
132
+ const level = node.attrs.level;
133
+ const classes: Record<number, string> = {
134
+ 1: 'text-4xl font-bold text-white m-0 mb-2 leading-none',
135
+ 2: 'text-2xl font-semibold text-zinc-100 m-0 mb-2 leading-tight',
136
+ 3: 'text-xl font-medium text-zinc-200 m-0 mb-1',
137
+ };
138
+ return [`h${level}`, mergeAttributes(this.options.HTMLAttributes, HTMLAttributes, { class: classes[level] }), 0];
139
+ },
140
+ }),
141
+ CustomBlockquote,
142
+ CustomCodeBlock,
143
+ Link.configure({
144
+ openOnClick: false,
145
+ HTMLAttributes: {
146
+ class: 'text-primary underline cursor-pointer hover:text-primary/80',
147
+ },
148
+ }),
149
+ TextAlign.configure({
150
+ types: ['heading', 'paragraph'],
151
+ }),
152
+ Code.extend({
153
+ inclusive: false,
154
+ addAttributes() {
155
+ return {
156
+ showBackground: {
157
+ default: true,
158
+ parseHTML: element => element.getAttribute('data-show-background') !== 'false',
159
+ renderHTML: attributes => {
160
+ if (!attributes.showBackground) {
161
+ return {
162
+ 'data-show-background': 'false',
163
+ style: 'background-color: transparent !important; color: inherit !important; padding: 0 !important;',
164
+ };
165
+ }
166
+ return {
167
+ 'data-show-background': 'true',
168
+ };
169
+ },
170
+ },
171
+ };
172
+ },
173
+ }),
174
+ CustomImageExtension,
175
+ UniversalVideoExtension,
176
+ CustomButton,
177
+ HorizontalRule.configure({
178
+ HTMLAttributes: {
179
+ class: 'border-t border-white/10 my-8', // Reduced opacity
180
+ },
181
+ }),
182
+ ArrowDownHandler,
183
+ ...extensions
184
+ ],
185
+ content: content,
186
+ editable: isEditable,
187
+ autofocus: autoFocus,
188
+ onUpdate: ({ editor }) => {
189
+ // Check if onUpdate expects an object or just the content
190
+ // The interface says (content: any) => void
191
+ // We'll pass both HTML and JSON if possible, but the signature usually expects one arg
192
+ // If the consumer expects JSON, we pass JSON.
193
+ // But for Title/Summary we want HTML.
194
+ // Let's pass an object with both, OR check usage.
195
+ // Existing usage: onUpdate(editor.getJSON())
196
+ // We should change this to allow the parent to decide, or just pass the editor instance context?
197
+ // "onUpdate" prop in DetailView expects "content: any".
198
+ // I will change it to return `editor.getHTML()` if `showToolbarOnFocus` is true, otherwise `editor.getJSON()`.
199
+ // This is a heuristic but matches the use case (Title/Summary = HTML string, Blocks = JSON).
200
+
201
+ if (showToolbarOnFocus) {
202
+ onUpdate(editor.getHTML());
203
+ } else {
204
+ onUpdate(editor.getJSON());
205
+ }
206
+ },
207
+ editorProps: {
208
+ handleDOMEvents: {
209
+ // Context menu handler removed
210
+ },
211
+ attributes: {
212
+ class: `prose prose-invert max-w-none focus:outline-none ${dense ? 'min-h-[40px]' : 'min-h-[50px]'} !h-auto prose-headings:font-bold prose-h1:text-3xl prose-h2:text-2xl prose-p:text-gray-300 prose-p:leading-relaxed prose-p:my-3 prose-blockquote:not-italic prose-pre:bg-[#000000] prose-pre:text-gray-300 prose-code:text-primary prose-code:rounded prose-code:px-1 prose-code:py-1 prose-code:leading-relaxed prose-code:decoration-clone prose-code:before:content-none prose-code:after:content-none prose-hr:border-white/10 ${className}`,
213
+ style: `
214
+ --code-font-family: ${styleConfig.code.fontFamily};
215
+ `
216
+ },
217
+ },
218
+ });
219
+
220
+ // Inject dynamic styles for code blocks
221
+ useEffect(() => {
222
+ if (!editor) return;
223
+
224
+ const handleTripleClick = (e: any) => {
225
+ const { type, pos } = e.detail;
226
+
227
+ // Find the index of the block
228
+ let index = 0;
229
+ let found = false;
230
+ let targetNode: any = null;
231
+
232
+ editor.state.doc.descendants((n, p) => {
233
+ if (found) return false;
234
+
235
+ if (n.type.name === 'customBlockquote' && type === 'quote') {
236
+ if (p === pos) {
237
+ targetNode = n;
238
+ found = true;
239
+ return false;
240
+ }
241
+ index++;
242
+ } else if (n.type.name === 'codeBlock' && type === 'code') {
243
+ if (p === pos) {
244
+ targetNode = n;
245
+ found = true;
246
+ return false;
247
+ }
248
+ index++;
249
+ }
250
+ return true;
251
+ });
252
+
253
+ if (found && targetNode) {
254
+ // If it's a quote, open settings for this specific block
255
+ if (type === 'quote') {
256
+ setEditingBlockIndex(pos); // Use pos as identifier for simplicity in this context, or index if we map it back
257
+ // Actually, let's use the node attributes to populate the settings panel
258
+ const nodeAttrs = targetNode.attrs;
259
+ const instanceConfig: StyleConfig = {
260
+ ...styleConfig,
261
+ quote: {
262
+ ...DEFAULT_QUOTE_STYLE,
263
+ ...nodeAttrs
264
+ }
265
+ };
266
+ // We need a way to pass this instance config to the panel without overwriting the global styleConfig state permanently
267
+ // But StyleSettingsPanel takes styleConfig as prop.
268
+ // We can use a temporary state or just pass it.
269
+ // Let's update the logic to open settings with this specific config.
270
+ // Wait, StyleSettingsPanel uses internal state initialized from prop.
271
+ // So if we pass a different config here, it should work.
272
+
273
+ // However, we need to know if we are in "instance edit" mode or "global edit" mode.
274
+ // We can use editingBlockIndex !== null to determine this.
275
+
276
+ // Let's set the styleConfig to this instance's config JUST for the panel
277
+ // But wait, styleConfig is used for global styles too (code font).
278
+ // If we overwrite it, we might lose global context.
279
+ // But here we are editing a quote.
280
+
281
+ // Let's try this:
282
+ // 1. Set editingBlockIndex to pos.
283
+ // 2. Open settings.
284
+ // 3. In the render, if editingBlockIndex is set, pass the instance config.
285
+ setIsSettingsOpen(true);
286
+ } else if (type === 'code') {
287
+ setEditingBlockIndex(pos);
288
+ setIsSettingsOpen(true);
289
+ setActiveTab('codeblock'); // Switch to codeblock tab
290
+ } else if (onBlockDoubleClick) {
291
+ // Keep existing behavior for code blocks if needed, or handle similarly
292
+ onBlockDoubleClick('code', index);
293
+ }
294
+ }
295
+ };
296
+
297
+ editor.view.dom.addEventListener('block-triple-click', handleTripleClick);
298
+ return () => {
299
+ editor.view.dom.removeEventListener('block-triple-click', handleTripleClick);
300
+ };
301
+ }, [editor, onBlockDoubleClick, styleConfig]); // Added styleConfig dependency to ensure we have latest defaults
302
+
303
+ useEffect(() => {
304
+ if (editor) {
305
+ editor.setEditable(isEditable);
306
+ }
307
+ }, [isEditable, editor]);
308
+
309
+ useEffect(() => {
310
+ if (editor && editorRef) {
311
+ editorRef.current = editor;
312
+ }
313
+ }, [editor, editorRef]);
314
+
315
+ // Update content if it changes externally (and is different)
316
+ useEffect(() => {
317
+ if (editor && content && JSON.stringify(editor.getJSON()) !== JSON.stringify(content)) {
318
+ // Specialized content set for HTML string vs JSON
319
+ if (typeof content === 'string') {
320
+ if (editor.getHTML() !== content) {
321
+ editor.commands.setContent(content);
322
+ }
323
+ } else {
324
+ editor.commands.setContent(content);
325
+ }
326
+ }
327
+ }, [content, editor]);
328
+
329
+ // Subscribe to style config changes
330
+ useEffect(() => {
331
+ const unsubscribe = subscribeToStyleConfig((config) => {
332
+ setStyleConfig(config);
333
+ });
334
+ return () => unsubscribe();
335
+ }, []);
336
+
337
+ if (!editor) {
338
+ return null;
339
+ }
340
+
341
+ // Determine the config to pass to the panel
342
+ const getSettingsPanelConfig = (): StyleConfig => {
343
+ if (editingBlockIndex !== null) {
344
+ // Find the node at editingBlockIndex
345
+ let targetNode: any = null;
346
+ editor.state.doc.descendants((n, p) => {
347
+ if (p === editingBlockIndex) {
348
+ targetNode = n;
349
+ return false;
350
+ }
351
+ return true;
352
+ });
353
+
354
+ if (targetNode && targetNode.type.name === 'customBlockquote') {
355
+ return {
356
+ ...styleConfig,
357
+ quote: {
358
+ ...DEFAULT_QUOTE_STYLE,
359
+ ...targetNode.attrs
360
+ }
361
+ };
362
+ }
363
+
364
+ if (targetNode && targetNode.type.name === 'codeBlock') {
365
+ return {
366
+ ...styleConfig,
367
+ code: {
368
+ ...DEFAULT_CODE_STYLE,
369
+ ...targetNode.attrs
370
+ }
371
+ };
372
+ }
373
+ }
374
+ return styleConfig;
375
+ };
376
+
377
+ return (
378
+ <div
379
+ className={`tiptap-editor-container w-full flex flex-col relative h-auto ${className}`}
380
+ onFocus={handleFocus}
381
+ onBlur={handleBlur}
382
+
383
+ >
384
+ <div className={`transition-opacity duration-200 ${isEditable && toolbarVisible ? 'opacity-100 pointer-events-auto' : 'opacity-0 pointer-events-none'}`}>
385
+ <EditorToolbar
386
+ editor={editor}
387
+ defaultQuoteStyles={styleConfig.quote}
388
+ codeStyleConfig={styleConfig.code}
389
+ linkStyleConfig={styleConfig.link}
390
+ buttonStyleConfig={styleConfig.button}
391
+ onOpenSettings={() => {
392
+ setEditingBlockIndex(null); // Reset to global mode
393
+ setIsSettingsOpen(true);
394
+ }}
395
+ onSave={onSave}
396
+ />
397
+ </div>
398
+ <div
399
+ className={`h-auto ${dense ? 'pb-0' : 'pb-24'} text-zinc-100 cursor-text flex flex-col items-start`}
400
+ >
401
+ <EditorSelectionWrapper
402
+ editor={editor}
403
+ onBackgroundClick={() => {
404
+ editor?.chain().focus('end').run();
405
+ }}
406
+ >
407
+ <EditorContent editor={editor} className="h-auto min-h-[40px]" />
408
+ </EditorSelectionWrapper>
409
+ </div>
410
+
411
+
412
+
413
+ {isSettingsOpen && (
414
+ <div className="fixed inset-0 z-[100] flex items-center justify-center bg-black/50 p-4">
415
+ {console.log('[TipTapEditor] Opening Settings. editingBlockIndex:', editingBlockIndex, 'cardStyle passed:', cardStyle)}
416
+ <div className="bg-[#1e1e1e] rounded-xl shadow-2xl w-full max-w-2xl h-[85vh] flex flex-col overflow-hidden border border-white/10">
417
+ <StyleSettingsPanel
418
+ styleConfig={getSettingsPanelConfig()}
419
+ onUpdateConfig={(newConfig) => {
420
+ // Only update local state for preview/interaction
421
+ // Actual save happens on confirm or debounce if we implemented it
422
+ setStyleConfig(newConfig);
423
+ }}
424
+ activeTab={activeTab}
425
+ onTabChange={setActiveTab}
426
+ onClose={() => {
427
+ setIsSettingsOpen(false);
428
+ setEditingBlockIndex(null);
429
+ }}
430
+ onConfirm={async (config) => {
431
+ if (editingBlockIndex !== null) {
432
+ // Instance Edit Mode: Update ONLY the specific block
433
+ if (editor) {
434
+ editor.chain().focus().command(({ tr }) => {
435
+ const node = editor.state.doc.nodeAt(editingBlockIndex);
436
+ if (node && node.type.name === 'customBlockquote') {
437
+ tr.setNodeMarkup(editingBlockIndex, undefined, {
438
+ ...config.quote,
439
+ backgroundColor: config.quote.bgColor
440
+ });
441
+ } else if (node && node.type.name === 'codeBlock') {
442
+ tr.setNodeMarkup(editingBlockIndex, undefined, {
443
+ ...node.attrs,
444
+ collapsible: config.code.collapsible,
445
+ showBackground: config.code.showBackground,
446
+ showLineNumbers: config.code.showLineNumbers,
447
+ wrapText: config.code.wrapText
448
+ });
449
+ }
450
+ return true;
451
+ }).run();
452
+ }
453
+ setEditingBlockIndex(null);
454
+ } else {
455
+ // Global Edit Mode: Save to cloud ONLY. Do NOT update existing blocks.
456
+ try {
457
+ await saveStyleConfigToCloud(config);
458
+
459
+ // Update local state
460
+ setStyleConfig(config);
461
+
462
+ // Propagate changes to all existing customBlockquote nodes
463
+ if (editor) {
464
+ editor.chain().focus().command(({ tr, state }) => {
465
+ state.doc.descendants((node, pos) => {
466
+ if (node.type.name === 'customBlockquote') {
467
+ tr.setNodeMarkup(pos, undefined, {
468
+ ...node.attrs,
469
+ showDownloadButton: config.quote.showDownloadButton,
470
+ showCopyButton: config.quote.showCopyButton
471
+ });
472
+ }
473
+ return true;
474
+ });
475
+ return true;
476
+ }).run();
477
+ }
478
+ } catch (error) {
479
+ console.error('Error saving style config:', error);
480
+ }
481
+ }
482
+ setIsSettingsOpen(false);
483
+ }}
484
+ hideTabs={false}
485
+ previewContent="Este es un ejemplo de cómo se verán tus citas con la configuración actual."
486
+ cardStyle={cardStyle}
487
+ onCardStyleChange={onCardStyleChange}
488
+ />
489
+ </div>
490
+ </div>
491
+ )}
492
+ </div>
493
+ );
494
+ };
components/extensions/CustomBlockquote.ts ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Blockquote } from '@tiptap/extension-blockquote';
2
+ import { ReactNodeViewRenderer } from '@tiptap/react';
3
+ import { QuoteComponent } from '../QuoteComponent';
4
+
5
+ export interface CustomBlockquoteOptions {
6
+ HTMLAttributes: Record<string, any>;
7
+ }
8
+
9
+ export const CustomBlockquote = Blockquote.extend<CustomBlockquoteOptions>({
10
+ name: 'customBlockquote',
11
+
12
+ addNodeView() {
13
+ return ReactNodeViewRenderer(QuoteComponent);
14
+ },
15
+
16
+ addAttributes() {
17
+ return {
18
+ borderColor: {
19
+ default: 'gray',
20
+ parseHTML: (element) => element.style.borderLeftColor,
21
+ renderHTML: (attributes) => {
22
+ if (!attributes.borderColor) {
23
+ return {};
24
+ }
25
+ return {
26
+ style: `border-left-color: ${attributes.borderColor}`,
27
+ };
28
+ },
29
+ },
30
+ borderWidth: {
31
+ default: '4px',
32
+ parseHTML: (element) => element.style.borderLeftWidth,
33
+ renderHTML: (attributes) => {
34
+ if (!attributes.borderWidth) return {};
35
+ return { style: `border-left-width: ${attributes.borderWidth}` };
36
+ }
37
+ },
38
+ backgroundColor: {
39
+ default: 'transparent',
40
+ parseHTML: (element) => element.style.backgroundColor,
41
+ renderHTML: (attributes) => {
42
+ if (!attributes.backgroundColor) {
43
+ return {};
44
+ }
45
+ return {
46
+ style: `background-color: ${attributes.backgroundColor}`,
47
+ };
48
+ },
49
+ },
50
+ textColor: {
51
+ default: 'inherit',
52
+ parseHTML: (element) => element.style.color,
53
+ renderHTML: (attributes) => {
54
+ if (!attributes.textColor) {
55
+ return {};
56
+ }
57
+ return {
58
+ style: `color: ${attributes.textColor}`,
59
+ };
60
+ },
61
+ },
62
+ padding: {
63
+ default: '4px',
64
+ parseHTML: (element) => element.style.padding,
65
+ renderHTML: (attributes) => {
66
+ if (!attributes.padding) return {};
67
+ return { style: `padding: ${attributes.padding}` };
68
+ }
69
+ },
70
+ fontSize: {
71
+ default: 'inherit',
72
+ parseHTML: (element) => element.style.fontSize,
73
+ renderHTML: (attributes) => {
74
+ if (!attributes.fontSize) return {};
75
+ return { style: `font-size: ${attributes.fontSize}` };
76
+ }
77
+ },
78
+ borderRadius: {
79
+ default: '0px',
80
+ parseHTML: (element) => element.style.borderRadius,
81
+ renderHTML: (attributes) => {
82
+ if (!attributes.borderRadius) return {};
83
+ return { style: `border-radius: ${attributes.borderRadius}` };
84
+ }
85
+ },
86
+ width: {
87
+ default: '100%',
88
+ parseHTML: (element) => element.style.width,
89
+ renderHTML: (attributes) => {
90
+ if (!attributes.width) return {};
91
+ return { style: `width: ${attributes.width}` };
92
+ }
93
+ },
94
+ height: {
95
+ default: 'auto',
96
+ parseHTML: (element) => element.style.height,
97
+ renderHTML: (attributes) => {
98
+ if (!attributes.height) return {};
99
+ return { style: `height: ${attributes.height}` };
100
+ }
101
+ },
102
+ italic: {
103
+ default: false,
104
+ parseHTML: (element) => element.style.fontStyle === 'italic',
105
+ renderHTML: (attributes) => {
106
+ if (!attributes.italic) return {};
107
+ return { style: `font-style: italic` };
108
+ }
109
+ },
110
+ showCopyButton: {
111
+ default: false,
112
+ parseHTML: (element) => element.getAttribute('data-show-copy') === 'true',
113
+ renderHTML: (attributes) => {
114
+ return { 'data-show-copy': attributes.showCopyButton };
115
+ }
116
+ },
117
+ fontFamily: {
118
+ default: 'inherit',
119
+ parseHTML: (element) => element.style.fontFamily,
120
+ renderHTML: (attributes) => {
121
+ if (!attributes.fontFamily) return {};
122
+ return { style: `font-family: ${attributes.fontFamily}` };
123
+ }
124
+ },
125
+ isCodeFont: {
126
+ default: false,
127
+ parseHTML: (element) => element.getAttribute('data-is-code-font') === 'true',
128
+ renderHTML: (attributes) => {
129
+ return { 'data-is-code-font': attributes.isCodeFont };
130
+ }
131
+ },
132
+ showDownloadButton: {
133
+ default: false,
134
+ parseHTML: (element) => element.getAttribute('data-show-download') === 'true',
135
+ renderHTML: (attributes) => {
136
+ return { 'data-show-download': attributes.showDownloadButton };
137
+ }
138
+ },
139
+ collapsible: {
140
+ default: true,
141
+ parseHTML: (element) => element.getAttribute('data-collapsible') === 'true',
142
+ renderHTML: (attributes) => {
143
+ return { 'data-collapsible': attributes.collapsible };
144
+ }
145
+ }
146
+ };
147
+ },
148
+
149
+ renderHTML({ HTMLAttributes }) {
150
+ // Merge all style attributes into a single style string to avoid multiple style attributes
151
+ const styleParts: string[] = [];
152
+
153
+ // Helper to extract style from HTMLAttributes if it exists as a separate property
154
+ // (though renderHTML in addAttributes usually handles adding it to HTMLAttributes.style)
155
+ // However, TipTap merges them. Let's ensure we have a clean style string.
156
+
157
+ // Actually, TipTap's default renderHTML merges the attributes returned by individual renderHTML functions.
158
+ // So we just need to return the tag.
159
+ return ['blockquote', HTMLAttributes, 0];
160
+ },
161
+ });
components/extensions/CustomButton.ts ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Node, mergeAttributes } from '@tiptap/core';
2
+ import { ReactNodeViewRenderer } from '@tiptap/react';
3
+ import { CustomButtonComponent } from '../CustomButtonComponent';
4
+
5
+ export interface CustomButtonOptions {
6
+ HTMLAttributes: Record<string, any>;
7
+ }
8
+
9
+ declare module '@tiptap/core' {
10
+ interface Commands<ReturnType> {
11
+ customButton: {
12
+ setCustomButton: (options: { text: string; url: string; variant: 'visit' | 'download' } & Record<string, any>) => ReturnType;
13
+ };
14
+ }
15
+ }
16
+
17
+ export const CustomButton = Node.create<CustomButtonOptions>({
18
+ name: 'customButton',
19
+
20
+ group: 'inline',
21
+
22
+ inline: true,
23
+
24
+ atom: true,
25
+
26
+ addAttributes() {
27
+ return {
28
+ text: {
29
+ default: 'Button',
30
+ parseHTML: element => element.textContent,
31
+ // We handle text content in the main renderHTML
32
+ },
33
+ url: {
34
+ default: '#',
35
+ parseHTML: element => element.getAttribute('href'),
36
+ renderHTML: attributes => ({
37
+ href: attributes.url,
38
+ }),
39
+ },
40
+ variant: {
41
+ default: 'visit',
42
+ parseHTML: element => element.getAttribute('data-variant'),
43
+ renderHTML: attributes => ({
44
+ 'data-variant': attributes.variant,
45
+ }),
46
+ },
47
+ backgroundColor: {
48
+ default: null,
49
+ parseHTML: element => element.getAttribute('data-background-color'),
50
+ renderHTML: attributes => ({
51
+ 'data-background-color': attributes.backgroundColor,
52
+ }),
53
+ },
54
+ textColor: {
55
+ default: null,
56
+ parseHTML: element => element.getAttribute('data-text-color'),
57
+ renderHTML: attributes => ({
58
+ 'data-text-color': attributes.textColor,
59
+ }),
60
+ },
61
+ borderRadius: {
62
+ default: null,
63
+ parseHTML: element => element.getAttribute('data-border-radius'),
64
+ renderHTML: attributes => ({
65
+ 'data-border-radius': attributes.borderRadius,
66
+ }),
67
+ },
68
+ width: {
69
+ default: null,
70
+ parseHTML: element => element.getAttribute('data-width'),
71
+ renderHTML: attributes => ({
72
+ 'data-width': attributes.width,
73
+ }),
74
+ },
75
+ height: {
76
+ default: null,
77
+ parseHTML: element => element.getAttribute('data-height'),
78
+ renderHTML: attributes => ({
79
+ 'data-height': attributes.height,
80
+ }),
81
+ },
82
+ };
83
+ },
84
+
85
+ parseHTML() {
86
+ return [
87
+ {
88
+ tag: 'a[data-type="custom-button"]',
89
+ priority: 10000,
90
+ getAttrs: (element) => {
91
+ if (element instanceof HTMLElement && element.getAttribute('data-type') === 'custom-button') {
92
+ return {};
93
+ }
94
+ return false;
95
+ },
96
+ },
97
+ ];
98
+ },
99
+
100
+ renderHTML({ node, HTMLAttributes }) {
101
+ const { text, url, variant, backgroundColor, textColor, borderRadius, width, height } = node.attrs;
102
+ const defaultBg = '#bb86fc';
103
+ const defaultText = '#ffffff';
104
+
105
+ const activeBg = backgroundColor || defaultBg;
106
+ const activeText = textColor || defaultText;
107
+
108
+ const styles = {
109
+ width: width || 'auto',
110
+ height: height || 'auto',
111
+ 'max-width': '100%',
112
+ 'background-color': 'transparent',
113
+ color: activeBg, // Main color for icon/border
114
+ 'border-radius': borderRadius || '8px',
115
+ border: `1px solid ${activeBg}`,
116
+ 'box-shadow': `0 0 10px ${activeBg}40`,
117
+ 'text-decoration': 'none',
118
+ 'vertical-align': 'middle',
119
+ };
120
+
121
+ const styleString = Object.entries(styles)
122
+ .map(([key, value]) => `${key}: ${value}`)
123
+ .join('; ');
124
+
125
+ // Start with the generic logic for icons
126
+ const getIconChildren = (v: string) => {
127
+ switch (v) {
128
+ case 'download':
129
+ // <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" x2="12" y1="15" y2="3"/>
130
+ return [
131
+ ['path', { d: 'M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4' }],
132
+ ['polyline', { points: '7 10 12 15 17 10' }],
133
+ ['line', { x1: '12', x2: '12', y1: '15', y2: '3' }]
134
+ ];
135
+ case 'visit':
136
+ default:
137
+ // <path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" x2="21" y1="14" y2="3"/>
138
+ return [
139
+ ['path', { d: 'M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6' }],
140
+ ['polyline', { points: '15 3 21 3 21 9' }],
141
+ ['line', { x1: '10', x2: '21', y1: '14', y2: '3' }]
142
+ ];
143
+ }
144
+ };
145
+
146
+ return [
147
+ 'a',
148
+ mergeAttributes(HTMLAttributes, {
149
+ 'data-type': 'custom-button',
150
+ class: 'inline-flex items-center justify-center gap-2 px-4 py-2 border transition-all duration-200 no-underline cursor-pointer hover:opacity-90 mx-1 align-middle',
151
+ style: styleString,
152
+ href: url || '#',
153
+ target: '_blank',
154
+ rel: 'noopener noreferrer'
155
+ }),
156
+ [
157
+ 'svg',
158
+ {
159
+ xmlns: 'http://www.w3.org/2000/svg',
160
+ width: '16',
161
+ height: '16',
162
+ viewBox: '0 0 24 24',
163
+ fill: 'none',
164
+ stroke: activeBg,
165
+ 'stroke-width': '2',
166
+ 'stroke-linecap': 'round',
167
+ 'stroke-linejoin': 'round',
168
+ },
169
+ ...getIconChildren(variant || 'visit')
170
+ ],
171
+ [
172
+ 'span',
173
+ {
174
+ class: 'font-medium text-sm',
175
+ style: `color: ${activeText}`
176
+ },
177
+ text || 'Button'
178
+ ]
179
+ ];
180
+ },
181
+
182
+ addNodeView() {
183
+ return ReactNodeViewRenderer(CustomButtonComponent);
184
+ },
185
+
186
+ addCommands() {
187
+ return {
188
+ setCustomButton:
189
+ (options) =>
190
+ ({ commands }) => {
191
+ return commands.insertContent({
192
+ type: this.name,
193
+ attrs: options,
194
+ });
195
+ },
196
+ };
197
+ },
198
+ });
components/extensions/CustomCodeBlock.ts ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { CodeBlock } from '@tiptap/extension-code-block';
2
+ import { ReactNodeViewRenderer } from '@tiptap/react';
3
+ import { CodeBlockComponent } from '../CodeBlockComponent';
4
+
5
+ export const CustomCodeBlock = CodeBlock.extend({
6
+ addNodeView() {
7
+ return ReactNodeViewRenderer(CodeBlockComponent);
8
+ },
9
+ addAttributes() {
10
+ return {
11
+ language: {
12
+ default: null,
13
+ },
14
+ filename: {
15
+ default: null,
16
+ },
17
+ collapsible: {
18
+ default: true,
19
+ parseHTML: (element) => element.getAttribute('data-collapsible') !== 'false',
20
+ renderHTML: (attributes) => {
21
+ return {
22
+ 'data-collapsible': attributes.collapsible,
23
+ };
24
+ },
25
+ },
26
+ showLineNumbers: {
27
+ default: false,
28
+ parseHTML: (element) => element.getAttribute('data-show-line-numbers') === 'true',
29
+ renderHTML: (attributes) => {
30
+ return {
31
+ 'data-show-line-numbers': attributes.showLineNumbers,
32
+ };
33
+ },
34
+ },
35
+ wrapText: {
36
+ default: false,
37
+ parseHTML: (element) => element.getAttribute('data-wrap-text') === 'true',
38
+ renderHTML: (attributes) => {
39
+ return {
40
+ 'data-wrap-text': attributes.wrapText,
41
+ };
42
+ },
43
+ }
44
+ };
45
+ },
46
+ content: 'text*',
47
+ marks: '_',
48
+ });
components/extensions/CustomImageExtension.ts ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import Image from '@tiptap/extension-image';
3
+ import { ReactNodeViewRenderer } from '@tiptap/react';
4
+ import { ResizableImageComponent } from './ResizableImageComponent';
5
+
6
+ export const CustomImageExtension = Image.extend({
7
+ addAttributes() {
8
+ return {
9
+ ...this.parent?.(),
10
+ width: {
11
+ default: '100%',
12
+ renderHTML: (attributes) => ({
13
+ width: attributes.width,
14
+ }),
15
+ },
16
+ height: {
17
+ default: 'auto',
18
+ renderHTML: (attributes) => ({
19
+ height: attributes.height,
20
+ }),
21
+ },
22
+ align: {
23
+ default: 'center',
24
+ renderHTML: (attributes) => ({
25
+ 'data-align': attributes.align,
26
+ style: `float: ${attributes.align === 'left' ? 'left' : attributes.align === 'right' ? 'right' : 'none'}; display: ${attributes.align === 'center' ? 'block' : 'inline-block'}; margin: ${attributes.align === 'center' ? '0 auto' : '0 1rem 0.5rem 0'}`,
27
+ }),
28
+ },
29
+ href: {
30
+ default: null,
31
+ },
32
+ target: {
33
+ default: '_blank',
34
+ },
35
+ };
36
+ },
37
+
38
+ addNodeView() {
39
+ return ReactNodeViewRenderer(ResizableImageComponent);
40
+ },
41
+ });
components/extensions/ResizableImageComponent.tsx ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import React, { useState, useRef, useEffect } from 'react';
3
+ import { NodeViewWrapper } from '@tiptap/react';
4
+ import { AlignLeft, AlignCenter, AlignRight, Maximize2, Link as LinkIcon, X, Check } from 'lucide-react';
5
+
6
+ export const ResizableImageComponent = (props: any) => {
7
+ const { node, updateAttributes, selected, editor } = props;
8
+ const [width, setWidth] = useState(node.attrs.width || '100%');
9
+ const [height, setHeight] = useState(node.attrs.height || 'auto');
10
+ const [align, setAlign] = useState(node.attrs.align || 'center');
11
+ const [isResizing, setIsResizing] = useState(false);
12
+ const [isLightboxOpen, setIsLightboxOpen] = useState(false);
13
+ const [isLinkMenuOpen, setIsLinkMenuOpen] = useState(false);
14
+ const [tempLink, setTempLink] = useState('');
15
+
16
+ const imageRef = useRef<HTMLImageElement>(null);
17
+ const resizeRef = useRef<{ startX: number; startWidth: number } | null>(null);
18
+
19
+ useEffect(() => {
20
+ setWidth(node.attrs.width || '100%');
21
+ setHeight(node.attrs.height || 'auto');
22
+ setAlign(node.attrs.align || 'center');
23
+ }, [node.attrs]);
24
+
25
+ const handleMouseDown = (e: React.MouseEvent) => {
26
+ e.preventDefault();
27
+ if (imageRef.current) {
28
+ setIsResizing(true);
29
+ resizeRef.current = {
30
+ startX: e.clientX,
31
+ startWidth: imageRef.current.offsetWidth,
32
+ };
33
+ document.addEventListener('mousemove', handleMouseMove);
34
+ document.addEventListener('mouseup', handleMouseUp);
35
+ }
36
+ };
37
+
38
+ const handleMouseMove = (e: MouseEvent) => {
39
+ if (!resizeRef.current) return;
40
+ const diff = e.clientX - resizeRef.current.startX;
41
+ const newWidth = resizeRef.current.startWidth + diff;
42
+ // Limit min width
43
+ if (newWidth > 100) {
44
+ setWidth(`${newWidth}px`);
45
+ }
46
+ };
47
+
48
+ const handleMouseUp = () => {
49
+ setIsResizing(false);
50
+ resizeRef.current = null;
51
+ document.removeEventListener('mousemove', handleMouseMove);
52
+ document.removeEventListener('mouseup', handleMouseUp);
53
+ // Update attributes only on mouse up to avoid too many updates
54
+ if (imageRef.current) {
55
+ updateAttributes({ width: `${imageRef.current.offsetWidth}px` });
56
+ }
57
+ };
58
+
59
+ const handleAlign = (newAlign: 'left' | 'center' | 'right') => {
60
+ setAlign(newAlign);
61
+ updateAttributes({ align: newAlign });
62
+ };
63
+
64
+ const handleLink = () => {
65
+ setTempLink(node.attrs.href || '');
66
+ setIsLinkMenuOpen(true);
67
+ };
68
+
69
+ const saveLink = () => {
70
+ updateAttributes({ href: tempLink || null });
71
+ setIsLinkMenuOpen(false);
72
+ };
73
+
74
+ const handleImageClick = (e: React.MouseEvent) => {
75
+ // Prevent navigation in edit mode
76
+ if (editor.isEditable) {
77
+ e.preventDefault();
78
+ }
79
+
80
+ // Triple click detection handled by TipTap or manual logic if needed.
81
+ // For simplicity, we can use detail property if available or just rely on toolbar.
82
+ if (e.detail === 3 && editor.isEditable) {
83
+ handleLink();
84
+ }
85
+ };
86
+
87
+ const handleDoubleClick = (e: React.MouseEvent) => {
88
+ if (!editor.isEditable && !node.attrs.href) {
89
+ setIsLightboxOpen(true);
90
+ }
91
+ };
92
+
93
+ let containerStyle: React.CSSProperties = {
94
+ display: 'flex',
95
+ justifyContent: align === 'left' ? 'flex-start' : align === 'right' ? 'flex-end' : 'center',
96
+ margin: '1rem 0',
97
+ clear: 'both', // Default to clear
98
+ position: 'relative',
99
+ };
100
+
101
+ // For "Word-like" wrapping, we might use float.
102
+ // However, flexbox centering doesn't work well with float.
103
+ // If align is left/right, we can use float.
104
+ if (align === 'left') {
105
+ containerStyle = {
106
+ float: 'left',
107
+ marginRight: '1rem',
108
+ marginBottom: '0.5rem',
109
+ display: 'inline-block',
110
+ };
111
+ } else if (align === 'right') {
112
+ containerStyle = {
113
+ float: 'right',
114
+ marginLeft: '1rem',
115
+ marginBottom: '0.5rem',
116
+ display: 'inline-block',
117
+ };
118
+ }
119
+
120
+ return (
121
+ <NodeViewWrapper style={containerStyle} className="resizable-image-wrapper group">
122
+ <div className={`relative inline-block transition-all ${selected && editor.isEditable ? 'ring-2 ring-primary rounded-lg' : ''}`}>
123
+ {node.attrs.href ? (
124
+ <a
125
+ href={node.attrs.href}
126
+ target={node.attrs.target}
127
+ onClick={handleImageClick}
128
+ className="block"
129
+ >
130
+ <img
131
+ ref={imageRef}
132
+ src={node.attrs.src}
133
+ alt={node.attrs.alt}
134
+ style={{
135
+ width: width,
136
+ height: height,
137
+ maxWidth: '100%',
138
+ borderRadius: '0.5rem',
139
+ display: 'block',
140
+ }}
141
+ className="transition-shadow shadow-lg"
142
+ />
143
+ </a>
144
+ ) : (
145
+ <img
146
+ ref={imageRef}
147
+ src={node.attrs.src}
148
+ alt={node.attrs.alt}
149
+ style={{
150
+ width: width,
151
+ height: height,
152
+ maxWidth: '100%',
153
+ borderRadius: '0.5rem',
154
+ display: 'block',
155
+ cursor: !editor.isEditable && !node.attrs.href ? 'zoom-in' : 'default'
156
+ }}
157
+ className="transition-shadow shadow-lg"
158
+ onClick={handleImageClick}
159
+ onDoubleClick={handleDoubleClick}
160
+ />
161
+ )}
162
+
163
+ {/* Resize Handle - Only in Edit Mode */}
164
+ {selected && editor.isEditable && (
165
+ <div
166
+ className="absolute bottom-2 right-2 w-4 h-4 bg-primary rounded-full cursor-se-resize shadow-md border-2 border-white z-10"
167
+ onMouseDown={handleMouseDown}
168
+ />
169
+ )}
170
+
171
+ {/* Toolbar (Visible on hover or selected) - Only in Edit Mode */}
172
+ {editor.isEditable && (
173
+ <div className={`absolute top-2 right-2 flex gap-1 bg-black/80 backdrop-blur rounded-lg p-1 opacity-0 group-hover:opacity-100 transition-opacity ${selected ? 'opacity-100' : ''}`}>
174
+ <button
175
+ onClick={() => handleAlign('left')}
176
+ className={`p-1 rounded hover:bg-white/20 ${align === 'left' ? 'text-primary' : 'text-white'}`}
177
+ title="Align Left"
178
+ >
179
+ <AlignLeft size={14} />
180
+ </button>
181
+ <button
182
+ onClick={() => handleAlign('center')}
183
+ className={`p-1 rounded hover:bg-white/20 ${align === 'center' ? 'text-primary' : 'text-white'}`}
184
+ title="Align Center"
185
+ >
186
+ <AlignCenter size={14} />
187
+ </button>
188
+ <button
189
+ onClick={() => handleAlign('right')}
190
+ className={`p-1 rounded hover:bg-white/20 ${align === 'right' ? 'text-primary' : 'text-white'}`}
191
+ title="Align Right"
192
+ >
193
+ <AlignRight size={14} />
194
+ </button>
195
+ <button
196
+ onClick={() => {
197
+ setWidth('100%');
198
+ updateAttributes({ width: '100%' });
199
+ }}
200
+ className="p-1 rounded hover:bg-white/20 text-white"
201
+ title="Full Width"
202
+ >
203
+ <Maximize2 size={14} />
204
+ </button>
205
+ <div className="w-px h-4 bg-white/20 mx-1 self-center" />
206
+ <button
207
+ onClick={handleLink}
208
+ className={`p-1 rounded hover:bg-white/20 ${node.attrs.href ? 'text-primary' : 'text-white'}`}
209
+ title={node.attrs.href ? "Editar Enlace" : "Añadir Enlace"}
210
+ >
211
+ <LinkIcon size={14} />
212
+ </button>
213
+ </div>
214
+ )}
215
+ </div>
216
+
217
+ {/* Link Menu Modal */}
218
+ {isLinkMenuOpen && (
219
+ <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 z-50 bg-[#1e1e1e] border border-white/10 rounded-xl shadow-2xl p-4 min-w-[300px] animate-fade-in flex flex-col gap-3">
220
+ <h4 className="text-sm font-medium text-white">Editar Enlace</h4>
221
+ <input
222
+ type="url"
223
+ value={tempLink}
224
+ onChange={(e) => setTempLink(e.target.value)}
225
+ placeholder="https://ejemplo.com"
226
+ className="w-full bg-black/20 border border-white/10 rounded-lg px-3 py-2 text-sm text-white placeholder-zinc-500 focus:outline-none focus:border-primary transition-colors"
227
+ autoFocus
228
+ onKeyDown={(e) => {
229
+ if (e.key === 'Enter') saveLink();
230
+ if (e.key === 'Escape') setIsLinkMenuOpen(false);
231
+ }}
232
+ />
233
+ <div className="flex gap-2 justify-end">
234
+ <button
235
+ onClick={() => setIsLinkMenuOpen(false)}
236
+ className="px-3 py-1.5 rounded-lg text-sm text-zinc-400 hover:text-white hover:bg-white/5 transition-colors"
237
+ >
238
+ Cancelar
239
+ </button>
240
+ <button
241
+ onClick={saveLink}
242
+ className="px-3 py-1.5 rounded-lg text-sm bg-primary text-background font-medium hover:opacity-90 transition-opacity flex items-center gap-1.5"
243
+ >
244
+ <Check size={14} strokeWidth={2.5} />
245
+ Guardar
246
+ </button>
247
+ </div>
248
+ </div>
249
+ )}
250
+
251
+ {/* Lightbox Overlay */}
252
+ {isLightboxOpen && (
253
+ <div
254
+ className="fixed inset-0 z-[9999] bg-black/90 flex items-center justify-center p-4 animate-fade-in"
255
+ onClick={() => setIsLightboxOpen(false)}
256
+ >
257
+ <button
258
+ className="absolute top-4 right-4 text-white/70 hover:text-white transition-colors"
259
+ onClick={() => setIsLightboxOpen(false)}
260
+ >
261
+ <X size={32} />
262
+ </button>
263
+ <img
264
+ src={node.attrs.src}
265
+ alt={node.attrs.alt}
266
+ className="max-w-full max-h-full object-contain rounded-lg shadow-2xl"
267
+ onClick={(e) => e.stopPropagation()}
268
+ />
269
+ </div>
270
+ )}
271
+ </NodeViewWrapper>
272
+ );
273
+ };
components/extensions/ResizableVideoComponent.tsx ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { useState, useRef, useEffect } from 'react';
2
+ import { NodeViewWrapper } from '@tiptap/react';
3
+ import { AlignLeft, AlignCenter, AlignRight, Maximize2 } from 'lucide-react';
4
+
5
+ export const ResizableVideoComponent = (props: any) => {
6
+ const { node, updateAttributes, selected, editor } = props;
7
+ const [width, setWidth] = useState(node.attrs.width || '100%');
8
+ const [align, setAlign] = useState(node.attrs.align || 'center');
9
+ const [isResizing, setIsResizing] = useState(false);
10
+ const [isMounted, setIsMounted] = useState(false);
11
+
12
+ const containerRef = useRef<HTMLDivElement>(null);
13
+ const resizeRef = useRef<{ startX: number; startWidth: number } | null>(null);
14
+
15
+ useEffect(() => {
16
+ setIsMounted(true);
17
+ setWidth(node.attrs.width || '100%');
18
+ setAlign(node.attrs.align || 'center');
19
+ }, [node.attrs]);
20
+
21
+ const handleMouseDown = (e: React.MouseEvent) => {
22
+ e.preventDefault();
23
+ if (containerRef.current) {
24
+ setIsResizing(true);
25
+ resizeRef.current = {
26
+ startX: e.clientX,
27
+ startWidth: containerRef.current.offsetWidth,
28
+ };
29
+ document.addEventListener('mousemove', handleMouseMove);
30
+ document.addEventListener('mouseup', handleMouseUp);
31
+ }
32
+ };
33
+
34
+ const handleMouseMove = (e: MouseEvent) => {
35
+ if (!resizeRef.current) return;
36
+ const diff = e.clientX - resizeRef.current.startX;
37
+ const newWidth = resizeRef.current.startWidth + diff;
38
+ // Limit min width
39
+ if (newWidth > 200) {
40
+ setWidth(`${newWidth}px`);
41
+ }
42
+ };
43
+
44
+ const handleMouseUp = () => {
45
+ setIsResizing(false);
46
+ resizeRef.current = null;
47
+ document.removeEventListener('mousemove', handleMouseMove);
48
+ document.removeEventListener('mouseup', handleMouseUp);
49
+ // Update attributes only on mouse up
50
+ if (containerRef.current) {
51
+ updateAttributes({ width: `${containerRef.current.offsetWidth}px` });
52
+ }
53
+ };
54
+
55
+ const handleAlign = (newAlign: 'left' | 'center' | 'right') => {
56
+ setAlign(newAlign);
57
+ updateAttributes({ align: newAlign });
58
+ };
59
+
60
+ let containerStyle: React.CSSProperties = {
61
+ display: 'flex',
62
+ justifyContent: align === 'left' ? 'flex-start' : align === 'right' ? 'flex-end' : 'center',
63
+ margin: '1rem 0',
64
+ clear: 'both',
65
+ position: 'relative',
66
+ };
67
+
68
+ if (align === 'left') {
69
+ containerStyle = {
70
+ float: 'left',
71
+ marginRight: '1rem',
72
+ marginBottom: '0.5rem',
73
+ display: 'inline-block',
74
+ };
75
+ } else if (align === 'right') {
76
+ containerStyle = {
77
+ float: 'right',
78
+ marginLeft: '1rem',
79
+ marginBottom: '0.5rem',
80
+ display: 'inline-block',
81
+ };
82
+ }
83
+
84
+ // Ensure URL is valid string
85
+ const videoUrl = typeof node.attrs.src === 'string' ? node.attrs.src.trim() : '';
86
+
87
+ const getEmbedConfig = (url: string) => {
88
+ // 1. Dropbox (Tratamiento especial: video nativo)
89
+ if (url.includes('dropbox.com')) {
90
+ try {
91
+ const urlObj = new URL(url);
92
+ urlObj.searchParams.set('raw', '1');
93
+ urlObj.searchParams.delete('dl');
94
+ return {
95
+ type: 'video',
96
+ src: urlObj.toString()
97
+ };
98
+ } catch (e) {
99
+ return {
100
+ type: 'video',
101
+ src: url
102
+ };
103
+ }
104
+ }
105
+
106
+ // 2. Archivos directos (Video nativo)
107
+ if (url.match(/\.(mp4|mov|webm|ogg)$/i)) {
108
+ return { type: 'video', src: url };
109
+ }
110
+
111
+ // 3. Transformaciones para Iframe
112
+ let embedUrl = url;
113
+
114
+ // YouTube
115
+ if (url.includes('youtube.com') || url.includes('youtu.be')) {
116
+ const id = url.match(/.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|&v=)([^#&?]*).*/)?.[2];
117
+ if (id) embedUrl = `https://www.youtube.com/embed/${id}`;
118
+ }
119
+ // Vimeo
120
+ else if (url.includes('vimeo.com')) {
121
+ const id = url.match(/vimeo\.com\/(?:channels\/(?:\w+\/)?|groups\/(?:[^\/]*)\/videos\/|album\/(?:\d+)\/video\/|video\/|)(\d+)/)?.[1];
122
+ if (id) embedUrl = `https://player.vimeo.com/video/${id}`;
123
+ }
124
+ // Google Drive
125
+ else if (url.includes('drive.google.com')) {
126
+ embedUrl = url.replace(/\/view.*/, '/preview').replace(/\/open.*/, '/preview');
127
+ }
128
+ // Facebook
129
+ else if (url.includes('facebook.com') || url.includes('fb.watch')) {
130
+ embedUrl = `https://www.facebook.com/plugins/video.php?href=${encodeURIComponent(url)}&show_text=false`;
131
+ }
132
+ // MEGA
133
+ else if (url.includes('mega.nz')) {
134
+ // Mega suele requerir formato embed, intentamos conversión simple si es enlace de archivo
135
+ if (!url.includes('/embed')) embedUrl = url.replace('/file/', '/embed/');
136
+ }
137
+ // TikTok (Experimental - requiere video ID)
138
+ else if (url.includes('tiktok.com')) {
139
+ const videoId = url.match(/video\/(\d+)/)?.[1];
140
+ if (videoId) embedUrl = `https://www.tiktok.com/embed/v2/${videoId}`;
141
+ }
142
+
143
+ return { type: 'iframe', src: embedUrl };
144
+ };
145
+
146
+ const embedConfig = getEmbedConfig(videoUrl);
147
+
148
+ return (
149
+ <NodeViewWrapper style={containerStyle} className="resizable-video-wrapper group">
150
+ <div
151
+ ref={containerRef}
152
+ className={`relative inline-block transition-all ${selected && editor.isEditable ? 'ring-2 ring-primary rounded-lg' : ''}`}
153
+ style={{
154
+ width: width,
155
+ maxWidth: '100%',
156
+ }}
157
+ >
158
+ <div className="rounded-lg overflow-hidden shadow-lg bg-black pointer-events-auto relative pt-[56.25%]">
159
+ {/* Overlay to capture clicks when not selected */}
160
+ {!selected && editor.isEditable && (
161
+ <div className="absolute inset-0 z-10 bg-transparent cursor-pointer" />
162
+ )}
163
+
164
+ {isMounted && videoUrl ? (
165
+ embedConfig.type === 'iframe' ? (
166
+ <iframe
167
+ src={embedConfig.src}
168
+ title="Video player"
169
+ frameBorder="0"
170
+ allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
171
+ allowFullScreen
172
+ className={`absolute top-0 left-0 w-full h-full ${selected && !isResizing ? 'pointer-events-auto' : 'pointer-events-none'}`}
173
+ />
174
+ ) : (
175
+ <video
176
+ src={embedConfig.src}
177
+ controls
178
+ className={`absolute top-0 left-0 w-full h-full object-contain bg-black ${selected && !isResizing ? 'pointer-events-auto' : 'pointer-events-none'}`}
179
+ />
180
+ )
181
+ ) : (
182
+ <div className="absolute inset-0 flex items-center justify-center text-white/50 bg-zinc-900">
183
+ {videoUrl ? 'Cargando video...' : 'Sin URL de video'}
184
+ </div>
185
+ )}
186
+ </div>
187
+
188
+
189
+
190
+ {/* Resize Handle - Only in Edit Mode */}
191
+ {selected && editor.isEditable && (
192
+ <div
193
+ className="absolute bottom-2 right-2 w-4 h-4 bg-primary rounded-full cursor-se-resize shadow-md border-2 border-white z-50"
194
+ onMouseDown={handleMouseDown}
195
+ />
196
+ )}
197
+
198
+ {/* Toolbar (Visible on hover or selected) - Only in Edit Mode */}
199
+ {editor.isEditable && (
200
+ <div className={`absolute top-2 right-2 flex gap-1 bg-black/80 backdrop-blur rounded-lg p-1 opacity-0 group-hover:opacity-100 transition-opacity ${selected ? 'opacity-100' : ''} z-50`}>
201
+ <button
202
+ onClick={() => handleAlign('left')}
203
+ className={`p-1 rounded hover:bg-white/20 ${align === 'left' ? 'text-primary' : 'text-white'}`}
204
+ title="Align Left"
205
+ >
206
+ <AlignLeft size={14} />
207
+ </button>
208
+ <button
209
+ onClick={() => handleAlign('center')}
210
+ className={`p-1 rounded hover:bg-white/20 ${align === 'center' ? 'text-primary' : 'text-white'}`}
211
+ title="Align Center"
212
+ >
213
+ <AlignCenter size={14} />
214
+ </button>
215
+ <button
216
+ onClick={() => handleAlign('right')}
217
+ className={`p-1 rounded hover:bg-white/20 ${align === 'right' ? 'text-primary' : 'text-white'}`}
218
+ title="Align Right"
219
+ >
220
+ <AlignRight size={14} />
221
+ </button>
222
+ <button
223
+ onClick={() => {
224
+ setWidth('100%');
225
+ updateAttributes({ width: '100%' });
226
+ }}
227
+ className="p-1 rounded hover:bg-white/20 text-white"
228
+ title="Full Width"
229
+ >
230
+ <Maximize2 size={14} />
231
+ </button>
232
+ </div>
233
+ )}
234
+ </div>
235
+ </NodeViewWrapper>
236
+ );
237
+ };
components/extensions/UniversalVideoExtension.ts ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Node, mergeAttributes, PasteRule } from '@tiptap/core';
2
+ import { ReactNodeViewRenderer } from '@tiptap/react';
3
+ import { ResizableVideoComponent } from './ResizableVideoComponent';
4
+
5
+ export const UniversalVideoExtension = Node.create({
6
+ name: 'universalVideo',
7
+
8
+ group: 'block',
9
+
10
+ atom: true,
11
+
12
+ addAttributes() {
13
+ return {
14
+ src: {
15
+ default: null,
16
+ parseHTML: element => element.getAttribute('data-src'),
17
+ renderHTML: attributes => ({
18
+ 'data-src': attributes.src,
19
+ }),
20
+ },
21
+ width: {
22
+ default: '100%',
23
+ parseHTML: element => element.getAttribute('data-width') || element.style.width,
24
+ renderHTML: (attributes) => ({
25
+ 'data-width': attributes.width,
26
+ style: `width: ${attributes.width}`,
27
+ }),
28
+ },
29
+ align: {
30
+ default: 'center',
31
+ parseHTML: element => element.getAttribute('data-align'),
32
+ renderHTML: (attributes) => ({
33
+ 'data-align': attributes.align,
34
+ style: `float: ${attributes.align === 'left' ? 'left' : attributes.align === 'right' ? 'right' : 'none'}; display: ${attributes.align === 'center' ? 'block' : 'inline-block'}; margin: ${attributes.align === 'center' ? '0 auto' : '0 1rem 0.5rem 0'}`,
35
+ }),
36
+ },
37
+ };
38
+ },
39
+
40
+ parseHTML() {
41
+ return [
42
+ {
43
+ tag: 'div[data-type="universal-video"]',
44
+ },
45
+ ];
46
+ },
47
+
48
+ renderHTML({ HTMLAttributes }) {
49
+ return ['div', mergeAttributes(HTMLAttributes, { 'data-type': 'universal-video' })];
50
+ },
51
+
52
+ addNodeView() {
53
+ return ReactNodeViewRenderer(ResizableVideoComponent);
54
+ },
55
+
56
+ addPasteRules() {
57
+ return [
58
+ new PasteRule({
59
+ find: /^(https?:\/\/)?(www\.)?(youtube\.com|youtu\.be)\/.+$/g,
60
+ handler: ({ state, range, match }) => {
61
+ const url = match[0];
62
+ let finalUrl = url;
63
+ if (!finalUrl.match(/^https?:\/\//)) {
64
+ finalUrl = `https://${finalUrl}`;
65
+ }
66
+
67
+ state.tr.replaceWith(range.from, range.to, this.type.create({ src: finalUrl }));
68
+ },
69
+ }),
70
+ ];
71
+ },
72
+ });
index.css ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @tailwind base;
2
+ @tailwind components;
3
+ @tailwind utilities;
4
+
5
+ :root {
6
+ --foreground-rgb: 0, 0, 0;
7
+ --background-start-rgb: 214, 219, 220;
8
+ --background-end-rgb: 255, 255, 255;
9
+ }
10
+
11
+ @media (prefers-color-scheme: dark) {
12
+ :root {
13
+ --foreground-rgb: 255, 255, 255;
14
+ --background-start-rgb: 0, 0, 0;
15
+ --background-end-rgb: 0, 0, 0;
16
+ }
17
+ }
18
+
19
+ body {
20
+ color: rgb(var(--foreground-rgb));
21
+ background: linear-gradient(to bottom,
22
+ transparent,
23
+ rgb(var(--background-end-rgb))) rgb(var(--background-start-rgb));
24
+ }
25
+
26
+ @layer utilities {
27
+ .text-balance {
28
+ text-wrap: balance;
29
+ }
30
+ }
31
+
32
+ /* Elimina el margen superior del primer elemento para que empiece arriba del todo */
33
+ .ProseMirror>*:first-child {
34
+ margin-top: 0 !important;
35
+ }
36
+
37
+ .ProseMirror p {
38
+ margin-top: 0.5rem;
39
+ margin-bottom: 0.5rem;
40
+ line-height: 1.5;
41
+ }
42
+
43
+ .ProseMirror ul {
44
+ list-style-type: disc;
45
+ padding-left: 1.5rem;
46
+ margin: 1rem 0;
47
+ }
48
+
49
+ .ProseMirror ol {
50
+ list-style-type: decimal;
51
+ padding-left: 1.5rem;
52
+ margin: 1rem 0;
53
+ }
54
+
55
+ .ProseMirror li {
56
+ margin-bottom: 0.25rem;
57
+ }
58
+
59
+ /* Custom Text Selection */
60
+ ::selection {
61
+ background-color: rgba(168, 85, 247, 0.25);
62
+ /* Purple-500 with low opacity */
63
+ color: inherit;
64
+ /* Keep original text color */
65
+ }
66
+
67
+ /* Specific override for ProseMirror to ensure it takes precedence */
68
+ .ProseMirror ::selection {
69
+ background-color: rgba(168, 85, 247, 0.25);
70
+ color: inherit;
71
+ }
72
+
73
+ /* Force no underline for links when configured */
74
+ .no-underline-link {
75
+ text-decoration: none !important;
76
+ }
index.html ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="es">
3
+
4
+ <head>
5
+ <meta charset="UTF-8" />
6
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
7
+ <title>CodeByDante</title>
8
+ <script src="https://cdn.tailwindcss.com"></script>
9
+ <script>
10
+ tailwind.config = {
11
+ theme: {
12
+ extend: {
13
+ colors: {
14
+ background: '#121212',
15
+ primary: '#bb86fc',
16
+ surface: '#1e1e1e',
17
+ surfaceHover: '#2d2d2d',
18
+ }
19
+ }
20
+ }
21
+ }
22
+ </script>
23
+ <style>
24
+ body {
25
+ background-color: #121212;
26
+ color: #e0e0e0;
27
+ }
28
+
29
+ /* Custom Scrollbar */
30
+ ::-webkit-scrollbar {
31
+ width: 8px;
32
+ }
33
+
34
+ ::-webkit-scrollbar-track {
35
+ background: #121212;
36
+ }
37
+
38
+ ::-webkit-scrollbar-thumb {
39
+ background: #333;
40
+ border-radius: 4px;
41
+ }
42
+
43
+ ::-webkit-scrollbar-thumb:hover {
44
+ background: #bb86fc;
45
+ }
46
+ </style>
47
+ <script type="importmap">
48
+ {
49
+ "imports": {
50
+ "react": "https://aistudiocdn.com/react@^19.2.0",
51
+ "react-dom/": "https://aistudiocdn.com/react-dom@^19.2.0/",
52
+ "react/": "https://aistudiocdn.com/react@^19.2.0/",
53
+ "@google/genai": "https://aistudiocdn.com/@google/genai@^1.30.0",
54
+ "lucide-react": "https://aistudiocdn.com/lucide-react@^0.554.0",
55
+ "firebase/app": "https://www.gstatic.com/firebasejs/10.8.0/firebase-app.js",
56
+ "firebase/firestore": "https://www.gstatic.com/firebasejs/10.8.0/firebase-firestore.js",
57
+ "firebase/": "https://aistudiocdn.com/firebase@^12.6.0/",
58
+ "react-markdown": "https://aistudiocdn.com/react-markdown@^10.1.0",
59
+ "@vitejs/plugin-react": "https://aistudiocdn.com/@vitejs/plugin-react@^5.1.1",
60
+ "vite": "https://aistudiocdn.com/vite@^7.2.4",
61
+ "remark-gfm": "https://aistudiocdn.com/remark-gfm@^4.0.1",
62
+ "path": "https://aistudiocdn.com/path@^0.12.7",
63
+ "rehype-raw": "https://aistudiocdn.com/rehype-raw@^7.0.0",
64
+ "rehype-sanitize": "https://aistudiocdn.com/rehype-sanitize@^6.0.0"
65
+ }
66
+ }
67
+ </script>
68
+ <link rel="preconnect" href="https://fonts.googleapis.com">
69
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
70
+ <link
71
+ href="https://fonts.googleapis.com/css2?family=Dancing+Script:wght@400..700&family=Fira+Code:wght@300..700&family=Inter:wght@100..900&family=JetBrains+Mono:ital,wght@0,100..800;1,100..800&family=Merriweather:ital,wght@0,300;0,400;0,700;0,900;1,300;1,400;1,700;1,900&family=Pacifico&family=Playfair+Display:ital,wght@0,400..900;1,400..900&family=Roboto:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&family=Source+Code+Pro:ital,wght@0,200..900;1,200..900&display=swap"
72
+ rel="stylesheet">
73
+ <link rel="stylesheet" href="/index.css">
74
+ </head>
75
+
76
+ <body>
77
+ <div id="root"></div>
78
+ <script type="module" src="/index.tsx"></script>
79
+ </body>
80
+
81
+ </html>
index.tsx ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React from 'react';
2
+ import ReactDOM from 'react-dom/client';
3
+ import App from './App';
4
+
5
+ const rootElement = document.getElementById('root');
6
+ if (!rootElement) {
7
+ throw new Error("Could not find root element to mount to");
8
+ }
9
+
10
+ const root = ReactDOM.createRoot(rootElement);
11
+ root.render(
12
+ <React.StrictMode>
13
+ <App />
14
+ </React.StrictMode>
15
+ );
metadata.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "name": "CodeByDante",
3
+ "description": "Una base de conocimiento personal moderna y oscura, organizada por bloques con capacidades de IA.",
4
+ "requestFramePermissions": []
5
+ }
package-lock.json ADDED
The diff for this file is too large to render. See raw diff
 
package.json ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "codebydante",
3
+ "private": true,
4
+ "version": "0.0.0",
5
+ "type": "module",
6
+ "scripts": {
7
+ "dev": "vite",
8
+ "build": "vite build",
9
+ "preview": "vite preview"
10
+ },
11
+ "dependencies": {
12
+ "@google/genai": "^1.30.0",
13
+ "@google/generative-ai": "^0.24.1",
14
+ "@tiptap/extension-blockquote": "^3.11.1",
15
+ "@tiptap/extension-image": "^3.11.1",
16
+ "@tiptap/extension-link": "^3.11.1",
17
+ "@tiptap/extension-text-align": "^3.11.1",
18
+ "@tiptap/pm": "^3.11.1",
19
+ "@tiptap/react": "^3.11.1",
20
+ "@tiptap/starter-kit": "^3.11.1",
21
+ "@types/react-syntax-highlighter": "^15.5.13",
22
+ "firebase": "^12.6.0",
23
+ "framer-motion": "^12.23.25",
24
+ "lucide-react": "^0.554.0",
25
+ "react": "^19.2.0",
26
+ "react-dom": "^19.2.0",
27
+ "react-markdown": "^10.1.0",
28
+ "react-player": "^3.4.0",
29
+ "react-syntax-highlighter": "^16.1.0",
30
+ "rehype-raw": "^7.0.0",
31
+ "rehype-sanitize": "^6.0.0",
32
+ "remark-gfm": "^4.0.1"
33
+ },
34
+ "devDependencies": {
35
+ "@types/node": "^22.14.0",
36
+ "@vitejs/plugin-react": "^5.0.0",
37
+ "typescript": "~5.8.2",
38
+ "vite": "^6.2.0"
39
+ }
40
+ }
services/aiService.ts ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { GoogleGenerativeAI } from "@google/generative-ai";
2
+
3
+ // Use environment variable, or fallback to the key provided by the user for immediate fix
4
+ const apiKey = import.meta.env.VITE_GEMINI_API_KEY || "AIzaSyCVIbMfcOuhr51iZ5wKGl7y7gBfm-cm63s";
5
+
6
+ if (!apiKey) {
7
+ console.warn("VITE_GEMINI_API_KEY is not set.");
8
+ }
9
+
10
+ const genAI = new GoogleGenerativeAI(apiKey);
11
+ // Prioritize the model that was verified to work: gemini-2.0-flash-exp
12
+ const availableModels = ["gemini-2.0-flash-exp", "gemini-1.5-flash", "gemini-pro"];
13
+
14
+ // Helper to clean response text
15
+ const cleanAIResponse = (text: string): string => {
16
+ if (!text) return "";
17
+ // Remove markdown code blocks (```html, ```xml, ```, etc.)
18
+ let cleaned = text.replace(/```(?:html|xml|markdown)?\s*([\s\S]*?)```/gi, "$1");
19
+ // Remove any remaining backticks if they are wrapping the whole content
20
+ cleaned = cleaned.trim();
21
+ if (cleaned.startsWith("`") && cleaned.endsWith("`")) {
22
+ cleaned = cleaned.slice(1, -1);
23
+ }
24
+ return cleaned;
25
+ };
26
+
27
+ export const expandSummary = async (text: string): Promise<string> => {
28
+ if (!text || text.length < 3) return text;
29
+
30
+ let lastError;
31
+
32
+ for (const modelName of availableModels) {
33
+ try {
34
+ const model = genAI.getGenerativeModel({ model: modelName });
35
+ const prompt = `
36
+ Actúa como un redactor técnico experto.
37
+ El usuario te dará un texto corto o un enlace. Tu trabajo es generar un resumen estructurado y detallado.
38
+
39
+ Entrada del usuario: "${text}"
40
+
41
+ Instrucciones:
42
+ 1. Explica qué es (tecnología, herramienta, concepto).
43
+ 2. Si es un enlace, infiere de qué trata por el nombre o contexto.
44
+ 3. Menciona para qué sirve y sus características principales.
45
+ 4. Usa un tono profesional pero directo.
46
+ 5. No uses markdown complejo (como headers #), usa texto plano o saltos de línea simples.
47
+ 6. Mantén la respuesta concisa pero informativa (máximo 150 palabras).
48
+
49
+ Solo devuelve el texto del resumen mejorado.
50
+ `;
51
+
52
+ const result = await model.generateContent(prompt);
53
+ const response = await result.response;
54
+ return cleanAIResponse(response.text());
55
+ } catch (error: any) {
56
+ console.warn(`Model ${modelName} failed:`, error.message);
57
+ lastError = error;
58
+ // Continue to next model
59
+ }
60
+ }
61
+
62
+ // If all failed
63
+ console.error("All AI models failed:", lastError);
64
+ const rawMessage = lastError?.message || String(lastError);
65
+
66
+ if (rawMessage.includes("API key")) {
67
+ throw new Error("Clave API inválida o no configurada.");
68
+ } else if (rawMessage.includes("403")) {
69
+ throw new Error("Acceso denegado. Revisa tu clave API.");
70
+ } else if (rawMessage.includes("404")) {
71
+ throw new Error("Modelos de IA no encontrados para esta clave.");
72
+ }
73
+
74
+ throw new Error(`Error de IA: ${rawMessage}`);
75
+ };
76
+
77
+ export const generateFromInstructions = async (
78
+ currentContent: string,
79
+ instructions: string,
80
+ context?: string
81
+ ): Promise<string> => {
82
+ let lastError;
83
+
84
+ for (const modelName of availableModels) {
85
+ try {
86
+ const model = genAI.getGenerativeModel({ model: modelName });
87
+
88
+ let prompt = "";
89
+
90
+ if (!currentContent || currentContent.trim().length === 0) {
91
+ // Generation mode
92
+ prompt = `
93
+ Actúa como un asistente de redacción experto y creativo.
94
+
95
+ Instrucciones del usuario: "${instructions}"
96
+
97
+ Contexto adicional: ${context || "Ninguno"}
98
+
99
+ Tu tarea es generar contenido nuevo basándote EXCLUSIVAMENTE en las instrucciones del usuario.
100
+ Usa un formato HTML limpio.
101
+ - Para listas usa <ul>/<li>.
102
+ - Para bloques de código usa <pre><code>...</code></pre>.
103
+ - Para negritas <b> o <strong>.
104
+
105
+ SI EL USUARIO PIDE COMPONENTES ESPECIALES, USA ESTOS FORMATOS:
106
+ 1. **Botones**: <a data-type="custom-button" href="URL" data-variant="visit|download|github" data-background-color="#COLOR">Texto</a>
107
+ 2. **Videos**: <div data-type="universal-video" data-src="URL_YOUTUBE" data-width="100%"></div>
108
+ 3. **Citas (Blockquotes)**: <blockquote style="border-left-color: #COLOR; border-left-width: 4px; background-color: transparent;">Texto</blockquote>
109
+
110
+ NO uses markdown (como ** o #).
111
+ Responde SOLO con el HTML generado, sin etiquetas <html> ni <body>.
112
+ `;
113
+ } else {
114
+ // Improvement/Edit mode
115
+ prompt = `
116
+ Actúa como un editor experto.
117
+
118
+ Contenido actual (HTML):
119
+ """
120
+ ${currentContent}
121
+ """
122
+
123
+ Instrucciones de modificación: "${instructions}"
124
+
125
+ Tu tarea es reescribir, mejorar o modificar el contenido actual siguiendo las instrucciones.
126
+ Mantén el estilo general pero aplica los cambios solicitados.
127
+ Devuelve el resultado en HTML válido compatible con Tiptap.
128
+
129
+ Responde SOLO con el contenido mejorado en HTML.
130
+ `;
131
+ }
132
+
133
+ const result = await model.generateContent(prompt);
134
+ const response = await result.response;
135
+ return cleanAIResponse(response.text());
136
+ } catch (error: any) {
137
+ console.warn(`Model ${modelName} failed for instructions:`, error.message);
138
+ lastError = error;
139
+ }
140
+ }
141
+
142
+ throw new Error(`Fallo en IA: ${lastError?.message || "No se pudo generar contenido."}`);
143
+ };
services/codeStyleService.ts ADDED
@@ -0,0 +1,351 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { initializeApp } from 'firebase/app';
2
+ import {
3
+ getFirestore,
4
+ collection,
5
+ doc,
6
+ getDoc,
7
+ setDoc,
8
+ onSnapshot
9
+ } from 'firebase/firestore';
10
+
11
+ const firebaseConfig = {
12
+ apiKey: "AIzaSyAH3jvbe0_QLzIuuv5kTMK8246HNvohvfE",
13
+ authDomain: "twistedbrody-9d163.firebaseapp.com",
14
+ projectId: "twistedbrody-9d163",
15
+ storageBucket: "twistedbrody-9d163.firebasestorage.app",
16
+ messagingSenderId: "733213514129",
17
+ appId: "1:733213514129:web:e9694684f5c3994ed06230",
18
+ measurementId: "G-N8TQ7MY42W"
19
+ };
20
+
21
+ const app = initializeApp(firebaseConfig);
22
+ const db = getFirestore(app);
23
+ const COLLECTION_NAME = 'code_style_config';
24
+
25
+ export interface GeneralConfig { }
26
+
27
+ export interface QuoteStyleConfig {
28
+ textColor: string;
29
+ bgColor: string;
30
+ borderColor: string;
31
+ borderWidth: string;
32
+ fontSize: string;
33
+ padding: string;
34
+ borderRadius: string;
35
+ italic: boolean;
36
+ width: string;
37
+ height: string;
38
+ showCopyButton: boolean;
39
+ showDownloadButton: boolean;
40
+ collapsible: boolean;
41
+ fontFamily: string;
42
+ isCodeFont: boolean;
43
+ }
44
+
45
+ export interface CodeStyleConfig {
46
+ textColor: string;
47
+ bgColor: string;
48
+ opacity: number;
49
+ width: string;
50
+ height: string;
51
+ fontSize: string;
52
+ borderRadius: string;
53
+ fontFamily: string;
54
+ showBackground: boolean;
55
+ lineHeight: string;
56
+ collapsible: boolean;
57
+ showLineNumbers: boolean;
58
+ wrapText: boolean;
59
+ }
60
+
61
+ export interface LinkStyleConfig {
62
+ underlineEnabled: boolean;
63
+ }
64
+
65
+ export interface ButtonStyleConfig {
66
+ width: string;
67
+ height: string;
68
+ backgroundColor: string;
69
+ textColor: string;
70
+ borderRadius: string;
71
+ }
72
+
73
+ export interface StyleConfig {
74
+ general: GeneralConfig;
75
+ code: CodeStyleConfig;
76
+ quote: QuoteStyleConfig;
77
+ link: LinkStyleConfig;
78
+ button: ButtonStyleConfig;
79
+ showCopyButton: boolean;
80
+ }
81
+
82
+ export const DEFAULT_GENERAL_STYLE: GeneralConfig = {};
83
+
84
+ export const DEFAULT_QUOTE_STYLE: QuoteStyleConfig = {
85
+ textColor: '#9ca3af',
86
+ bgColor: 'rgba(255, 255, 255, 0.06)',
87
+ borderColor: '#4a4a4a',
88
+ borderWidth: '7px',
89
+ fontSize: '0.9em',
90
+ padding: '8px',
91
+ borderRadius: '3px',
92
+ italic: true,
93
+ width: 'auto',
94
+ height: 'auto',
95
+ showCopyButton: true,
96
+ showDownloadButton: true,
97
+ collapsible: false,
98
+ fontFamily: 'inherit',
99
+ isCodeFont: true
100
+ };
101
+
102
+ export const DEFAULT_CODE_STYLE: CodeStyleConfig = {
103
+ textColor: '#c0c0c0',
104
+ bgColor: 'rgba(85, 85, 85, 0.55)',
105
+ opacity: 55,
106
+ width: 'auto',
107
+ height: 'auto',
108
+ fontSize: '0.85em',
109
+ borderRadius: '4px',
110
+ fontFamily: "'Consolas', 'Monaco', monospace",
111
+ showBackground: true,
112
+ lineHeight: '1.5',
113
+ collapsible: true, // Collapsible enabled by default for new blocks
114
+ showLineNumbers: false,
115
+ wrapText: false
116
+ };
117
+
118
+ export const DEFAULT_LINK_STYLE: LinkStyleConfig = {
119
+ underlineEnabled: true
120
+ };
121
+
122
+ export const DEFAULT_BUTTON_STYLE: ButtonStyleConfig = {
123
+ width: 'auto',
124
+ height: 'auto',
125
+ backgroundColor: '#bb86fc', // Primary color
126
+ textColor: '#ffffff',
127
+ borderRadius: '8px'
128
+ };
129
+
130
+ export const DEFAULT_STYLE_CONFIG: StyleConfig = {
131
+ general: DEFAULT_GENERAL_STYLE,
132
+ code: DEFAULT_CODE_STYLE,
133
+ quote: DEFAULT_QUOTE_STYLE,
134
+ link: DEFAULT_LINK_STYLE,
135
+ button: DEFAULT_BUTTON_STYLE,
136
+ showCopyButton: false
137
+ };
138
+
139
+ const getUserId = (): string => {
140
+ let userId = localStorage.getItem('codebydate_user_id');
141
+ if (!userId) {
142
+ userId = `user_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
143
+ localStorage.setItem('codebydate_user_id', userId);
144
+ }
145
+ return userId;
146
+ };
147
+
148
+ export const saveStyleConfigToCloud = async (config: StyleConfig): Promise<void> => {
149
+ try {
150
+ const userId = getUserId();
151
+ const docRef = doc(db, COLLECTION_NAME, userId);
152
+
153
+ await setDoc(docRef, {
154
+ ...config,
155
+ userId,
156
+ updatedAt: new Date().toISOString()
157
+ }, { merge: true });
158
+
159
+ console.log('Style config saved to cloud:', config);
160
+ } catch (error) {
161
+ console.error('Error saving style config to cloud:', error);
162
+ throw error;
163
+ }
164
+ };
165
+
166
+ export const loadStyleConfigFromCloud = async (): Promise<StyleConfig | null> => {
167
+ try {
168
+ const userId = getUserId();
169
+ const docRef = doc(db, COLLECTION_NAME, userId);
170
+ const docSnap = await getDoc(docRef);
171
+
172
+ if (docSnap.exists()) {
173
+ const data = docSnap.data();
174
+ return {
175
+ general: {},
176
+ code: {
177
+ textColor: data.code?.textColor || DEFAULT_CODE_STYLE.textColor,
178
+ bgColor: data.code?.bgColor || DEFAULT_CODE_STYLE.bgColor,
179
+ opacity: data.code?.opacity || DEFAULT_CODE_STYLE.opacity,
180
+ width: data.code?.width || DEFAULT_CODE_STYLE.width,
181
+ height: data.code?.height || DEFAULT_CODE_STYLE.height,
182
+ fontSize: data.code?.fontSize || DEFAULT_CODE_STYLE.fontSize,
183
+ borderRadius: data.code?.borderRadius || DEFAULT_CODE_STYLE.borderRadius,
184
+ fontFamily: data.code?.fontFamily || DEFAULT_CODE_STYLE.fontFamily,
185
+ showBackground: data.code?.showBackground !== undefined ? data.code.showBackground : DEFAULT_CODE_STYLE.showBackground,
186
+ lineHeight: data.code?.lineHeight || DEFAULT_CODE_STYLE.lineHeight,
187
+ collapsible: data.code?.collapsible !== undefined ? data.code.collapsible : DEFAULT_CODE_STYLE.collapsible,
188
+ showLineNumbers: data.code?.showLineNumbers !== undefined ? data.code.showLineNumbers : DEFAULT_CODE_STYLE.showLineNumbers,
189
+ wrapText: data.code?.wrapText !== undefined ? data.code.wrapText : DEFAULT_CODE_STYLE.wrapText
190
+ },
191
+ quote: {
192
+ textColor: data.quote?.textColor || DEFAULT_QUOTE_STYLE.textColor,
193
+ bgColor: data.quote?.bgColor || DEFAULT_QUOTE_STYLE.bgColor,
194
+ borderColor: data.quote?.borderColor || DEFAULT_QUOTE_STYLE.borderColor,
195
+ borderWidth: data.quote?.borderWidth || DEFAULT_QUOTE_STYLE.borderWidth,
196
+ fontSize: data.quote?.fontSize || DEFAULT_QUOTE_STYLE.fontSize,
197
+ padding: data.quote?.padding || DEFAULT_QUOTE_STYLE.padding,
198
+ borderRadius: data.quote?.borderRadius || DEFAULT_QUOTE_STYLE.borderRadius,
199
+ italic: data.quote?.italic !== undefined ? data.quote.italic : DEFAULT_QUOTE_STYLE.italic,
200
+ width: data.quote?.width || DEFAULT_QUOTE_STYLE.width,
201
+ height: data.quote?.height || DEFAULT_QUOTE_STYLE.height,
202
+ showCopyButton: data.quote?.showCopyButton !== undefined ? data.quote.showCopyButton : DEFAULT_QUOTE_STYLE.showCopyButton,
203
+ showDownloadButton: data.quote?.showDownloadButton !== undefined ? data.quote.showDownloadButton : DEFAULT_QUOTE_STYLE.showDownloadButton,
204
+ collapsible: data.quote?.collapsible !== undefined ? data.quote.collapsible : DEFAULT_QUOTE_STYLE.collapsible,
205
+ fontFamily: data.quote?.fontFamily || DEFAULT_QUOTE_STYLE.fontFamily,
206
+ isCodeFont: data.quote?.isCodeFont !== undefined ? data.quote.isCodeFont : DEFAULT_QUOTE_STYLE.isCodeFont,
207
+ },
208
+ link: {
209
+ underlineEnabled: data.link?.underlineEnabled !== undefined ? data.link.underlineEnabled : DEFAULT_LINK_STYLE.underlineEnabled
210
+ },
211
+ button: {
212
+ width: data.button?.width || DEFAULT_BUTTON_STYLE.width,
213
+ height: data.button?.height || DEFAULT_BUTTON_STYLE.height,
214
+ backgroundColor: data.button?.backgroundColor || DEFAULT_BUTTON_STYLE.backgroundColor,
215
+ textColor: data.button?.textColor || DEFAULT_BUTTON_STYLE.textColor,
216
+ borderRadius: data.button?.borderRadius || DEFAULT_BUTTON_STYLE.borderRadius
217
+ },
218
+ showCopyButton: data.showCopyButton !== undefined ? data.showCopyButton : DEFAULT_STYLE_CONFIG.showCopyButton
219
+ };
220
+ }
221
+
222
+ return null;
223
+ } catch (error) {
224
+ console.error('Error loading style config from cloud:', error);
225
+ return null;
226
+ }
227
+ };
228
+
229
+ export const subscribeToStyleConfig = (callback: (config: StyleConfig) => void) => {
230
+ const userId = getUserId();
231
+ const docRef = doc(db, COLLECTION_NAME, userId);
232
+
233
+ // Load initial config immediately
234
+ getDoc(docRef).then((docSnap) => {
235
+ if (docSnap.exists()) {
236
+ const data = docSnap.data();
237
+ const config: StyleConfig = {
238
+ general: {},
239
+ code: {
240
+ textColor: data.code?.textColor || DEFAULT_CODE_STYLE.textColor,
241
+ bgColor: data.code?.bgColor || DEFAULT_CODE_STYLE.bgColor,
242
+ opacity: data.code?.opacity || DEFAULT_CODE_STYLE.opacity,
243
+ width: data.code?.width || DEFAULT_CODE_STYLE.width,
244
+ height: data.code?.height || DEFAULT_CODE_STYLE.height,
245
+ fontSize: data.code?.fontSize || DEFAULT_CODE_STYLE.fontSize,
246
+ borderRadius: data.code?.borderRadius || DEFAULT_CODE_STYLE.borderRadius,
247
+ fontFamily: data.code?.fontFamily || DEFAULT_CODE_STYLE.fontFamily,
248
+ showBackground: data.code?.showBackground !== undefined ? data.code.showBackground : DEFAULT_CODE_STYLE.showBackground,
249
+ lineHeight: data.code?.lineHeight || DEFAULT_CODE_STYLE.lineHeight,
250
+ collapsible: data.code?.collapsible !== undefined ? data.code.collapsible : DEFAULT_CODE_STYLE.collapsible,
251
+ showLineNumbers: data.code?.showLineNumbers !== undefined ? data.code.showLineNumbers : DEFAULT_CODE_STYLE.showLineNumbers,
252
+ wrapText: data.code?.wrapText !== undefined ? data.code.wrapText : DEFAULT_CODE_STYLE.wrapText
253
+ },
254
+ quote: {
255
+ textColor: data.quote?.textColor || DEFAULT_QUOTE_STYLE.textColor,
256
+ bgColor: data.quote?.bgColor || DEFAULT_QUOTE_STYLE.bgColor,
257
+ borderColor: data.quote?.borderColor || DEFAULT_QUOTE_STYLE.borderColor,
258
+ borderWidth: data.quote?.borderWidth || DEFAULT_QUOTE_STYLE.borderWidth,
259
+ fontSize: data.quote?.fontSize || DEFAULT_QUOTE_STYLE.fontSize,
260
+ padding: data.quote?.padding || DEFAULT_QUOTE_STYLE.padding,
261
+ borderRadius: data.quote?.borderRadius || DEFAULT_QUOTE_STYLE.borderRadius,
262
+ italic: data.quote?.italic !== undefined ? data.quote.italic : DEFAULT_QUOTE_STYLE.italic,
263
+ width: data.quote?.width || DEFAULT_QUOTE_STYLE.width,
264
+ height: data.quote?.height || DEFAULT_QUOTE_STYLE.height,
265
+ showCopyButton: data.quote?.showCopyButton !== undefined ? data.quote.showCopyButton : DEFAULT_QUOTE_STYLE.showCopyButton,
266
+ showDownloadButton: data.quote?.showDownloadButton !== undefined ? data.quote.showDownloadButton : DEFAULT_QUOTE_STYLE.showDownloadButton,
267
+ collapsible: data.quote?.collapsible !== undefined ? data.quote.collapsible : DEFAULT_QUOTE_STYLE.collapsible,
268
+ fontFamily: data.quote?.fontFamily || DEFAULT_QUOTE_STYLE.fontFamily,
269
+ isCodeFont: data.quote?.isCodeFont !== undefined ? data.quote.isCodeFont : DEFAULT_QUOTE_STYLE.isCodeFont,
270
+ },
271
+ link: {
272
+ underlineEnabled: data.link?.underlineEnabled !== undefined ? data.link.underlineEnabled : DEFAULT_LINK_STYLE.underlineEnabled
273
+ },
274
+ button: {
275
+ width: data.button?.width || DEFAULT_BUTTON_STYLE.width,
276
+ height: data.button?.height || DEFAULT_BUTTON_STYLE.height,
277
+ backgroundColor: data.button?.backgroundColor || DEFAULT_BUTTON_STYLE.backgroundColor,
278
+ textColor: data.button?.textColor || DEFAULT_BUTTON_STYLE.textColor,
279
+ borderRadius: data.button?.borderRadius || DEFAULT_BUTTON_STYLE.borderRadius
280
+ },
281
+ showCopyButton: data.showCopyButton !== undefined ? data.showCopyButton : DEFAULT_STYLE_CONFIG.showCopyButton
282
+ };
283
+ callback(config);
284
+ } else {
285
+ callback(DEFAULT_STYLE_CONFIG);
286
+ }
287
+ }).catch((error) => {
288
+ console.error('Error loading initial style config:', error);
289
+ callback(DEFAULT_STYLE_CONFIG);
290
+ });
291
+
292
+ // Subscribe to real-time updates
293
+ return onSnapshot(docRef, (docSnap) => {
294
+ if (docSnap.exists()) {
295
+ const data = docSnap.data();
296
+ const config: StyleConfig = {
297
+ general: {},
298
+ code: {
299
+ textColor: data.code?.textColor || DEFAULT_CODE_STYLE.textColor,
300
+ bgColor: data.code?.bgColor || DEFAULT_CODE_STYLE.bgColor,
301
+ opacity: data.code?.opacity || DEFAULT_CODE_STYLE.opacity,
302
+ width: data.code?.width || DEFAULT_CODE_STYLE.width,
303
+ height: data.code?.height || DEFAULT_CODE_STYLE.height,
304
+ fontSize: data.code?.fontSize || DEFAULT_CODE_STYLE.fontSize,
305
+ borderRadius: data.code?.borderRadius || DEFAULT_CODE_STYLE.borderRadius,
306
+ fontFamily: data.code?.fontFamily || DEFAULT_CODE_STYLE.fontFamily,
307
+ showBackground: data.code?.showBackground !== undefined ? data.code.showBackground : DEFAULT_CODE_STYLE.showBackground,
308
+ lineHeight: data.code?.lineHeight || DEFAULT_CODE_STYLE.lineHeight,
309
+ collapsible: data.code?.collapsible !== undefined ? data.code.collapsible : DEFAULT_CODE_STYLE.collapsible,
310
+ showLineNumbers: data.code?.showLineNumbers !== undefined ? data.code.showLineNumbers : DEFAULT_CODE_STYLE.showLineNumbers,
311
+ wrapText: data.code?.wrapText !== undefined ? data.code.wrapText : DEFAULT_CODE_STYLE.wrapText
312
+ },
313
+ quote: {
314
+ textColor: data.quote?.textColor || DEFAULT_QUOTE_STYLE.textColor,
315
+ bgColor: data.quote?.bgColor || DEFAULT_QUOTE_STYLE.bgColor,
316
+ borderColor: data.quote?.borderColor || DEFAULT_QUOTE_STYLE.borderColor,
317
+ borderWidth: data.quote?.borderWidth || DEFAULT_QUOTE_STYLE.borderWidth,
318
+ fontSize: data.quote?.fontSize || DEFAULT_QUOTE_STYLE.fontSize,
319
+ padding: data.quote?.padding || DEFAULT_QUOTE_STYLE.padding,
320
+ borderRadius: data.quote?.borderRadius || DEFAULT_QUOTE_STYLE.borderRadius,
321
+ italic: data.quote?.italic !== undefined ? data.quote.italic : DEFAULT_QUOTE_STYLE.italic,
322
+ width: data.quote?.width || DEFAULT_QUOTE_STYLE.width,
323
+ height: data.quote?.height || DEFAULT_QUOTE_STYLE.height,
324
+ showCopyButton: data.quote?.showCopyButton !== undefined ? data.quote.showCopyButton : DEFAULT_QUOTE_STYLE.showCopyButton,
325
+ showDownloadButton: data.quote?.showDownloadButton !== undefined ? data.quote.showDownloadButton : DEFAULT_QUOTE_STYLE.showDownloadButton,
326
+ collapsible: data.quote?.collapsible !== undefined ? data.quote.collapsible : DEFAULT_QUOTE_STYLE.collapsible,
327
+ fontFamily: data.quote?.fontFamily || DEFAULT_QUOTE_STYLE.fontFamily,
328
+ isCodeFont: data.quote?.isCodeFont !== undefined ? data.quote.isCodeFont : DEFAULT_QUOTE_STYLE.isCodeFont,
329
+ },
330
+ link: {
331
+ underlineEnabled: data.link?.underlineEnabled !== undefined ? data.link.underlineEnabled : DEFAULT_LINK_STYLE.underlineEnabled
332
+ },
333
+ button: {
334
+ width: data.button?.width || DEFAULT_BUTTON_STYLE.width,
335
+ height: data.button?.height || DEFAULT_BUTTON_STYLE.height,
336
+ backgroundColor: data.button?.backgroundColor || DEFAULT_BUTTON_STYLE.backgroundColor,
337
+ textColor: data.button?.textColor || DEFAULT_BUTTON_STYLE.textColor,
338
+ borderRadius: data.button?.borderRadius || DEFAULT_BUTTON_STYLE.borderRadius
339
+ },
340
+
341
+ showCopyButton: data.showCopyButton !== undefined ? data.showCopyButton : DEFAULT_STYLE_CONFIG.showCopyButton
342
+ };
343
+ callback(config);
344
+ } else {
345
+ callback(DEFAULT_STYLE_CONFIG);
346
+ }
347
+ }, (error) => {
348
+ console.error('Error subscribing to style config:', error);
349
+ callback(DEFAULT_STYLE_CONFIG);
350
+ });
351
+ };
services/firebase.ts ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { initializeApp } from 'firebase/app';
2
+ import {
3
+ getFirestore,
4
+ collection,
5
+ addDoc,
6
+ updateDoc,
7
+ deleteDoc,
8
+ doc,
9
+ onSnapshot,
10
+ query,
11
+ orderBy,
12
+ serverTimestamp
13
+ } from 'firebase/firestore';
14
+ import { DataItem } from '../types';
15
+
16
+ // Configuration provided by user
17
+ const firebaseConfig = {
18
+ apiKey: "AIzaSyAH3jvbe0_QLzIuuv5kTMK8246HNvohvfE",
19
+ authDomain: "twistedbrody-9d163.firebaseapp.com",
20
+ projectId: "twistedbrody-9d163",
21
+ storageBucket: "twistedbrody-9d163.firebasestorage.app",
22
+ messagingSenderId: "733213514129",
23
+ appId: "1:733213514129:web:e9694684f5c3994ed06230",
24
+ measurementId: "G-N8TQ7MY42W"
25
+ };
26
+
27
+ const app = initializeApp(firebaseConfig);
28
+ const db = getFirestore(app);
29
+ const COLLECTION_NAME = 'neonvault_items';
30
+
31
+ /**
32
+ * Helper function to remove fields with 'undefined' values from an object.
33
+ * Firestore throws an error if a field is set to undefined.
34
+ */
35
+ const cleanData = (data: any) => {
36
+ const cleaned: any = {};
37
+ Object.keys(data).forEach(key => {
38
+ if (data[key] !== undefined) {
39
+ cleaned[key] = data[key];
40
+ }
41
+ });
42
+ return cleaned;
43
+ };
44
+
45
+ export const subscribeToItems = (callback: (items: DataItem[]) => void) => {
46
+ const q = query(collection(db, COLLECTION_NAME), orderBy('createdAt', 'desc'));
47
+
48
+ return onSnapshot(q, (snapshot) => {
49
+ const items = snapshot.docs.map(doc => {
50
+ const data = doc.data();
51
+
52
+ // Migrate old blocks without type to have 'text' type
53
+ let blocks = data.blocks;
54
+ if (blocks && Array.isArray(blocks)) {
55
+ blocks = blocks.map((block: any) => ({
56
+ ...block,
57
+ type: block.type || 'text' // Default to 'text' if type is missing
58
+ }));
59
+ }
60
+
61
+ return {
62
+ id: doc.id,
63
+ ...data,
64
+ blocks,
65
+ // Convert Firestore Timestamp to number (milliseconds) if necessary
66
+ createdAt: data.createdAt?.toMillis ? data.createdAt.toMillis() : Date.now(),
67
+ updatedAt: data.updatedAt?.toMillis ? data.updatedAt.toMillis() : (data.createdAt?.toMillis ? data.createdAt.toMillis() : Date.now()),
68
+ } as DataItem;
69
+ });
70
+ callback(items);
71
+ }, (error) => {
72
+ console.error("Error reading from Firestore:", error);
73
+ });
74
+ };
75
+
76
+ export const addItem = async (item: Omit<DataItem, 'id' | 'createdAt'>) => {
77
+ try {
78
+ // Sanitize the item to ensure no undefined values are sent
79
+ const itemToSave = cleanData(item);
80
+
81
+ await addDoc(collection(db, COLLECTION_NAME), {
82
+ ...itemToSave,
83
+ createdAt: serverTimestamp() // Use server timestamp for consistency
84
+ });
85
+ } catch (e) {
86
+ console.error("Error adding document: ", e);
87
+ throw e;
88
+ }
89
+ };
90
+
91
+ export const updateItem = async (id: string, item: Partial<DataItem>) => {
92
+ try {
93
+ const docRef = doc(db, COLLECTION_NAME, id);
94
+ // Remove id and createdAt from the update payload to prevent overwriting logic
95
+ const { id: _, createdAt: __, ...updateData } = item;
96
+
97
+ // Sanitize the data
98
+ const sanitizedUpdateData = cleanData(updateData);
99
+
100
+ await updateDoc(docRef, {
101
+ ...sanitizedUpdateData,
102
+ updatedAt: serverTimestamp()
103
+ });
104
+ } catch (e) {
105
+ console.error("Error updating document: ", e);
106
+ throw e;
107
+ }
108
+ };
109
+
110
+ export const deleteItem = async (id: string) => {
111
+ try {
112
+ await deleteDoc(doc(db, COLLECTION_NAME, id));
113
+ } catch (e) {
114
+ console.error("Error deleting document: ", e);
115
+ throw e;
116
+ }
117
+ };
services/geminiService.ts ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { GoogleGenAI } from "@google/genai";
2
+
3
+ const apiKey = process.env.API_KEY || '';
4
+
5
+ let ai: GoogleGenAI | null = null;
6
+
7
+ if (apiKey) {
8
+ ai = new GoogleGenAI({ apiKey: apiKey });
9
+ }
10
+
11
+ export const generateSummary = async (content: string): Promise<string> => {
12
+ if (!ai) {
13
+ console.warn("API Key not found. Skipping AI generation.");
14
+ return "Resumen IA no disponible (Falta API Key).";
15
+ }
16
+
17
+ try {
18
+ const response = await ai.models.generateContent({
19
+ model: 'gemini-2.0-flash-exp',
20
+ contents: `Resume el siguiente contenido en un párrafo conciso y atractivo (máx 30 palabras) adecuado para una vista previa de tarjeta. Responde en ESPAÑOL. Contenido: ${content}`,
21
+ });
22
+
23
+ return response.text || "No se pudo generar el resumen.";
24
+ } catch (error) {
25
+ console.error("Gemini API Error:", error);
26
+ throw new Error("Failed to generate summary.");
27
+ }
28
+ };
29
+
30
+ export const suggestTags = async (content: string): Promise<string[]> => {
31
+ if (!ai) return [];
32
+
33
+ try {
34
+ const response = await ai.models.generateContent({
35
+ model: 'gemini-2.5-flash',
36
+ contents: `Genera de 3 a 5 palabras clave/etiquetas cortas y relevantes para el siguiente texto. Responde SOLO con las etiquetas separadas por comas, sin texto extra. Contenido: ${content}`,
37
+ });
38
+
39
+ const text = response.text || "";
40
+ return text.split(',').map(tag => tag.trim()).filter(tag => tag.length > 0);
41
+ } catch (e) {
42
+ return [];
43
+ }
44
+ }
services/imageService.ts ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ const IMGBB_API_KEY = 'f3657bd2200d5c8cfb8ac201f7daf284';
3
+
4
+ export const uploadImageToImgBB = async (file: File): Promise<string> => {
5
+ const formData = new FormData();
6
+ formData.append('image', file);
7
+
8
+ try {
9
+ const response = await fetch(`https://api.imgbb.com/1/upload?key=${IMGBB_API_KEY}`, {
10
+ method: 'POST',
11
+ body: formData,
12
+ });
13
+
14
+ const data = await response.json();
15
+
16
+ if (data.success) {
17
+ return data.data.url;
18
+ } else {
19
+ throw new Error(data.error?.message || 'Error uploading image');
20
+ }
21
+ } catch (error) {
22
+ console.error('Error uploading to ImgBB:', error);
23
+ throw error;
24
+ }
25
+ };
tsconfig.json ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "experimentalDecorators": true,
5
+ "useDefineForClassFields": false,
6
+ "module": "ESNext",
7
+ "lib": [
8
+ "ES2022",
9
+ "DOM",
10
+ "DOM.Iterable"
11
+ ],
12
+ "skipLibCheck": true,
13
+ "types": [
14
+ "node"
15
+ ],
16
+ "moduleResolution": "bundler",
17
+ "isolatedModules": true,
18
+ "moduleDetection": "force",
19
+ "allowJs": true,
20
+ "jsx": "react-jsx",
21
+ "paths": {
22
+ "@/*": [
23
+ "./*"
24
+ ]
25
+ },
26
+ "allowImportingTsExtensions": true,
27
+ "noEmit": true
28
+ }
29
+ }
types.ts ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export interface ContentBlock {
2
+ id: string;
3
+ type: 'text' | 'markdown';
4
+ content: any;
5
+ }
6
+
7
+ export interface DataItem {
8
+ id: string;
9
+ icon?: string;
10
+ cardStyle?: 'bordered' | 'transparent' | 'filled'; // New field for card styling
11
+ title: string;
12
+ summary: string;
13
+ content: string; // Kept for backward compatibility and search
14
+ blocks?: ContentBlock[]; // New structure for multiple blocks
15
+ downloadUrl?: string;
16
+ visitUrl?: string;
17
+ createdAt: number;
18
+ updatedAt?: number; // Added for modification date sorting
19
+ tags: string[];
20
+ }
21
+
22
+ export type ViewState = 'LIST' | 'DETAIL' | 'CREATE' | 'EDIT';
23
+
24
+ export interface AlertMessage {
25
+ type: 'success' | 'error' | 'info';
26
+ text: string;
27
+ }
utils/codeStyleLoader.ts ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { loadStyleConfigFromCloud, DEFAULT_STYLE_CONFIG, type CodeStyleConfig } from '../services/codeStyleService';
2
+
3
+ export const loadCodeStyle = async (): Promise<void> => {
4
+ let codeStyle: CodeStyleConfig = DEFAULT_STYLE_CONFIG.code;
5
+
6
+ try {
7
+ const cloudConfig = await loadStyleConfigFromCloud();
8
+ if (cloudConfig) {
9
+ codeStyle = cloudConfig.code;
10
+ }
11
+ } catch (error) {
12
+ console.error('Error loading from cloud, using defaults:', error);
13
+ }
14
+
15
+ const rgbaMatch = codeStyle.bgColor.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*[\d.]+)?\)/);
16
+ let bgColorWithOpacity = codeStyle.bgColor;
17
+
18
+ if (rgbaMatch) {
19
+ const [_, r, g, b] = rgbaMatch;
20
+ bgColorWithOpacity = `rgba(${r}, ${g}, ${b}, ${codeStyle.opacity / 100})`;
21
+ }
22
+
23
+ const widthValue = codeStyle.width === 'auto' ? 0 : parseFloat(codeStyle.width) || 0;
24
+ const heightValue = codeStyle.height === 'auto' ? 0 : parseFloat(codeStyle.height) || 0;
25
+
26
+ const existingStyle = document.getElementById('dynamic-code-style');
27
+ if (existingStyle) {
28
+ existingStyle.remove();
29
+ }
30
+
31
+ const style = document.createElement('style');
32
+ style.id = 'dynamic-code-style';
33
+ style.innerHTML = `
34
+ :not(pre) > code {
35
+ background-color: ${bgColorWithOpacity} !important;
36
+ color: ${codeStyle.textColor} !important;
37
+ font-size: ${codeStyle.fontSize} !important;
38
+ border-radius: ${codeStyle.borderRadius} !important;
39
+ padding: 0px 2px !important;
40
+ ${codeStyle.width !== 'auto' && widthValue > 0 ? `min-width: ${codeStyle.width} !important;` : ''}
41
+ ${codeStyle.height !== 'auto' && heightValue > 0 ? `min-height: ${codeStyle.height} !important;` : ''}
42
+
43
+ display: inline-flex !important;
44
+ align-items: center !important;
45
+ justify-content: center !important;
46
+
47
+ vertical-align: middle !important;
48
+ border: none !important;
49
+ font-family: 'Consolas', monospace !important;
50
+ line-height: 1 !important;
51
+ margin: 0 1px !important;
52
+ }
53
+
54
+ button code, a code, .btn code {
55
+ background: transparent !important;
56
+ padding: 0 !important;
57
+ color: inherit !important;
58
+ border: none !important;
59
+ }
60
+
61
+ code::before, code::after {
62
+ content: "" !important;
63
+ display: none !important;
64
+ }
65
+ `;
66
+
67
+ document.head.appendChild(style);
68
+ };