Foro: reemplazar el foro anterior por el port del foro estilo FusionCMS

Se sustituye por completo el foro anterior de Next (que estaba vacío: 0 temas, 0
posts) por una adaptación del foro PHP de FusionCMS que tenía el usuario, con su
estructura, sus imágenes y su estética, llevadas a Next.

BASE DE DATOS (acore_web), esquema idéntico al original (sql/forum_fusion.sql):
  forum_categories(id, order, name)
  forum_forums(id, category, order, name, description, icon, colortitle, type)
  forum_topics(id, forum, name, sticky, locked, deleted, created)
  forum_posts(id, topic, poster, text, time, deleted)
Se hizo DROP de las tablas antiguas (forums, forum_categories, forum_topics,
forum_posts) y CREATE de estas, con el seed original (News/Reports/General,
foros con icono, clases con color, subforos por idioma con bandera). Única
diferencia con el dump: forum_topics.created, que faltaba y usan las vistas, y
el recorte del salto de línea final en los nombres de clase.

Los temas no guardan autor ni última actividad: se derivan del primer/último post,
como en el original. `poster` es el AccountID de acore_auth; el nombre se resuelve
al render (username sin el sufijo #N de Battle.net). El texto se guarda como HTML
saneado con nh3 (no BBCode) para encajar con el editor.

EDITOR: TinyMCE community self-hosted (licenseKey gpl), servido desde /tinymce
(scripts/copy-tinymce.mjs en postinstall; public/tinymce en .gitignore por ser
artefacto). El HTML se sanea SIEMPRE en el servidor.

PÁGINAS (app/[locale]/forum): índice con los 3 tipos de foro (fila normal, tarjeta
de clase tipo 1, tarjeta de idioma tipo 2), subforo, tema, crear y editar. La
lógica de forum.js (crear/responder/editar/moderar) se portó a fetch + los avisos
del sitio, sin jQuery/SweetAlert, y la moderación pasa por POST (no GET).

CSS: forum.css adaptado al tema (app/forum.css), rutas de imagen a /forum, dorado
alineado al acento del sitio (#d79602), y se aportan .nice_button/.main-wide/
.pagination que no estaban en theme.css.

ADMIN: lib/admin-forum.ts, sus rutas y AdminForumManager reescritos al esquema
nuevo (categoría, icono, color, tipo, orden; sin _en/visibility).

Se eliminan /forum/search y /forum/user (no existen en el foro nuevo) y los
componentes que quedaban huérfanos (ForumSearchBox, PostActions, TopicModBar,
NewTopicForm). i18n ES/EN completado (next-intl).

Verificado en producción: el índice renderiza en es/en con categorías, clases,
banderas e iconos; los assets y TinyMCE sirven 200; crear tema y responder guardan
las filas con el esquema correcto y las páginas las muestran (autor resuelto, HTML
saneado). Datos de prueba borrados: el foro arranca vacío.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-07-16 12:22:08 +00:00
parent 0f98b754d4
commit af707ad98c
190 changed files with 3142 additions and 1104 deletions
+77 -56
View File
@@ -6,22 +6,29 @@ import { useRouter } from '@/i18n/navigation'
import type { AdminCategory, AdminForum } from '@/lib/admin-forum'
type Group = { category: AdminCategory; forums: AdminForum[] }
type ForumFields = {
name: string
description: string
icon: string
colortitle: string
type: string
order: string
}
const EMPTY_FORUM: ForumFields = { name: '', description: '', icon: '', colortitle: '', type: '0', order: '0' }
export function AdminForumManager({ initial }: { initial: Group[] }) {
const t = useTranslations('Admin')
const router = useRouter()
const [busy, setBusy] = useState(false)
const [catForm, setCatForm] = useState({ name: '', nameEn: '', order: '0' })
const [forumForm, setForumForm] = useState<Record<number, { name: string; nameEn: string; description: string; descriptionEn: string; order: string }>>({})
const [editCat, setEditCat] = useState<{ id: number; name: string; nameEn: string; order: string } | null>(null)
const [editForum, setEditForum] = useState<{ id: number; name: string; nameEn: string; description: string; descriptionEn: string; order: string; visibility: number } | null>(null)
const [catForm, setCatForm] = useState({ name: '', order: '0' })
const [forumForm, setForumForm] = useState<Record<number, ForumFields>>({})
const [editCat, setEditCat] = useState<{ id: number; name: string; order: string } | null>(null)
const [editForum, setEditForum] = useState<(ForumFields & { id: number }) | null>(null)
function ff(catId: number) {
return forumForm[catId] ?? { name: '', nameEn: '', description: '', descriptionEn: '', order: '0' }
}
function setFF(catId: number, patch: Partial<{ name: string; nameEn: string; description: string; descriptionEn: string; order: string }>) {
const ff = (catId: number) => forumForm[catId] ?? EMPTY_FORUM
const setFF = (catId: number, patch: Partial<ForumFields>) =>
setForumForm((s) => ({ ...s, [catId]: { ...ff(catId), ...patch } }))
}
async function call(url: string, method: string, body?: unknown): Promise<boolean> {
setBusy(true)
@@ -38,12 +45,46 @@ export function AdminForumManager({ initial }: { initial: Group[] }) {
return true
}
if (d.error === 'categoryNotEmpty') alert(t('categoryNotEmpty'))
else if (d.error === 'forumNotEmpty') alert(t('forumNotEmpty'))
return false
} finally {
setBusy(false)
}
}
const forumBody = (v: ForumFields, category: number) => ({
category,
name: v.name,
description: v.description,
icon: v.icon,
colortitle: v.colortitle,
type: Number(v.type),
order: Number(v.order),
})
function ForumEditFields({
v,
onChange,
}: {
v: ForumFields
onChange: (patch: Partial<ForumFields>) => void
}) {
return (
<>
<input value={v.name} onChange={(e) => onChange({ name: e.target.value })} placeholder={t('forumName')} maxLength={45} />
<input value={v.description} onChange={(e) => onChange({ description: e.target.value })} placeholder={t('forumDescription')} />
<select value={v.type} onChange={(e) => onChange({ type: e.target.value })}>
<option value="0">{t('forumTypeNormal')}</option>
<option value="1">{t('forumTypeClass')}</option>
<option value="2">{t('forumTypeFlag')}</option>
</select>
<input value={v.icon} onChange={(e) => onChange({ icon: e.target.value })} placeholder={t('forumIcon')} />
<input value={v.colortitle} onChange={(e) => onChange({ colortitle: e.target.value })} placeholder={t('forumColor')} />
<input type="number" value={v.order} onChange={(e) => onChange({ order: e.target.value })} placeholder={t('order')} />
</>
)
}
return (
<div>
{/* Alta de categoría */}
@@ -51,18 +92,16 @@ export function AdminForumManager({ initial }: { initial: Group[] }) {
onSubmit={(e) => {
e.preventDefault()
if (catForm.name.trim())
call('/api/admin/forum/category', 'POST', { name: catForm.name, nameEn: catForm.nameEn, order: Number(catForm.order) }).then(
(ok) => ok && setCatForm({ name: '', nameEn: '', order: '0' }),
call('/api/admin/forum/category', 'POST', { name: catForm.name, order: Number(catForm.order) }).then(
(ok) => ok && setCatForm({ name: '', order: '0' }),
)
}}
className="admin-form info-box-light separate2"
>
<span className="second-brown">{t('newCategory')}</span>
<input value={catForm.name} onChange={(e) => setCatForm({ ...catForm, name: e.target.value })} placeholder={t('categoryName')} />
<input value={catForm.nameEn} onChange={(e) => setCatForm({ ...catForm, nameEn: e.target.value })} placeholder={t('categoryNameEn')} />
<input value={catForm.name} onChange={(e) => setCatForm({ ...catForm, name: e.target.value })} placeholder={t('categoryName')} maxLength={45} />
<span className="second-brown">{t('order')}</span>
<input type="number" value={catForm.order} onChange={(e) => setCatForm({ ...catForm, order: e.target.value })} />
<p className="third-brown small-font">{t('forumEnHint')}</p>
<button type="submit" disabled={busy}>{t('create')}</button>
</form>
<br />
@@ -73,13 +112,12 @@ export function AdminForumManager({ initial }: { initial: Group[] }) {
<div key={category.id} className="inline-div" style={{ display: 'block' }}>
{editCat?.id === category.id ? (
<div className="admin-form separate2">
<input value={editCat.name} onChange={(e) => setEditCat({ ...editCat, name: e.target.value })} placeholder={t('categoryName')} />
<input value={editCat.nameEn} onChange={(e) => setEditCat({ ...editCat, nameEn: e.target.value })} placeholder={t('categoryNameEn')} />
<input value={editCat.name} onChange={(e) => setEditCat({ ...editCat, name: e.target.value })} placeholder={t('categoryName')} maxLength={45} />
<input type="number" value={editCat.order} onChange={(e) => setEditCat({ ...editCat, order: e.target.value })} />
<button
onClick={() =>
editCat.name.trim() &&
call(`/api/admin/forum/category/${category.id}`, 'PUT', { name: editCat.name, nameEn: editCat.nameEn, order: Number(editCat.order) }).then((ok) => ok && setEditCat(null))
call(`/api/admin/forum/category/${category.id}`, 'PUT', { name: editCat.name, order: Number(editCat.order) }).then((ok) => ok && setEditCat(null))
}
disabled={busy}
className="ns-tool-btn"
@@ -91,11 +129,9 @@ export function AdminForumManager({ initial }: { initial: Group[] }) {
) : (
<div className="title-content-h3">
<h3 className="big-font">
{category.name}
{category.name_en && <span className="third-brown small-font"> · EN: {category.name_en}</span>}{' '}
<span className="third-brown small-font">#{category.order}</span>{' '}
{category.name} <span className="third-brown small-font">#{category.order}</span>{' '}
<button
onClick={() => setEditCat({ id: category.id, name: category.name, nameEn: category.name_en, order: String(category.order) })}
onClick={() => setEditCat({ id: category.id, name: category.name, order: String(category.order) })}
disabled={busy}
className="ns-tool-btn"
>
@@ -112,7 +148,6 @@ export function AdminForumManager({ initial }: { initial: Group[] }) {
</div>
)}
{/* Foros de la categoría */}
<table className="max-center-table">
<tbody>
{forums.length === 0 && (
@@ -124,21 +159,11 @@ export function AdminForumManager({ initial }: { initial: Group[] }) {
editForum?.id === f.id ? (
<tr key={f.id} className="team-center-table-tr">
<td className="lefted separate" colSpan={2}>
<input value={editForum.name} onChange={(e) => setEditForum({ ...editForum, name: e.target.value })} placeholder={t('forumName')} maxLength={45} />
<input value={editForum.nameEn} onChange={(e) => setEditForum({ ...editForum, nameEn: e.target.value })} placeholder={t('forumNameEn')} maxLength={45} />
<input value={editForum.description} onChange={(e) => setEditForum({ ...editForum, description: e.target.value })} placeholder={t('forumDescription')} />
<input value={editForum.descriptionEn} onChange={(e) => setEditForum({ ...editForum, descriptionEn: e.target.value })} placeholder={t('forumDescriptionEn')} />
<ForumEditFields v={editForum} onChange={(patch) => setEditForum({ ...editForum, ...patch })} />
<button
onClick={() =>
editForum.name.trim() &&
call(`/api/admin/forum/${f.id}`, 'PUT', {
name: editForum.name,
nameEn: editForum.nameEn,
description: editForum.description,
descriptionEn: editForum.descriptionEn,
order: Number(editForum.order),
visibility: editForum.visibility !== 0,
}).then((ok) => ok && setEditForum(null))
call(`/api/admin/forum/${f.id}`, 'PUT', forumBody(editForum, category.id)).then((ok) => ok && setEditForum(null))
}
disabled={busy}
className="ns-tool-btn"
@@ -152,25 +177,29 @@ export function AdminForumManager({ initial }: { initial: Group[] }) {
<tr key={f.id} className="team-center-table-tr">
<td className="lefted separate">
<span className="yellow-info">{f.name}</span>{' '}
{f.name_en && <span className="third-brown small-font">· EN: {f.name_en}</span>}{' '}
{f.visibility === 0 && <span className="red-info2 small-font">({t('hidden')})</span>}
<span className="third-brown small-font">
· {t('forumType')}: {f.type} · #{f.order}
</span>
{f.description && <p className="third-brown small-font">{f.description}</p>}
</td>
<td className="real-info-box no-wrap-td">
<button
onClick={() => setEditForum({ id: f.id, name: f.name, nameEn: f.name_en, description: f.description, descriptionEn: f.description_en, order: String(f.order), visibility: f.visibility })}
onClick={() =>
setEditForum({
id: f.id,
name: f.name,
description: f.description,
icon: f.icon ?? '',
colortitle: f.colortitle ?? '',
type: String(f.type),
order: String(f.order),
})
}
disabled={busy}
className="ns-tool-btn"
>
{t('edit')}
</button>{' '}
<button
onClick={() => call(`/api/admin/forum/${f.id}`, 'PATCH', { visibility: f.visibility === 0 })}
disabled={busy}
className="ns-tool-btn"
>
{f.visibility === 0 ? t('show') : t('hide')}
</button>{' '}
<button
onClick={() => confirm(t('confirmDelete')) && call(`/api/admin/forum/${f.id}`, 'DELETE')}
disabled={busy}
@@ -191,21 +220,13 @@ export function AdminForumManager({ initial }: { initial: Group[] }) {
e.preventDefault()
const v = ff(category.id)
if (v.name.trim())
call('/api/admin/forum', 'POST', {
categoryId: category.id,
name: v.name,
nameEn: v.nameEn,
description: v.description,
descriptionEn: v.descriptionEn,
order: Number(v.order),
}).then((ok) => ok && setFF(category.id, { name: '', nameEn: '', description: '', descriptionEn: '', order: '0' }))
call('/api/admin/forum', 'POST', forumBody(v, category.id)).then(
(ok) => ok && setFF(category.id, EMPTY_FORUM),
)
}}
className="admin-form separate"
>
<input value={ff(category.id).name} onChange={(e) => setFF(category.id, { name: e.target.value })} placeholder={t('forumName')} maxLength={45} />
<input value={ff(category.id).nameEn} onChange={(e) => setFF(category.id, { nameEn: e.target.value })} placeholder={t('forumNameEn')} maxLength={45} />
<input value={ff(category.id).description} onChange={(e) => setFF(category.id, { description: e.target.value })} placeholder={t('forumDescription')} />
<input value={ff(category.id).descriptionEn} onChange={(e) => setFF(category.id, { descriptionEn: e.target.value })} placeholder={t('forumDescriptionEn')} />
<ForumEditFields v={ff(category.id)} onChange={(patch) => setFF(category.id, patch)} />
<button type="submit" disabled={busy}>{t('addForum')}</button>
</form>
</div>
+59
View File
@@ -0,0 +1,59 @@
'use client'
import { useState } from 'react'
import { useTranslations } from 'next-intl'
import { useRouter } from '@/i18n/navigation'
import { ForumEditor } from './ForumEditor'
/** Formulario de nuevo tema: título + editor TinyMCE, enviado por fetch. */
export function CreateTopicForm({ forumId }: { forumId: number }) {
const t = useTranslations('Forum')
const router = useRouter()
const [title, setTitle] = useState('')
const [text, setText] = useState('')
const [busy, setBusy] = useState(false)
const [error, setError] = useState<string | null>(null)
async function submit(e: React.FormEvent) {
e.preventDefault()
if (busy) return
if (title.trim().length < 3) return setError(t('errTitle'))
setBusy(true)
setError(null)
try {
const res = await fetch('/api/forum/topic', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'same-origin',
body: JSON.stringify({ forumId, title, text }),
})
const data: { success?: boolean; topicId?: number; error?: string } = await res.json()
if (data.success && data.topicId) router.push(`/forum/topic/${data.topicId}`)
else setError(data.error || t('genericError'))
} catch {
setError(t('genericError'))
} finally {
setBusy(false)
}
}
return (
<form onSubmit={submit}>
<input
className="forum-input"
value={title}
onChange={(e) => setTitle(e.target.value)}
type="text"
placeholder={t('topicTitle')}
maxLength={45}
/>
<ForumEditor value={text} onChange={setText} />
<div className="forum-form-actions">
<button type="submit" className="nice_button" disabled={busy}>
{busy ? t('sending') : t('postTopic')}
</button>
{error && <span className="red-form-response">{error}</span>}
</div>
</form>
)
}
+14
View File
@@ -0,0 +1,14 @@
'use client'
import { useTranslations } from 'next-intl'
import { Link } from '@/i18n/navigation'
/** Enlace «Editar» de un post, hacia la página de edición a pantalla completa. */
export function EditPostForm({ postId }: { postId: number; initialText?: string }) {
const t = useTranslations('Forum')
return (
<Link className="edit" href={`/forum/edit/${postId}`}>
{t('edit')}
</Link>
)
}
+60
View File
@@ -0,0 +1,60 @@
'use client'
import { useState } from 'react'
import { useTranslations } from 'next-intl'
import { useRouter, Link } from '@/i18n/navigation'
import { ForumEditor } from './ForumEditor'
/** Edición de un post a página completa: editor TinyMCE precargado, PATCH por fetch. */
export function EditPostPageForm({
postId,
topicId,
initialText,
}: {
postId: number
topicId: number
initialText: string
}) {
const t = useTranslations('Forum')
const router = useRouter()
const [text, setText] = useState(initialText)
const [busy, setBusy] = useState(false)
const [error, setError] = useState<string | null>(null)
async function submit(e: React.FormEvent) {
e.preventDefault()
if (busy) return
setBusy(true)
setError(null)
try {
const res = await fetch('/api/forum/post', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
credentials: 'same-origin',
body: JSON.stringify({ postId, text }),
})
const data: { success?: boolean; error?: string } = await res.json()
if (data.success) router.push(`/forum/topic/${topicId}`)
else setError(data.error || t('genericError'))
} catch {
setError(t('genericError'))
} finally {
setBusy(false)
}
}
return (
<form onSubmit={submit}>
<ForumEditor value={text} onChange={setText} />
<div className="forum-form-actions">
<button type="submit" className="nice_button" disabled={busy}>
{busy ? t('sending') : t('editPost')}
</button>
<Link className="nice_button" href={`/forum/topic/${topicId}`}>
{t('cancel')}
</Link>
{error && <span className="red-form-response">{error}</span>}
</div>
</form>
)
}
+19
View File
@@ -0,0 +1,19 @@
import { Link } from '@/i18n/navigation'
/** Migas del foro (Foro Subforo Tema). El último item va sin enlace. */
export function ForumBreadcrumb({
items,
}: {
items: { label: string; href?: string }[]
}) {
return (
<div className="forum-path">
{items.map((it, i) => (
<span key={i}>
{i > 0 && <span className="sep"></span>}
{it.href ? <Link href={it.href}>{it.label}</Link> : <span>{it.label}</span>}
</span>
))}
</div>
)
}
+48
View File
@@ -0,0 +1,48 @@
'use client'
import { Editor } from '@tinymce/tinymce-react'
/**
* Editor TinyMCE del foro (community, self-hosted desde /tinymce — ver
* scripts/copy-tinymce.mjs). Mismo editor que el foro original de FusionCMS, con su
* skin oscura y su lista de plugins, adaptado a React como componente controlado:
* el HTML vive en el estado del padre (value/onChange) y se envía por fetch, en vez
* del `tinyMCE.triggerSave()` + jQuery del forum.js original.
*
* `licenseKey: 'gpl'` deja claro que es la edición community (GPL), no la de nube.
* El HTML que produce se sanea SIEMPRE en el servidor con nh3 (lib/forum-sanitize),
* nunca se confía en el cliente.
*/
export function ForumEditor({
value,
onChange,
height = 400,
}: {
value: string
onChange: (html: string) => void
height?: number
}) {
return (
<Editor
tinymceScriptSrc="/tinymce/tinymce.min.js"
licenseKey="gpl"
value={value}
onEditorChange={(content) => onChange(content)}
init={{
height,
menubar: false,
statusbar: false,
skin: 'oxide-dark',
content_css: 'dark',
branding: false,
promotion: false,
mobile: { menubar: true },
plugins:
'preview searchreplace autolink directionality visualblocks visualchars fullscreen image link media codesample table charmap pagebreak nonbreaking anchor insertdatetime advlist lists wordcount emoticons',
toolbar:
'bold italic strikethrough forecolor backcolor emoticons | link image media | alignleft aligncenter alignright alignjustify | numlist bullist outdent indent | removeformat',
image_advtab: true,
}}
/>
)
}
+68
View File
@@ -0,0 +1,68 @@
'use client'
import { useState } from 'react'
import { useTranslations } from 'next-intl'
import { useRouter } from '@/i18n/navigation'
/**
* Acciones de moderación de un post o tema (borrar/restaurar y, en temas,
* cerrar/abrir). Reemplaza los enlaces GET del forum.js original por POST a
* /api/forum/moderate, para no mutar estado con peticiones GET.
*/
export function ForumModActions({
kind,
id,
deleted = false,
locked = false,
}: {
kind: 'post' | 'topic'
id: number
deleted?: boolean
locked?: boolean
}) {
const t = useTranslations('Forum')
const router = useRouter()
const [busy, setBusy] = useState(false)
async function act(action: string) {
if (busy) return
setBusy(true)
try {
const res = await fetch('/api/forum/moderate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'same-origin',
body: JSON.stringify({ kind, id, action }),
})
const data: { success?: boolean } = await res.json()
if (data.success) router.refresh()
} finally {
setBusy(false)
}
}
return (
<>
<a
className="delete"
role="button"
tabIndex={0}
onClick={() => act(deleted ? 'undelete' : 'delete')}
style={busy ? { opacity: 0.5 } : undefined}
>
{deleted ? t('undelete') : t('delete')}
</a>
{kind === 'topic' && (
<a
className="lock"
role="button"
tabIndex={0}
onClick={() => act(locked ? 'unlock' : 'lock')}
style={busy ? { opacity: 0.5 } : undefined}
>
{locked ? t('unlock') : t('lock')}
</a>
)}
</>
)
}
-32
View File
@@ -1,32 +0,0 @@
'use client'
import { useState } from 'react'
import { useTranslations } from 'next-intl'
import { useRouter } from '@/i18n/navigation'
export function ForumSearchBox({ initial = '' }: { initial?: string }) {
const t = useTranslations('Forum')
const router = useRouter()
const [q, setQ] = useState(initial)
function submit(e: React.FormEvent) {
e.preventDefault()
const query = q.trim()
if (query.length < 2) return
router.push(`/forum/search?q=${encodeURIComponent(query)}`)
}
return (
<form onSubmit={submit} className="centered separate">
<input
type="text"
value={q}
onChange={(e) => setQ(e.target.value)}
placeholder={t('searchPlaceholder')}
/>{' '}
<button type="submit" className="search-items-button">
{t('search')}
</button>
</form>
)
}
-59
View File
@@ -1,59 +0,0 @@
'use client'
import { useState } from 'react'
import { useTranslations } from 'next-intl'
import { useRouter } from '@/i18n/navigation'
import { RichTextArea } from './RichTextArea'
export function NewTopicForm({ forumId }: { forumId: number }) {
const t = useTranslations('Forum')
const router = useRouter()
const [name, setName] = useState('')
const [text, setText] = useState('')
const [busy, setBusy] = useState(false)
const [error, setError] = useState<string | null>(null)
async function handleSubmit(e: React.FormEvent) {
e.preventDefault()
if (busy || !name.trim() || !text.trim()) return
setBusy(true)
setError(null)
try {
const res = await fetch('/api/forum/topic', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'same-origin',
body: JSON.stringify({ forumId, name, text }),
})
const data: { success?: boolean; topicId?: number } = await res.json()
if (data.success && data.topicId) router.push(`/forum/topic/${data.topicId}`)
else {
setError(t('genericError'))
setBusy(false)
}
} catch {
setError(t('genericError'))
setBusy(false)
}
}
return (
<form onSubmit={handleSubmit} className="info-box-light separate2">
<div className="title-content-h3">
<h3 className="big-font">{t('newTopic')}</h3>
</div>
<br />
<input value={name} onChange={(e) => setName(e.target.value)} placeholder={t('newTopicName')} maxLength={200} style={{ width: '100%' }} />
<br />
<br />
<RichTextArea value={text} onChange={setText} placeholder={t('newTopicText')} rows={4} />
<br />
<button type="submit" disabled={busy}>
{busy ? t('publishing') : t('publish')}
</button>
<div className="alert-message" style={{ display: error ? 'block' : 'none' }}>
{error && <span className="red-form-response">{error}</span>}
</div>
</form>
)
}
-133
View File
@@ -1,133 +0,0 @@
'use client'
import { useState } from 'react'
import { useTranslations } from 'next-intl'
import { useRouter } from '@/i18n/navigation'
import { RichTextArea } from './RichTextArea'
export function PostActions({
postId,
initialText,
deleted = false,
}: {
postId: number
initialText: string
deleted?: boolean
}) {
const t = useTranslations('Forum')
const router = useRouter()
const [editing, setEditing] = useState(false)
const [text, setText] = useState(initialText)
const [busy, setBusy] = useState(false)
const [error, setError] = useState<string | null>(null)
async function save() {
if (busy || !text.trim()) return
setBusy(true)
setError(null)
try {
const res = await fetch('/api/forum/post', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
credentials: 'same-origin',
body: JSON.stringify({ postId, text }),
})
const data: { success?: boolean; error?: string } = await res.json()
if (data.success) {
setEditing(false)
router.refresh()
} else {
setError(t(data.error === 'tooShort' ? 'tooShort' : data.error === 'topicLocked' ? 'topicLocked' : 'genericError'))
}
} catch {
setError(t('genericError'))
} finally {
setBusy(false)
}
}
async function restore() {
if (busy) return
setBusy(true)
setError(null)
try {
const res = await fetch('/api/forum/post', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
credentials: 'same-origin',
body: JSON.stringify({ postId }),
})
if ((await res.json()).success) router.refresh()
else setError(t('genericError'))
} catch {
setError(t('genericError'))
} finally {
setBusy(false)
}
}
async function remove() {
if (busy || !confirm(t('confirmDeletePost'))) return
setBusy(true)
setError(null)
try {
const res = await fetch('/api/forum/post', {
method: 'DELETE',
headers: { 'Content-Type': 'application/json' },
credentials: 'same-origin',
body: JSON.stringify({ postId }),
})
const data: { success?: boolean } = await res.json()
if (data.success) router.refresh()
else setError(t('genericError'))
} catch {
setError(t('genericError'))
} finally {
setBusy(false)
}
}
if (editing) {
return (
<div className="separate">
<RichTextArea value={text} onChange={setText} rows={4} />
<br />
<button type="button" onClick={save} disabled={busy} className="ns-tool-btn">
{busy ? t('sending') : t('save')}
</button>{' '}
<button
type="button"
onClick={() => { setEditing(false); setText(initialText); setError(null) }}
className="ns-tool-btn"
>
{t('cancel')}
</button>
{error && <p className="red-info2 small-font">{error}</p>}
</div>
)
}
if (deleted) {
return (
<div className="separate small-font">
<button type="button" onClick={restore} disabled={busy} className="ns-tool-btn green-info">
{t('restore')}
</button>
{error && <span className="red-info2"> {error}</span>}
</div>
)
}
return (
<div className="separate small-font">
<a role="button" tabIndex={0} onClick={() => setEditing(true)} className="second-brown" style={{ cursor: 'pointer' }}>
{t('edit')}
</a>
{' '}
<a role="button" tabIndex={0} onClick={() => { if (!busy) remove() }} className="second-brown" style={{ cursor: 'pointer' }}>
{t('delete')}
</a>
{error && <span className="red-info2"> {error}</span>}
</div>
)
}
+18 -15
View File
@@ -3,8 +3,9 @@
import { useState } from 'react'
import { useTranslations } from 'next-intl'
import { useRouter } from '@/i18n/navigation'
import { RichTextArea } from './RichTextArea'
import { ForumEditor } from './ForumEditor'
/** Respuesta rápida a un tema: editor TinyMCE, enviado por fetch. */
export function ReplyForm({ topicId }: { topicId: number }) {
const t = useTranslations('Forum')
const router = useRouter()
@@ -12,9 +13,9 @@ export function ReplyForm({ topicId }: { topicId: number }) {
const [busy, setBusy] = useState(false)
const [error, setError] = useState<string | null>(null)
async function handleSubmit(e: React.FormEvent) {
async function submit(e: React.FormEvent) {
e.preventDefault()
if (busy || !text.trim()) return
if (busy) return
setBusy(true)
setError(null)
try {
@@ -24,12 +25,12 @@ export function ReplyForm({ topicId }: { topicId: number }) {
credentials: 'same-origin',
body: JSON.stringify({ topicId, text }),
})
const data: { success?: boolean } = await res.json()
const data: { success?: boolean; error?: string } = await res.json()
if (data.success) {
setText('')
router.refresh()
} else {
setError(t('genericError'))
setError(data.error || t('genericError'))
}
} catch {
setError(t('genericError'))
@@ -39,15 +40,17 @@ export function ReplyForm({ topicId }: { topicId: number }) {
}
return (
<form onSubmit={handleSubmit} className="separate2">
<RichTextArea value={text} onChange={setText} placeholder={t('replyText')} rows={3} />
<br />
<button type="submit" disabled={busy}>
{busy ? t('sending') : t('sendReply')}
</button>
<div className="alert-message" style={{ display: error ? 'block' : 'none' }}>
{error && <span className="red-form-response">{error}</span>}
</div>
</form>
<div className="quick_reply">
<h2>{t('reply')}</h2>
<form onSubmit={submit}>
<ForumEditor value={text} onChange={setText} height={260} />
<div className="forum-form-actions">
<button type="submit" className="nice_button" disabled={busy}>
{busy ? t('sending') : t('post')}
</button>
{error && <span className="red-form-response">{error}</span>}
</div>
</form>
</div>
)
}
-95
View File
@@ -1,95 +0,0 @@
'use client'
import { useState } from 'react'
import { useTranslations } from 'next-intl'
import { useRouter } from '@/i18n/navigation'
export function TopicModBar({
topicId,
locked,
sticky,
deleted = false,
moveForums = [],
}: {
topicId: number
locked: boolean
sticky: boolean
deleted?: boolean
moveForums?: { id: number; name: string }[]
}) {
const t = useTranslations('Forum')
const router = useRouter()
const [busy, setBusy] = useState(false)
async function act(action: string, extra?: Record<string, unknown>, confirmMsg?: string) {
if (busy) return
if (confirmMsg && !confirm(confirmMsg)) return
setBusy(true)
try {
const res = await fetch('/api/forum/moderate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'same-origin',
body: JSON.stringify({ topicId, action, ...extra }),
})
const data: { success?: boolean; forumId?: number } = await res.json()
if (data.success && action === 'delete' && data.forumId) {
router.push(`/forum/${data.forumId}`)
} else if (data.success && action === 'move') {
router.push(`/forum/${extra?.forumId}`)
} else {
router.refresh()
}
} finally {
setBusy(false)
}
}
if (deleted) {
return (
<div className="info-box-light separate">
<span className="red-info2">{t('deletedMark')}</span>{' '}
<button type="button" onClick={() => act('restore')} disabled={busy} className="ns-tool-btn green-info">
{t('restoreTopic')}
</button>
</div>
)
}
return (
<div className="info-box-light separate">
<span className="yellow-info">{t('moderation')}:</span>{' '}
<button type="button" onClick={() => act(locked ? 'unlock' : 'lock')} disabled={busy} className="ns-tool-btn">
{locked ? t('unlock') : t('lock')}
</button>{' '}
<button type="button" onClick={() => act(sticky ? 'unsticky' : 'sticky')} disabled={busy} className="ns-tool-btn">
{sticky ? t('unpin') : t('pin')}
</button>{' '}
{moveForums.length > 0 && (
<select
defaultValue=""
disabled={busy}
onChange={(e) => {
const forumId = Number(e.target.value)
e.target.value = ''
if (forumId) act('move', { forumId })
}}
style={{ width: 'auto' }}
aria-label={t('moveTopic')}
>
<option value="" disabled>
{t('moveTopic')}
</option>
{moveForums.map((f) => (
<option key={f.id} value={f.id}>
{f.name}
</option>
))}
</select>
)}{' '}
<button type="button" onClick={() => act('delete', undefined, t('confirmDeleteTopic'))} disabled={busy} className="ns-tool-btn red-info2">
{t('deleteTopic')}
</button>
</div>
)
}