Files
ESPDocs/components/CodeExample.jsx
T
Lucas RayanandClaude Sonnet 5.5 5a9fe676fc
CI / Lint e auditorias (push) Successful in 1m10s
CI / Trivy (dependências e segredos) (push) Successful in 12s
CI / Imagem Docker (linux/arm64) (push) Successful in 2m39s
Release / Plano (reaproveitar a imagem?) (push) Successful in 6s
Release / ci (push) Skipped
Release / Publica a imagem (linux/arm64) (push) Successful in 18s
Release / Cria a release no Gitea (push) Successful in 5s
feat(i18n): Simplified Chinese (zh-CN), search answers per locale, fr/de/es data fixes
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 23:28:39 -03:00

259 lines
9.2 KiB
React

"use client";
import { useEffect, useState } from "react";
import { Check, Copy, ExternalLink } from "lucide-react";
import { usePathname } from "next/navigation";
export default function CodeExample({ framework }) {
const pathname = usePathname() || "";
const isEn = pathname === "/en" || pathname.startsWith("/en/");
const isEs = pathname === "/es" || pathname.startsWith("/es/");
const isFr = pathname === "/fr" || pathname.startsWith("/fr/");
const isDe = pathname === "/de" || pathname.startsWith("/de/");
const isZh = pathname === "/zh-CN" || pathname.startsWith("/zh-CN/");
const loc = isEn ? "en" : isEs ? "es" : isFr ? "fr" : isZh ? "zh-CN" : isDe ? "de" : "pt";
const examplesUrl = framework?.exemplos;
const [sample, setSample] = useState("");
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const [copied, setCopied] = useState(false);
useEffect(() => {
setSample("");
setError(null);
setLoading(false);
if (!framework) return;
const exemploPath = framework.exemplo;
if (!exemploPath) {
setSample(
isEn
? `// Full examples: ${examplesUrl || "see repository"}\n`
: isEs
? `// Ejemplos completos: ${examplesUrl || "ver repositorio"}\n`
: isFr
? `// Exemples complets : ${examplesUrl || "voir le dépôt"}\n`
: isZh ? `// 完整示例:${examplesUrl || "见代码仓库"}\n` : isDe
? `// Vollständige Beispiele: ${examplesUrl || "Repository ansehen"}\n`
: `// Exemplos completos: ${examplesUrl || "ver repositório"}\n`
);
return;
}
// Se locale for diferente de pt, busca primeiro em /exemplos/<loc>/
let url = exemploPath.startsWith("/") ? exemploPath : `/${exemploPath}`;
if (loc !== "pt" && url.startsWith("/exemplos/") && !url.startsWith(`/exemplos/${loc}/`)) {
url = url.replace("/exemplos/", `/exemplos/${loc}/`);
}
let cancelled = false;
setLoading(true);
fetch(url)
.then((res) => {
if (!res.ok) {
// Fallback para o arquivo original se não achar a versão traduzida
const fallbackUrl = exemploPath.startsWith("/") ? exemploPath : `/${exemploPath}`;
if (fallbackUrl !== url) {
return fetch(fallbackUrl).then((r2) => {
if (!r2.ok) throw new Error(`HTTP ${r2.status}`);
return r2.text();
});
}
throw new Error(`HTTP ${res.status}`);
}
return res.text();
})
.then((text) => {
if (cancelled) return;
if (text && text.trim().length > 0) {
setSample(text);
} else {
setSample(
isEn
? "// The example file is empty. Refer to the official repository.\n"
: isEs
? "// El archivo de ejemplo está vacío. Consulte el repositorio oficial.\n"
: isFr
? "// Le fichier d'exemple est vide. Consultez le dépôt officiel.\n"
: isZh ? "// 示例文件为空,请查阅官方代码仓库。\n" : isDe
? "// Die Beispieldatei ist leer. Bitte konsultieren Sie das offizielle Repository.\n"
: "// O arquivo de exemplo está vazio. Consulte o repositório oficial.\n"
);
setError(
isEn
? "empty file"
: isEs
? "archivo vacío"
: isFr
? "fichier vide"
: isZh ? "文件为空" : isDe
? "leere Datei"
: "arquivo vazio"
);
}
})
.catch((err) => {
if (cancelled) return;
setSample(
isEn
? "// Could not load example.\n// Refer to official repository for complete examples.\n"
: isEs
? "// No fue posible cargar el ejemplo.\n// Consulte el repositorio oficial para ver los ejemplos completos.\n"
: isFr
? "// Impossible de charger l'exemple.\n// Consultez le dépôt officiel pour des exemples complets.\n"
: isZh ? "// 无法加载示例。\n// 完整示例请查阅官方代码仓库。\n" : isDe
? "// Beispiel konnte nicht geladen werden.\n// Vollständige Beispiele finden Sie im offiziellen Repository.\n"
: "// Não foi possível carregar o exemplo.\n// Consulte o repositório oficial para exemplos completos.\n"
);
setError(
err.message ||
(isEn
? "load failure"
: isEs
? "fallo al cargar"
: isFr
? "échec du chargement"
: isZh ? "加载失败" : isDe
? "Ladefehler"
: "falha ao carregar")
);
})
.finally(() => {
if (!cancelled) setLoading(false);
});
return () => {
cancelled = true;
};
}, [framework?.exemplo, framework?.exemplos, isEn, isEs, isFr, isDe, loc]);
const lines = (sample || "").replace(/\n$/, "").split("\n");
async function handleCopy() {
try {
await navigator.clipboard.writeText(sample);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
} catch {}
}
return (
<div className="card p-5 sm:p-7">
<div className="flex flex-wrap items-start justify-between gap-4">
<div>
<h2 className="font-display text-xl font-semibold tracking-[-0.03em] text-ink">
{isEn
? "Code example"
: isEs
? "Ejemplo de código"
: isFr
? "Exemple de code"
: isZh ? "代码示例" : isDe
? "Codebeispiel"
: "Exemplo de código"}
</h2>
<p className="mt-1 text-sm text-muted">
{isEn
? `Starter snippet in ${framework?.linguagem}. Adjust pins and configuration for your board.`
: isEs
? `Fragmento de inicio en ${framework?.linguagem}. Ajuste los pines y la configuración para su placa.`
: isFr
? `Extrait de départ en ${framework?.linguagem}. Adaptez les broches et la configuration à votre carte.`
: isZh ? `${framework?.linguagem} 的起始代码片段,请根据你的开发板调整引脚和配置。` : isDe
? `Startbeispiel in ${framework?.linguagem}. Passen Sie Pins und Konfiguration an Ihr Board an.`
: `Trecho de partida em ${framework?.linguagem}. Ajuste pinos e configuração à sua placa.`}
</p>
</div>
<div className="flex flex-wrap items-center gap-2">
<button type="button" onClick={handleCopy} className="btn btn-ghost btn-sm">
{copied ? <Check className="h-4 w-4 text-ok" aria-hidden="true" /> : <Copy className="h-4 w-4" aria-hidden="true" />}
<span role="status">
{copied
? (isEn ? "Copied" : isEs ? "Copiado" : isFr ? "Copié" : isZh ? "已复制" : isDe ? "Kopiert" : "Copiado")
: (isEn ? "Copy" : isEs ? "Copiar" : isFr ? "Copier" : isZh ? "复制" : isDe ? "Kopieren" : "Copiar")}
</span>
</button>
{examplesUrl && (
<a href={examplesUrl} target="_blank" rel="noopener noreferrer" className="btn btn-ghost btn-sm">
{isEn ? "More examples" : isEs ? "Más ejemplos" : isFr ? "Plus d'exemples" : isZh ? "更多示例" : isDe ? "Weitere Beispiele" : "Mais exemplos"}
<ExternalLink className="h-4 w-4" aria-hidden="true" />
<span className="sr-only">
{isEn
? " (opens in new tab)"
: isEs
? " (abre en una pestaña nueva)"
: isFr
? " (ouvre un nouvel onglet)"
: isZh ? "(在新标签页打开)" : isDe
? " (öffnet in neuem Tab)"
: " (abre em nova aba)"}
</span>
</a>
)}
</div>
</div>
<div className="code-panel mt-5" aria-busy={loading}>
<div className="flex items-center justify-between border-b border-white/10 px-4 py-2.5 text-xs text-[#a6afbd]">
<span className="font-mono">{framework?.nome}</span>
<span>
{loading
? (isEn
? "Loading example…"
: isEs
? "Cargando ejemplo…"
: isFr
? "Chargement de l'exemple…"
: isZh ? "正在加载示例…" : isDe
? "Beispiel wird geladen…"
: "Carregando exemplo…")
: framework?.linguagem}
</span>
</div>
<pre
tabIndex={0}
aria-label={
isEn
? `Code example in ${framework?.linguagem}`
: isEs
? `Código de ejemplo en ${framework?.linguagem}`
: isFr
? `Exemple de code en ${framework?.linguagem}`
: isZh ? `${framework?.linguagem} 示例代码` : isDe
? `Codebeispiel in ${framework?.linguagem}`
: `Código de exemplo em ${framework?.linguagem}`
}
>
<code>
{lines.map((line, idx) => (
<span key={idx} className="flex">
<span className="mr-4 w-7 shrink-0 select-none text-right text-[#7d8794]">{idx + 1}</span>
<span className="min-w-0 whitespace-pre text-[#e9eef4]">{line || " "}</span>
</span>
))}
</code>
</pre>
</div>
{error && (
<p role="alert" className="callout callout-warn mt-4">
{isEn
? `Could not load local example (${error}). Use “More examples” to view official code.`
: isEs
? `No se pudo cargar el ejemplo local (${error}). Utilice “Más ejemplos” para ver el código oficial.`
: isFr
? `Impossible de charger l'exemple local (${error}). Utilisez « Plus d'exemples » pour consulter le code officiel.`
: isZh ? `无法加载本地示例(${error})。请使用“更多示例”查看官方代码。` : isDe
? `Lokales Beispiel konnte nicht geladen werden (${error}). Nutzen Sie „Weitere Beispiele“, um den offiziellen Code anzusehen.`
: `Não foi possível carregar o exemplo local (${error}). Use “Mais exemplos” para ver o código oficial.`}
</p>
)}
</div>
);
}