-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathreference.txt
More file actions
1567 lines (1394 loc) · 49.9 KB
/
Copy pathreference.txt
File metadata and controls
1567 lines (1394 loc) · 49.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
Este es el componente de otra rama PostEditor:
Hace que funcione la logica de publicar post desde modo avanzado,
pero en diseño no hay nada que quiera cambiar respecto a mi desño actual,
Así que solo analiza la logica manteniendo el diseño actual de el componente PostEditor editor,
no de este que te presento, pero implementa la logica de este:
---------------------------------------------------------------------------
PostEditor
// src/components/admin/PostEditor.jsx
import React, { useState, useEffect } from 'react';
import { spacing, typography, shadows, borderRadius } from '../../styles/theme';
import { useTheme } from '../../context/ThemeContext'; // Añadir esta importación
import { createPublicacion, createPublicacionFromHTML } from '../../services/publicacionesService';
import { getAllCategorias } from '../../services/categoriasServices';
// Componentes para el editor
import DualModeEditor from './DualModeEditor';
import PostMetadata from './PostMetadata';
import CoverImageUploader from './CoverImageUploader';
import StatusMessage from './StatusMessage';
import ImportExportActions from './ImportExportActions';
// Funciones para almacenamiento local
const savePostToLocalStorage = (post) => {
try {
const postToSave = { ...post };
// No guardamos la imagen como tal, sino solo la URL de vista previa
delete postToSave.coverImage;
localStorage.setItem('post_draft', JSON.stringify(postToSave));
console.log('Saved to localStorage:', postToSave); // Debug
} catch (error) {
console.error('Error saving to localStorage:', error);
}
};
const loadPostFromLocalStorage = () => {
try {
const savedPost = localStorage.getItem('post_draft');
return savedPost ? JSON.parse(savedPost) : null;
} catch (error) {
console.error('Error loading from localStorage:', error);
return null;
}
};
// Componente para la etiqueta de Contenido animada
const ContentLabel = () => {
const [isAnimated, setIsAnimated] = useState(false);
const { colors, isDarkMode } = useTheme(); // Obtener colores del tema
useEffect(() => {
// Activar animación después de un breve retraso
const timer = setTimeout(() => {
setIsAnimated(true);
}, 300);
return () => clearTimeout(timer);
}, []);
const styles = {
container: {
display: 'flex',
alignItems: 'center',
marginBottom: spacing.md,
transform: isAnimated ? 'translateX(0)' : 'translateX(-20px)',
opacity: isAnimated ? 1 : 0,
transition: 'all 0.6s ease-out'
},
icon: {
fontSize: '22px',
marginRight: spacing.sm,
color: colors?.secondary || '#d2b99a',
animation: isAnimated ? 'pulseIcon 2s infinite' : 'none'
},
label: {
fontSize: typography.fontSize.lg,
fontWeight: typography.fontWeight.semiBold,
color: isDarkMode ? (colors?.textLight || '#e0e0e0') : (colors?.primary || '#0b4444'), // Ajustar color según el tema
position: 'relative',
paddingBottom: '3px'
},
underline: {
position: 'absolute',
bottom: 0,
left: 0,
width: isAnimated ? '100%' : '0%',
height: '2px',
backgroundColor: colors?.secondary || '#d2b99a',
transition: 'width 0.8s ease-in-out',
transitionDelay: '0.3s'
},
badge: {
display: 'inline-block',
backgroundColor: isAnimated ? (colors?.primary || '#0b4444') : 'transparent',
color: 'white',
padding: `${spacing.xs} ${spacing.sm}`,
borderRadius: borderRadius.round,
fontSize: typography.fontSize.xs,
marginLeft: spacing.md,
transform: isAnimated ? 'scale(1)' : 'scale(0)',
transition: 'all 0.5s ease-out',
transitionDelay: '0.6s',
boxShadow: isAnimated ? '0 2px 4px rgba(11, 68, 68, 0.2)' : 'none'
}
};
return (
<div style={styles.container}>
<span style={styles.icon}>📝</span>
<h3 style={styles.label}>
Contenido
<span style={styles.underline}></span>
</h3>
<span style={styles.badge}>Editor</span>
</div>
);
};
const PostEditor = () => {
// Estado para el tema
const { colors, isDarkMode } = useTheme(); // Extraer colors y isDarkMode
// Estado del post
const [post, setPost] = useState({
title: '',
content: '',
category: '',
coverImage: null,
status: 'draft',
editorMode: 'simple', // Es importante inicializar este valor
previewUrl: null,
lastSaved: null
});
// Otros estados
const [categories, setCategories] = useState([]);
const [isSaving, setIsSaving] = useState(false);
const [isPublishing, setIsPublishing] = useState(false);
const [saveMessage, setSaveMessage] = useState(null);
const [isDragging, setIsDragging] = useState(false);
// Cargar categorías
useEffect(() => {
loadCategories();
// Cargar borrador del almacenamiento local
const savedPost = loadPostFromLocalStorage();
if (savedPost) {
setPost(prev => ({
...prev,
...savedPost,
lastSaved: savedPost.lastSaved || null,
// Asegurarnos que editorMode existe y tiene un valor válido
editorMode: savedPost.editorMode || 'simple'
}));
}
// Auto-guardado cada 30 segundos
const interval = setInterval(() => {
saveDraft();
}, 30000);
return () => clearInterval(interval);
}, []);
// Función para cargar categorías
const loadCategories = async () => {
try {
const data = await getAllCategorias();
console.log("Categorías cargadas:", data);
if (data && Array.isArray(data)) {
setCategories(data);
} else {
// Si no hay datos o no es un array, usar categorías predeterminadas
setCategories([
{ ID_categoria: 1, Nombre_categoria: 'Noticias' },
{ ID_categoria: 2, Nombre_categoria: 'Técnicas de Estudio' },
{ ID_categoria: 3, Nombre_categoria: 'Problemáticas en el Estudio' },
{ ID_categoria: 4, Nombre_categoria: 'Educación de Calidad' },
{ ID_categoria: 5, Nombre_categoria: 'Herramientas Tecnológicas' },
{ ID_categoria: 6, Nombre_categoria: 'Desarrollo Profesional Docente' },
{ ID_categoria: 7, Nombre_categoria: 'Comunidad y Colaboración' }
]);
}
} catch (error) {
console.error('Error al cargar categorías:', error);
// Usar categorías predeterminadas en caso de error
setCategories([
{ ID_categoria: 1, Nombre_categoria: 'Noticias' },
{ ID_categoria: 2, Nombre_categoria: 'Técnicas de Estudio' },
{ ID_categoria: 3, Nombre_categoria: 'Problemáticas en el Estudio' },
{ ID_categoria: 4, Nombre_categoria: 'Educación de Calidad' },
{ ID_categoria: 5, Nombre_categoria: 'Herramientas Tecnológicas' },
{ ID_categoria: 6, Nombre_categoria: 'Desarrollo Profesional Docente' },
{ ID_categoria: 7, Nombre_categoria: 'Comunidad y Colaboración' }
]);
}
};
// Manejador para cambios en los campos del formulario
const handleInputChange = (e) => {
const { name, value } = e.target;
console.log(`Campo ${name} cambió a: ${value}`);
if (name === 'editorMode') {
console.log(`Modo de editor cambiado a: ${value}`);
}
setPost(prev => ({
...prev,
[name]: value
}));
};
// Manejador para cambios en la imagen de portada
const handleImageChange = (e) => {
const file = e.target.files[0];
if (file) {
setPost(prev => ({
...prev,
coverImage: file,
previewUrl: URL.createObjectURL(file)
}));
}
};
// Autoguardado cuando el contenido cambia
useEffect(() => {
if (!post.content.length > 0 || !post.title.length > 0) {
// console.log('Guardado automático'); // Eliminar o comentar esta línea
savePostToLocalStorage(post);
}
}, [post]);
// Guardar como borrador
const saveDraft = async () => {
// Validación básica
if (!post.title.trim()) {
setSaveMessage({
type: 'error',
text: 'Por favor añade un título a tu publicación',
icon: '✖'
});
setTimeout(() => setSaveMessage(null), 3000);
return;
}
setIsSaving(true);
try {
// Convertir la categoría seleccionada a un ID numérico si existe
let categorias = [];
if (post.category) {
// Buscar el ID de la categoría seleccionada
const categoriaSeleccionada = categories.find(cat =>
typeof cat === 'object' ? cat.Nombre_categoria === post.category : cat === post.category
);
if (typeof categoriaSeleccionada === 'object' && categoriaSeleccionada.ID_categoria) {
categorias = [categoriaSeleccionada.ID_categoria];
} else if (post.category) {
// Si no encontramos el ID pero hay una categoría seleccionada, usamos 1 como valor predeterminado
console.warn("No se pudo encontrar el ID de la categoría, usando valor predeterminado");
categorias = [1];
}
}
// Preparar los datos para el backend
const postData = {
titulo: post.title,
contenido: post.content,
resumen: post.title.substring(0, 150), // Usar parte del título como resumen
estado: 'borrador',
categorias: categorias
};
console.log("Guardando borrador con datos:", postData);
// Guardar en el backend
const result = await createPublicacion(postData);
// Guardar en localStorage como respaldo
savePostToLocalStorage(post);
setIsSaving(false);
setSaveMessage({
type: 'success',
text: 'Borrador guardado correctamente',
icon: '✓'
});
// Limpiar mensaje después de unos segundos
setTimeout(() => setSaveMessage(null), 3000);
} catch (error) {
console.error('Error al guardar borrador:', error);
setIsSaving(false);
setSaveMessage({
type: 'error',
text: `Error al guardar: ${error.message}`,
icon: '✖'
});
setTimeout(() => setSaveMessage(null), 3000);
}
};
// Publicar el post
const publishPost = async () => {
// Validación básica
if (!post.title.trim() || !post.content.trim() || !post.category) {
setSaveMessage({
type: 'error',
text: 'Por favor completa al menos el título, categoría y contenido del post',
icon: '✖'
});
setTimeout(() => setSaveMessage(null), 3000);
return;
}
setIsPublishing(true);
try {
// Convertir la categoría seleccionada a un ID numérico
// Buscar el ID de la categoría seleccionada
const categoriaSeleccionada = categories.find(cat =>
typeof cat === 'object' ? cat.Nombre_categoria === post.category : cat === post.category
);
let categoriaId;
if (typeof categoriaSeleccionada === 'object' && categoriaSeleccionada.ID_categoria) {
categoriaId = categoriaSeleccionada.ID_categoria;
} else {
// Si no encontramos el ID, usamos 1 como valor predeterminado (asumiendo que existe)
console.warn("No se pudo encontrar el ID de la categoría, usando valor predeterminado");
categoriaId = 1;
}
// Preparar los datos para el backend
const postData = {
titulo: post.title,
contenido: post.content,
resumen: post.title.substring(0, 150), // Usar parte del título como resumen
estado: 'publicado',
categorias: [categoriaId] // Usar el ID numérico de la categoría
};
console.log("Enviando publicación con datos:", postData);
// Determinar qué endpoint usar según el modo del editor
let result;
if (post.editorMode === 'html') {
console.log("Usando endpoint HTML con contenido HTML de longitud:", post.content.length);
console.log("Muestra del contenido HTML:", post.content.substring(0, 150) + "...");
// Verificar que el contenido no sea vacío o solo espacios
if (!post.content.trim()) {
throw new Error("El contenido HTML está vacío o solo contiene espacios");
}
// Verificar que el contenido tenga etiquetas HTML válidas
if (!post.content.includes("<") || !post.content.includes(">")) {
console.warn("El contenido no parece contener etiquetas HTML válidas");
}
result = await createPublicacionFromHTML({
titulo: postData.titulo,
htmlContent: post.content, // Aquí está el cambio clave: enviamos el contenido como htmlContent
resumen: postData.resumen,
estado: postData.estado,
categorias: postData.categorias
});
} else {
result = await createPublicacion(postData);
}
setIsPublishing(false);
setPost(prev => ({ ...prev, status: 'published' }));
setSaveMessage({
type: 'success',
text: '¡Post publicado correctamente!',
icon: '🎉'
});
// Limpiar mensaje después de unos segundos
setTimeout(() => setSaveMessage(null), 3000);
// Limpieza del borrador en localStorage después de publicar
localStorage.removeItem('post_draft');
} catch (error) {
console.error('Error al publicar:', error);
setIsPublishing(false);
setSaveMessage({
type: 'error',
text: `Error al publicar: ${error.message}`,
icon: '✖'
});
setTimeout(() => setSaveMessage(null), 3000);
}
};
// Exportar el post a HTML para descargar
const exportToFile = () => {
// Crear un objeto de texto para descargar
const content = post.content;
const blob = new Blob([content], { type: 'text/html' });
const url = URL.createObjectURL(blob);
// Crear un enlace de descarga y hacer clic en él
const a = document.createElement('a');
a.href = url;
a.download = `${post.title.replace(/[^a-z0-9]/gi, '-').toLowerCase()}.html`;
document.body.appendChild(a);
a.click();
// Limpiar
document.body.removeChild(a);
URL.revokeObjectURL(url);
// Mostrar mensaje de éxito
setSaveMessage({
type: 'success',
text: `Archivo HTML descargado correctamente`,
icon: '📥'
});
setTimeout(() => setSaveMessage(null), 3000);
};
// Importar un archivo HTML
const importFile = (e) => {
const file = e.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = (event) => {
const content = event.target.result;
const fileExtension = file.name.split('.').pop().toLowerCase();
// Verificar que sea HTML
const isHTML = fileExtension === 'html' || fileExtension === 'htm';
if (isHTML) {
// Extraer el título del documento HTML si existe
const titleMatch = content.match(/<title>(.*?)<\/title>/i);
const title = titleMatch ? titleMatch[1] : '';
// Actualizar el estado con el contenido HTML
setPost(prevPost => ({
...prevPost,
title: title || prevPost.title,
content: content,
editorMode: 'html'
}));
} else {
// Informar que solo se permiten archivos HTML
setSaveMessage({
type: 'error',
text: 'Solo se permiten archivos HTML (.html, .htm)',
icon: '⚠️'
});
setTimeout(() => setSaveMessage(null), 3000);
return;
}
// Mostrar mensaje de éxito
setSaveMessage({
type: 'success',
text: `Archivo HTML importado correctamente`,
icon: '📤'
});
setTimeout(() => setSaveMessage(null), 3000);
};
reader.readAsText(file);
};
// Estilos CSS
const styles = {
container: {
maxWidth: "1200px",
margin: "0 auto",
padding: `${"100px"} ${spacing.md}`,
fontFamily: typography.fontFamily
},
editorContainer: {
display: "grid",
// Cambiado: Invertir el orden de las columnas para que la barra lateral esté a la izquierda
gridTemplateColumns: "300px 1fr",
gap: spacing.xl,
marginBottom: spacing.xxl,
'@media (max-width: 768px)': {
gridTemplateColumns: "1fr"
}
},
mainEditor: {
width: "100%",
maxWidth: "800px" // Anchura predefinida para el contenido del post
},
sidebar: {
// No necesita cambios específicos de estilo aquí
},
formGroup: {
marginBottom: spacing.lg
},
actionsContainer: {
display: "flex",
justifyContent: "space-between",
gap: spacing.md,
marginTop: spacing.xl
},
actionButton: {
padding: `${spacing.sm} ${spacing.lg}`,
borderRadius: borderRadius.md,
fontWeight: typography.fontWeight.medium,
cursor: "pointer",
transition: "all 0.3s ease",
fontSize: typography.fontSize.md,
border: "none",
// Estilos específicos se aplicarán en cada botón
},
saveButton: {
backgroundColor: colors?.secondary || '#d2b99a',
color: colors?.primary || '#0b4444',
"&:hover": {
backgroundColor: (colors?.secondary || '#d2b99a') + "cc", // Añadir transparencia al hover
}
},
publishButton: {
backgroundColor: colors?.primary || '#0b4444',
color: colors?.white || '#ffffff',
"&:hover": {
backgroundColor: colors?.primaryLight || '#166363',
}
}
};
// Modificar el componente PostMetadata para usar las categorías cargadas
const renderPostMetadata = () => {
return (
<div style={{
marginTop: spacing.lg,
backgroundColor: isDarkMode ? (colors?.backgroundDarkSecondary || '#1a3838') : (colors?.white || '#ffffff'),
padding: spacing.md,
borderRadius: borderRadius.md,
boxShadow: shadows.sm
}}>
<h3 style={{
fontSize: typography.fontSize.lg,
fontWeight: typography.fontWeight.semiBold,
marginBottom: spacing.md,
color: isDarkMode ? (colors?.textLight || '#e0e0e0') : (colors?.primary || '#0b4444')
}}>Detalles de la publicación</h3>
<div style={{ marginBottom: spacing.md }}>
<label style={{
display: 'block',
marginBottom: spacing.xs,
fontWeight: typography.fontWeight.medium,
color: isDarkMode ? (colors?.textLight || '#e0e0e0') : (colors?.textPrimary || '#333333')
}} htmlFor="category">
Categoría
</label>
<select
id="category"
name="category"
value={post.category}
onChange={handleInputChange}
style={{
width: "100%",
padding: spacing.sm,
borderRadius: borderRadius.sm,
border: `1px solid ${colors?.gray200 || '#e9e9e9'}`,
backgroundColor: isDarkMode ? (colors?.backgroundDark || '#0f2e2e') : (colors?.white || '#ffffff'),
color: isDarkMode ? (colors?.textLight || '#e0e0e0') : (colors?.textPrimary || '#333333')
}}
>
<option value="">Seleccionar categoría</option>
{categories.map((cat) => (
<option
key={cat.ID_categoria}
value={cat.Nombre_categoria}
>
{cat.Nombre_categoria}
</option>
))}
</select>
</div>
<div style={{ marginBottom: spacing.md }}>
<label style={{
display: 'block',
marginBottom: spacing.xs,
fontWeight: typography.fontWeight.medium,
color: isDarkMode ? (colors?.textLight || '#e0e0e0') : (colors?.textPrimary || '#333333')
}} htmlFor="tags">
Etiquetas (separadas por comas)
</label>
<input
type="text"
id="tags"
name="tags"
value={post.tags}
onChange={handleInputChange}
style={{
width: "100%",
padding: spacing.sm,
borderRadius: borderRadius.sm,
border: `1px solid ${colors?.gray200 || '#e9e9e9'}`,
backgroundColor: isDarkMode ? (colors?.backgroundDark || '#0f2e2e') : (colors?.white || '#ffffff'),
color: isDarkMode ? (colors?.textLight || '#e0e0e0') : (colors?.textPrimary || '#333333')
}}
placeholder="ej. educación, tecnología, aprendizaje"
/>
</div>
<div style={{ marginBottom: spacing.md }}>
<label style={{
display: 'block',
marginBottom: spacing.xs,
fontWeight: typography.fontWeight.medium,
color: isDarkMode ? (colors?.textLight || '#e0e0e0') : (colors?.textPrimary || '#333333')
}} htmlFor="publishDate">
Fecha de publicación
</label>
<input
type="date"
id="publishDate"
name="publishDate"
value={post.publishDate}
onChange={handleInputChange}
style={{
width: "100%",
padding: spacing.sm,
borderRadius: borderRadius.sm,
border: `1px solid ${colors?.gray200 || '#e9e9e9'}`,
backgroundColor: isDarkMode ? (colors?.backgroundDark || '#0f2e2e') : (colors?.white || '#ffffff'),
color: isDarkMode ? (colors?.textLight || '#e0e0e0') : (colors?.textPrimary || '#333333')
}}
/>
</div>
<div style={{ marginBottom: spacing.md }}>
<label style={{
display: 'block',
marginBottom: spacing.xs,
fontWeight: typography.fontWeight.medium,
color: isDarkMode ? (colors?.textLight || '#e0e0e0') : (colors?.textPrimary || '#333333')
}}>
Estado actual
</label>
<div style={{
display: 'inline-block',
padding: `${spacing.xs} ${spacing.sm}`,
backgroundColor: post.status === 'draft' ? (colors?.warning || '#f6c23e') : (colors?.success || '#1cc88a'),
color: colors?.white || '#ffffff',
borderRadius: borderRadius.sm,
fontSize: typography.fontSize.sm,
fontWeight: typography.fontWeight.medium
}}>
{post.status === 'draft' ? 'Borrador' : 'Publicado'}
</div>
</div>
</div>
);
};
// Solo renderizar una vez inicializado para evitar problemas de redimensión
if (!categories.length) {
return <div style={styles.container}>Cargando categorías...</div>;
}
return (
<div style={styles.container}>
{/* Estilos CSS en línea para animaciones */}
<style dangerouslySetInnerHTML={{
__html: `
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
@keyframes slideInUp {
from { transform: translateY(20px); opacity: 0; }
to { transform: translateY(0); opacity: 1; }
}
@keyframes pulseIcon {
0% { transform: scale(1); }
50% { transform: scale(1.1); }
100% { transform: scale(1); }
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
@keyframes shine {
0% { background-position: -200% 0; }
100% { background-position: 200% 0; }
}
@keyframes shake {
0%, 100% { transform: translateX(0); }
10%, 30%, 50%, 70%, 90% { transform: translateX(-5px); }
20%, 40%, 60%, 80% { transform: translateX(5px); }
}
`
}} />
<div style={styles.editorContainer}>
{/* Sidebar - Ahora a la izquierda */}
<div style={styles.sidebar}>
<CoverImageUploader
coverImagePreview={post.previewUrl}
onChange={handleImageChange}
/>
{renderPostMetadata()}
<ImportExportActions
onExport={exportToFile}
onImport={importFile}
/>
</div>
{/* Main Editor - Ahora a la derecha */}
<div style={styles.mainEditor}>
<div style={styles.formGroup}>
<label style={{
display: 'flex',
alignItems: 'center',
gap: spacing.xs,
marginBottom: spacing.xs,
fontWeight: typography.fontWeight.medium,
color: isDarkMode ? colors.textLight : colors.primary
}} htmlFor="title">
<span style={{color: isDarkMode ? colors.textLight : colors.primary, fontSize: '1.4em'}}>📝</span> Título del post
</label>
<input
type="text"
id="title"
name="title"
value={post.title}
onChange={handleInputChange}
style={{
width: "100%",
padding: spacing.md,
borderRadius: borderRadius.md,
border: `1px solid ${colors?.gray200 || '#e9e9e9'}`,
fontSize: typography.fontSize.lg,
transition: "all 0.3s ease",
marginBottom: spacing.md,
fontWeight: typography.fontWeight.semiBold,
borderLeft: `4px solid ${colors?.primary || '#0b4444'}`,
backgroundColor: colors?.white || '#ffffff',
color: isDarkMode ? (colors?.textPrimary || '#333333') : "#000000",
}}
placeholder="Escribe un título atractivo"
onFocus={(e) => {
e.target.style.boxShadow = `0 0 0 2px ${colors?.primary || '#0b4444'}30`;
e.target.style.borderLeft = `4px solid ${colors?.secondary || '#d2b99a'}`;
}}
onBlur={(e) => {
e.target.style.boxShadow = 'none';
e.target.style.borderLeft = `4px solid ${colors?.primary || '#0b4444'}`;
}}
/>
</div>
<div style={styles.formGroup}>
{/* Etiqueta "Contenido" animada */}
<ContentLabel />
<DualModeEditor
content={post.content}
onChange={handleInputChange}
initialMode={post.editorMode}
/>
</div>
{saveMessage && (
<StatusMessage
type={saveMessage.type}
text={saveMessage.text}
icon={saveMessage.icon}
/>
)}
<div style={styles.actionsContainer}>
<button
onClick={saveDraft}
disabled={isSaving}
style={{
...styles.actionButton,
...styles.saveButton
}}
>
{isSaving ? 'Guardando...' : 'Guardar borrador'}
</button>
<button
onClick={publishPost}
disabled={isPublishing}
style={{
...styles.actionButton,
...styles.publishButton
}}
>
{isPublishing ? 'Publicando...' : 'Publicar post'}
</button>
</div>
</div>
</div>
</div>
);
};
export default PostEditor;
----------------------------------------------------
Este es el componente de otra rama DualModeEditor:
Hace que funcione la logica de publicar post desde modo avanzado,
pero en diseño no hay nada que quiera cambiar respecto a mi desño actual,
Así que solo analiza la logica manteniendo el diseño actual de el componente DualModeEditor editor,
no de este que te presento, pero implementa la logica de este:
-------------------------------------------------------------------------------------------
DualModeEditor
import React, { useRef, useState, useEffect } from 'react';
import { colors, spacing, typography, shadows, borderRadius, transitions } from '../../styles/theme';
import EditorToolbar from './EditorToolbar';
import { insertHTML } from './utils/editorUtils';
import HTMLPreview from './HTMLPreview';
import SyntaxHighlighter from './SyntaxHighlighter';
import SimpleEditor from './SimpleEditor';
import ImportExportActions from './ImportExportActions';
const DualModeEditor = ({ content, onChange, initialMode = 'simple', onExport, onImport }) => {
const textAreaRef = useRef(null);
const [mode, setMode] = useState('simple'); // Siempre comenzar con modo simple
const [activeTab, setActiveTab] = useState('code'); // Para el modo desarrollador
const [internalContent, setInternalContent] = useState(content || '');
const [isHighlightingEnabled, setIsHighlightingEnabled] = useState(true);
const [simpleContent, setSimpleContent] = useState(content || '');
const [showDeveloperModal, setShowDeveloperModal] = useState(false);
const [hoveredElement, setHoveredElement] = useState(null);
// Actualizar contenido cuando cambia externamente
useEffect(() => {
setInternalContent(content || '');
setSimpleContent(content || '');
}, [content]);
// Manejar acciones de la barra de herramientas para el modo desarrollador
const handleToolbarAction = (actionType, placeholder) => {
if (mode === 'simple') {
return;
}
const newContent = insertHTML(
internalContent,
actionType,
placeholder,
textAreaRef.current
);
updateContent(newContent);
};
// Actualizar contenido según el modo actual
const updateContent = (newContent) => {
setInternalContent(newContent);
// Notificar al componente padre sobre el cambio
const event = {
target: {
name: 'content',
value: newContent
}
};
console.log('DualModeEditor - updateContent: Actualizando contenido del editor', newContent.substring(0, 50) + '...');
onChange(event);
};
// Manejar cambio de modo entre simple y desarrollador
const handleModeToggle = (newMode) => {
console.log('DualModeEditor - handleModeToggle: Cambiando modo de', mode, 'a', newMode);
if (newMode === 'developer' && mode === 'simple') {
setShowDeveloperModal(true);
return;
}
setMode(newMode);
// Resetear pestañas a vista de código al cambiar a modo desarrollador
if (newMode === 'developer') {
setActiveTab('code');
}
// Notificar al componente padre sobre el cambio de modo
const event = {
target: {
name: 'editorMode',
value: newMode === 'developer' ? 'html' : 'simple'
}
};
console.log('DualModeEditor - handleModeToggle: Notificando cambio de modo al padre:', event.target.value);
onChange(event);
};
// Confirmar cambio al modo desarrollador
const confirmDeveloperMode = () => {
console.log('DualModeEditor - confirmDeveloperMode: Confirmando cambio a modo HTML');
setShowDeveloperModal(false);
setMode('developer');
// Notificar al componente padre sobre el cambio de modo
const event = {
target: {
name: 'editorMode',
value: 'html'
}
};
console.log('DualModeEditor - confirmDeveloperMode: Notificando cambio de modo al padre:', event.target.value);
onChange(event);
};
// Cancelar cambio al modo desarrollador
const cancelDeveloperMode = () => {
setShowDeveloperModal(false);
};
// Manejar cambios en el área de texto
const handleTextAreaChange = (e) => {
console.log('DualModeEditor - handleTextAreaChange llamado con valor:',
e.target.value ? `"${e.target.value.substring(0, 50)}..."` : 'vacío');
// Asegurar que no estamos estableciendo a null o undefined
const newContent = e.target.value || '';
setInternalContent(newContent);
// Crear un evento limpio con el contenido adecuado
const cleanEvent = {
target: {
name: 'content',
value: newContent
}
};
console.log('DualModeEditor - notificando al padre con contenido de longitud:', newContent.length);
onChange(cleanEvent);
};
// Manejar cambios en el contenido del editor simple