Update page.tsx

This commit is contained in:
MacRimi 2025-02-15 17:52:05 +01:00 committed by GitHub
parent 14e0c1cf23
commit 74d54ee9de
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -3,6 +3,7 @@ import path from "path"
import { remark } from "remark"
import html from "remark-html"
import * as gfm from "remark-gfm"
import matter from "gray-matter"
import dynamic from "next/dynamic"
import React from "react"
import parse from "html-react-parser"
@ -11,7 +12,7 @@ const CopyableCode = dynamic(() => import("@/components/CopyableCode"), { ssr: f
const guidesDirectory = path.join(process.cwd(), "..", "guides")
// 🔹 Función para buscar archivos Markdown dentro de subdirectorios
// 🔹 Busca archivos Markdown dentro de subdirectorios
function findMarkdownFiles(dir: string, basePath = "") {
let files: { slug: string; path: string }[] = []
@ -23,7 +24,7 @@ function findMarkdownFiles(dir: string, basePath = "") {
files = files.concat(findMarkdownFiles(fullPath, relativePath))
} else if (entry.isFile() && entry.name.endsWith(".md")) {
files.push({
slug: relativePath.replace(/\.md$/, ""), // 🔹 Quitamos la extensión .md
slug: relativePath.replace(/\.md$/, "").replace(/\/index$/, ""), // 🔹 Quitamos `.md` y `index` si es necesario
path: fullPath,
})
}
@ -32,27 +33,37 @@ function findMarkdownFiles(dir: string, basePath = "") {
return files
}
// 🔹 Obtiene el contenido de la guía
async function getGuideContent(slug: string) {
try {
const markdownFiles = findMarkdownFiles(guidesDirectory)
const guideFile = markdownFiles.find((file) => file.slug === slug)
let guideFile = markdownFiles.find((file) => file.slug === slug)
// 🔹 Si no se encuentra, intentamos con `index.md` dentro de la carpeta
if (!guideFile) {
guideFile = markdownFiles.find((file) => file.slug === `${slug}/index`)
}
if (!guideFile) {
console.error(`❌ No se encontró la guía: ${slug}`)
return "<p class='text-red-600'>Error: No se encontró la guía solicitada.</p>"
return { content: "<p class='text-red-600'>Error: No se encontró la guía solicitada.</p>", metadata: null }
}
const fileContents = fs.readFileSync(guideFile.path, "utf8")
// 🔹 Extraemos los metadatos (title, description, etc.)
const { content, data } = matter(fileContents)
const result = await remark()
.use(gfm.default || gfm)
.use(html)
.process(fileContents)
.process(content)
return result.toString()
return { content: result.toString(), metadata: data }
} catch (error) {
console.error(`❌ Error al leer la guía ${slug}`, error)
return "<p class='text-red-600'>Error: No se pudo cargar la guía.</p>"
return { content: "<p class='text-red-600'>Error: No se pudo cargar la guía.</p>", metadata: null }
}
}
@ -67,12 +78,14 @@ export async function generateStaticParams() {
}
}
// 🔹 Limpia las comillas invertidas en fragmentos de código en línea
function cleanInlineCode(content: string) {
return content.replace(/<code>(.*?)<\/code>/g, (_, codeContent) => {
return `<code class="bg-gray-200 text-gray-900 px-1 rounded">${codeContent.replace(/^`|`$/g, "")}</code>`
})
}
// 🔹 Envuelve los bloques de código en `<CopyableCode />`
function wrapCodeBlocksWithCopyable(content: string) {
return parse(content, {
replace: (domNode: any) => {
@ -87,14 +100,17 @@ function wrapCodeBlocksWithCopyable(content: string) {
})
}
// 🔹 Página principal de cada guía
export default async function GuidePage({ params }: { params: { slug: string } }) {
const guideContent = await getGuideContent(params.slug)
const cleanedInlineCode = cleanInlineCode(guideContent)
const { content, metadata } = await getGuideContent(params.slug)
const cleanedInlineCode = cleanInlineCode(content)
const parsedContent = wrapCodeBlocksWithCopyable(cleanedInlineCode)
return (
<div className="min-h-screen bg-white text-gray-900">
<div className="container mx-auto px-4 py-16" style={{ maxWidth: "980px" }}>
{metadata?.title && <h1 className="text-4xl font-bold mb-4">{metadata.title}</h1>}
{metadata?.description && <p className="text-lg text-gray-700 mb-8">{metadata.description}</p>}
<div className="prose max-w-none text-[16px]">{parsedContent}</div>
</div>
</div>