Reescrita dos geradores: biblioteca IGenerator, minimal API e novo frontend
- GeradoresService: cada tipo passa a ser um IGenerator (NIF, NIPC, NISS, CC, passaporte, IBAN, NIB, cartões, referência MB, pessoa, telefone, código postal, email, matrícula, EAN, UUID) registado em GeneratorRegistry; remove DAL/EF - GeradoresWS: minimal APIs em /api/v1 com OpenAPI + Scalar e health check - UnitTest: testes de ida e volta, valores conhecidos, detecção e API - geradoresfe: UI construída a partir dos metadados da API, validador livre, exportação CSV/JSON/TXT, nginx com API_UPSTREAM configurável - Docker, docker-compose e Jenkinsfile actualizados Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
14
geradoresfe/src/components/ChecksumBadge.tsx
Normal file
14
geradoresfe/src/components/ChecksumBadge.tsx
Normal file
@@ -0,0 +1,14 @@
|
||||
import { ShieldCheckIcon } from "lucide-react";
|
||||
import type { Generator } from "../lib/api";
|
||||
import { Badge } from "./ui/Badge";
|
||||
|
||||
export function ChecksumBadge({ generator }: { generator: Generator }) {
|
||||
if (!generator.canValidate) return null;
|
||||
return generator.hasChecksum ? (
|
||||
<Badge tone="green" className="shrink-0">
|
||||
<ShieldCheckIcon className="h-3 w-3" /> Controlo
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge className="shrink-0">Formato</Badge>
|
||||
);
|
||||
}
|
||||
57
geradoresfe/src/components/GeneratorCard.tsx
Normal file
57
geradoresfe/src/components/GeneratorCard.tsx
Normal file
@@ -0,0 +1,57 @@
|
||||
import { useState } from "react";
|
||||
import { Link } from "react-router";
|
||||
import { ArrowRightIcon, RefreshCwIcon } from "lucide-react";
|
||||
import { toast } from "react-hot-toast";
|
||||
import { api, defaultOptions, type Generator } from "../lib/api";
|
||||
import { OptionsForm } from "./OptionsForm";
|
||||
import { Button } from "./ui/Button";
|
||||
import { ResultDisplay } from "./ui/ResultDisplay";
|
||||
import { ChecksumBadge } from "./ChecksumBadge";
|
||||
|
||||
/** Cartão de geração rápida (1 valor) usado na página inicial. */
|
||||
export function GeneratorCard({ generator }: { generator: Generator }) {
|
||||
const [options, setOptions] = useState(() => defaultOptions(generator));
|
||||
const [value, setValue] = useState("");
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const generate = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const [item] = await api.generate(generator.id, options);
|
||||
setValue(item.value);
|
||||
} catch (e) {
|
||||
toast.error((e as Error).message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<article className="flex flex-col gap-4 rounded-2xl border border-gray-200 bg-white p-5 shadow-sm transition-shadow hover:shadow-md dark:border-zinc-800 dark:bg-zinc-900">
|
||||
<header>
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<h3 className="text-lg font-bold text-blue-700 dark:text-blue-400">{generator.name}</h3>
|
||||
<ChecksumBadge generator={generator} />
|
||||
</div>
|
||||
<p className="mt-1 text-sm text-gray-600 dark:text-gray-400">{generator.description}</p>
|
||||
</header>
|
||||
|
||||
<OptionsForm generator={generator} values={options} onChange={(k, v) => setOptions((o) => ({ ...o, [k]: v }))} />
|
||||
|
||||
<div className="mt-auto flex flex-col gap-3">
|
||||
<ResultDisplay value={value} label={generator.name} />
|
||||
<div className="flex gap-2">
|
||||
<Button onClick={generate} loading={loading} icon={<RefreshCwIcon className="h-4 w-4" />} className="flex-1">
|
||||
Gerar
|
||||
</Button>
|
||||
<Link
|
||||
to={`/gerador/${generator.id}`}
|
||||
className="inline-flex items-center gap-1 rounded-lg px-3 py-2 text-sm font-medium text-blue-700 hover:bg-blue-50 dark:text-blue-400 dark:hover:bg-zinc-800"
|
||||
>
|
||||
Em lote <ArrowRightIcon className="h-4 w-4" />
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
);
|
||||
}
|
||||
@@ -1,191 +0,0 @@
|
||||
// src/components/Geradores/GeradorCard.tsx
|
||||
import { useCallback, useState } from "react";
|
||||
import { RefreshCwIcon, CopyIcon } from "lucide-react";
|
||||
import { Button } from "../ui/Button";
|
||||
import { Input } from "../ui/Input";
|
||||
import { Select } from "../ui/Select";
|
||||
import { ResultDisplay } from "../ui/ResultDisplay";
|
||||
import { toast } from "react-hot-toast";
|
||||
|
||||
export type Parametro =
|
||||
| { nome: string; tipo: "text" | "number" | "password"; placeholder?: string; default?: string }
|
||||
| { nome: string; tipo: "select"; options: { label: string; value: string }[]; default?: string };
|
||||
|
||||
export type GeradorCardProps = {
|
||||
readonly titulo: string;
|
||||
readonly descricao?: string;
|
||||
readonly parametros?: Parametro[];
|
||||
readonly onGerar: (parametros?: Record<string, string>) => string | Promise<string>;
|
||||
readonly onValidar?: (valor: string) => boolean | Promise<boolean>;
|
||||
};
|
||||
|
||||
export default function GeradorCard({
|
||||
titulo,
|
||||
descricao,
|
||||
parametros = [],
|
||||
onGerar,
|
||||
onValidar,
|
||||
}: GeradorCardProps) {
|
||||
// Inicializa paramInputs com defaults vindos de `parametros`
|
||||
const initialParamInputs = parametros.reduce<Record<string, string>>((acc, p) => {
|
||||
debugger;
|
||||
if (p.default) {
|
||||
acc[p.nome] = p.default;
|
||||
} else {
|
||||
acc[p.nome] = "";
|
||||
}
|
||||
return acc;
|
||||
}, {});
|
||||
|
||||
const [resultado, setResultado] = useState("");
|
||||
const [paramInputs, setParamInputs] = useState<Record<string, string>>(initialParamInputs);
|
||||
const [validado, setValidado] = useState<boolean | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const handleInputChange = useCallback((nome: string, valor: string) => {
|
||||
setParamInputs((prev) => ({ ...prev, [nome]: valor }));
|
||||
}, []);
|
||||
|
||||
const handleGerar = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setValidado(null);
|
||||
try {
|
||||
const gerado = await onGerar(paramInputs);
|
||||
setResultado(typeof gerado === "string" ? gerado : String(gerado ?? ""));
|
||||
toast.success(`${titulo} gerado com sucesso.`, { duration: 2000 });
|
||||
} catch (err) {
|
||||
console.error("Erro ao gerar:", err);
|
||||
toast.error("Falha ao gerar. Tente novamente.");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [onGerar, paramInputs, titulo]);
|
||||
|
||||
const handleValidar = useCallback(async () => {
|
||||
if (!onValidar) return;
|
||||
if (!resultado) {
|
||||
toast.error("Nenhum valor para validar.");
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
try {
|
||||
const isValid = await onValidar(resultado);
|
||||
setValidado(Boolean(isValid));
|
||||
if (isValid) {
|
||||
toast.success("Válido", { duration: 1500 });
|
||||
} else {
|
||||
toast.error("Inválido", { duration: 1500 });
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Erro ao validar:", err);
|
||||
toast.error("Falha na validação. Tente novamente.");
|
||||
setValidado(null);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [onValidar, resultado]);
|
||||
|
||||
const handleCopiar = useCallback(async () => {
|
||||
if (!resultado) return;
|
||||
try {
|
||||
await navigator.clipboard.writeText(resultado);
|
||||
toast.success(`${titulo} copiado!`, { duration: 2000 });
|
||||
} catch (err) {
|
||||
console.error("Erro ao copiar:", err);
|
||||
toast.error("Não foi possível copiar para a área de transferência.");
|
||||
}
|
||||
}, [resultado, titulo]);
|
||||
|
||||
const handleResultadoChange = useCallback((valor: string) => {
|
||||
setResultado(valor);
|
||||
setValidado(null); // reset ao editar
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div
|
||||
className="w-full max-w-md rounded-2xl border border-gray-200 bg-white dark:bg-zinc-900 p-6 shadow-lg hover:shadow-xl transition-shadow duration-300"
|
||||
aria-busy={loading}
|
||||
>
|
||||
<div className="mb-6">
|
||||
<h3 className="text-xl font-bold text-blue-700 dark:text-blue-400">{titulo}</h3>
|
||||
{descricao && <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">{descricao}</p>}
|
||||
</div>
|
||||
|
||||
{parametros.length > 0 && (
|
||||
<div className="space-y-4 mb-6">
|
||||
{parametros.map((param) => {
|
||||
if (param.tipo === "select") {
|
||||
return (
|
||||
<Select
|
||||
key={param.nome}
|
||||
label={param.nome}
|
||||
options={param.options}
|
||||
value={paramInputs[param.nome] ?? ""}
|
||||
onChange={(val) => handleInputChange(param.nome, val)}
|
||||
placeholder={`Selecionar ${param.nome}`}
|
||||
aria-label={param.nome}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Input
|
||||
key={param.nome}
|
||||
type={param.tipo}
|
||||
placeholder={param.placeholder || param.nome}
|
||||
value={paramInputs[param.nome] ?? ""}
|
||||
onChange={(e) => handleInputChange(param.nome, e.target.value)}
|
||||
aria-label={param.nome}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="mb-6 flex items-center gap-2 relative">
|
||||
<ResultDisplay
|
||||
value={resultado}
|
||||
validated={validado}
|
||||
onChange={handleResultadoChange}
|
||||
aria-label={`${titulo} resultado`}
|
||||
/>
|
||||
|
||||
{resultado && (
|
||||
<Button
|
||||
onClick={handleCopiar}
|
||||
icon={<CopyIcon className="w-4 h-4" />}
|
||||
variant="secondary"
|
||||
className="flex items-center gap-1 px-2 py-1 text-xs h-auto"
|
||||
title="Copiar"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex w-full gap-x-2">
|
||||
<Button
|
||||
onClick={handleGerar}
|
||||
icon={<RefreshCwIcon className="w-4 h-4" />}
|
||||
variant="primary"
|
||||
className="flex-1"
|
||||
title={`Gerar ${titulo}`}
|
||||
disabled={loading}
|
||||
>
|
||||
{loading ? "A gerar..." : "Gerar"}
|
||||
</Button>
|
||||
|
||||
{onValidar && (
|
||||
<Button
|
||||
onClick={handleValidar}
|
||||
variant={validado === true ? "primary" : "danger"}
|
||||
className="flex-1"
|
||||
title={`Validar ${titulo}`}
|
||||
disabled={loading || !resultado}
|
||||
>
|
||||
{loading ? "Verificando..." : "Validar"}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
import GeradorService from "../../../Api/GeradorApi.tsx";
|
||||
import GeradorCard from "../GeradorCard.tsx";
|
||||
|
||||
const GenerateCC = () => {
|
||||
|
||||
const handleGenerateCC = async () => {
|
||||
const cc = await GeradorService.GenerateCC()
|
||||
return cc;
|
||||
};
|
||||
|
||||
const handleValidateCC = async (valor: string) => {
|
||||
// Lógica real de validação
|
||||
//const bol = await GeradorService.ValidateCC(valor);
|
||||
return true;
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="max-w-md mx-auto p-6">
|
||||
<GeradorCard
|
||||
titulo="Cartão Cidadão"
|
||||
onGerar={handleGenerateCC}
|
||||
onValidar={handleValidateCC}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default GenerateCC;
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
import GeradorCard, { type Parametro } from "../GeradorCard";
|
||||
import { EnumToOptions, getEnumKeyByValue } from "../../../library/utils";
|
||||
import { NIFType } from "../../../service/api";
|
||||
import GeradorService from "../../../Api/GeradorApi";
|
||||
|
||||
const NifTypes = EnumToOptions(NIFType).map((opt) => ({
|
||||
label: opt.label,
|
||||
value: opt.value,
|
||||
}));
|
||||
|
||||
const GenerateNIF = () => {
|
||||
const handleGenerateNIF = async (params?: Record<string, string>) => {
|
||||
const tipoSelecionado = params?.["Tipo de NIF"] ?? String(NIFType.PessoaSingular2);
|
||||
const nif = String(await GeradorService.GenerateNIF(tipoSelecionado));
|
||||
return nif;
|
||||
};
|
||||
|
||||
const handleValidateNIF = async (valor: string) => {
|
||||
const bol = Boolean(await GeradorService.ValidateNIF(valor));
|
||||
return bol;
|
||||
};
|
||||
|
||||
const parametros: Parametro[] = [
|
||||
{
|
||||
nome: "Tipo de NIF",
|
||||
tipo: "select",
|
||||
options: NifTypes,
|
||||
default: getEnumKeyByValue(NIFType, NIFType.PessoaSingular2)
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="max-w-md mx-auto p-6">
|
||||
<GeradorCard
|
||||
titulo="NIF"
|
||||
parametros={parametros}
|
||||
onGerar={handleGenerateNIF}
|
||||
onValidar={handleValidateNIF}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default GenerateNIF;
|
||||
@@ -1,28 +0,0 @@
|
||||
import GeradorService from "../../../Api/GeradorApi";
|
||||
import GeradorCard from "../GeradorCard.tsx";
|
||||
|
||||
const GenerateNISS = () => {
|
||||
|
||||
const handleGenerateNISS = async () => {
|
||||
const niss = await GeradorService.GenerateNISS()
|
||||
return niss;
|
||||
};
|
||||
|
||||
const handleValidateNISS = async (valor: string) => {
|
||||
// Lógica real de validação
|
||||
const bol = await GeradorService.ValidateNISS(valor);
|
||||
return bol;
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="max-w-md mx-auto p-6">
|
||||
<GeradorCard
|
||||
titulo="NISS"
|
||||
onGerar={handleGenerateNISS}
|
||||
onValidar={handleValidateNISS}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default GenerateNISS;
|
||||
26
geradoresfe/src/components/LoadState.tsx
Normal file
26
geradoresfe/src/components/LoadState.tsx
Normal file
@@ -0,0 +1,26 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { Loader2, ServerCrashIcon } from "lucide-react";
|
||||
import { useGenerators } from "../lib/useGenerators";
|
||||
|
||||
/** Mostra loading/erro enquanto a lista de geradores não está disponível. */
|
||||
export function LoadState({ children }: { children: ReactNode }) {
|
||||
const { loading, error } = useGenerators();
|
||||
|
||||
if (loading)
|
||||
return (
|
||||
<div className="flex justify-center py-16 text-gray-500">
|
||||
<Loader2 className="h-8 w-8 animate-spin" aria-label="A carregar" />
|
||||
</div>
|
||||
);
|
||||
|
||||
if (error)
|
||||
return (
|
||||
<div className="mx-auto mt-12 flex max-w-md flex-col items-center gap-2 rounded-2xl border border-red-200 bg-red-50 p-6 text-center text-red-800 dark:border-red-900 dark:bg-red-950/50 dark:text-red-200">
|
||||
<ServerCrashIcon className="h-8 w-8" />
|
||||
<p className="font-semibold">Não foi possível carregar os geradores.</p>
|
||||
<p className="text-sm">{error}</p>
|
||||
</div>
|
||||
);
|
||||
|
||||
return <>{children}</>;
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
// components/Logo.tsx
|
||||
import logo from '../assets/Logotipo.png';
|
||||
|
||||
export const Logo = () => (
|
||||
<img src={logo} alt="FactoryId logo" className="h-8 w-8" />
|
||||
);
|
||||
25
geradoresfe/src/components/OptionsForm.tsx
Normal file
25
geradoresfe/src/components/OptionsForm.tsx
Normal file
@@ -0,0 +1,25 @@
|
||||
import type { Generator } from "../lib/api";
|
||||
import { Select } from "./ui/Select";
|
||||
|
||||
type OptionsFormProps = {
|
||||
generator: Generator;
|
||||
values: Record<string, string>;
|
||||
onChange: (key: string, value: string) => void;
|
||||
};
|
||||
|
||||
export function OptionsForm({ generator, values, onChange }: OptionsFormProps) {
|
||||
if (generator.options.length === 0) return null;
|
||||
return (
|
||||
<div className="grid gap-3">
|
||||
{generator.options.map((option) => (
|
||||
<Select
|
||||
key={option.key}
|
||||
label={option.label}
|
||||
options={option.choices}
|
||||
value={values[option.key] ?? option.defaultValue}
|
||||
onChange={(v) => onChange(option.key, v)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
39
geradoresfe/src/components/ValidationResultView.tsx
Normal file
39
geradoresfe/src/components/ValidationResultView.tsx
Normal file
@@ -0,0 +1,39 @@
|
||||
import { AlertTriangleIcon, CheckCircle2Icon, XCircleIcon } from "lucide-react";
|
||||
import type { ValidationResult } from "../lib/api";
|
||||
|
||||
type Props = {
|
||||
result: ValidationResult;
|
||||
title?: string;
|
||||
};
|
||||
|
||||
export function ValidationResultView({ result, title }: Props) {
|
||||
const tone = result.isValid
|
||||
? "border-green-300 bg-green-50 text-green-900 dark:border-green-800 dark:bg-green-950/50 dark:text-green-200"
|
||||
: result.formatMatch
|
||||
? "border-amber-300 bg-amber-50 text-amber-900 dark:border-amber-800 dark:bg-amber-950/50 dark:text-amber-200"
|
||||
: "border-red-300 bg-red-50 text-red-900 dark:border-red-800 dark:bg-red-950/50 dark:text-red-200";
|
||||
|
||||
const Icon = result.isValid ? CheckCircle2Icon : result.formatMatch ? AlertTriangleIcon : XCircleIcon;
|
||||
|
||||
return (
|
||||
<div className={`rounded-xl border p-4 ${tone}`} role="status">
|
||||
<div className="flex items-start gap-3">
|
||||
<Icon className="mt-0.5 h-5 w-5 shrink-0" />
|
||||
<div className="min-w-0 flex-1">
|
||||
{title && <p className="font-semibold">{title}</p>}
|
||||
<p className={title ? "text-sm" : "font-medium"}>{result.message}</p>
|
||||
{result.normalized && (
|
||||
<p className="mt-1 break-all font-mono text-sm opacity-80">{result.normalized}</p>
|
||||
)}
|
||||
{result.details && result.details.length > 0 && (
|
||||
<ul className="mt-2 list-inside list-disc space-y-0.5 text-sm opacity-80">
|
||||
{result.details.map((d) => (
|
||||
<li key={d}>{d}</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
84
geradoresfe/src/components/Validator.tsx
Normal file
84
geradoresfe/src/components/Validator.tsx
Normal file
@@ -0,0 +1,84 @@
|
||||
import { useState, type FormEvent } from "react";
|
||||
import { Link } from "react-router";
|
||||
import { SearchCheckIcon } from "lucide-react";
|
||||
import { api, type DetectMatch } from "../lib/api";
|
||||
import { Button } from "./ui/Button";
|
||||
import { Input } from "./ui/Input";
|
||||
import { ValidationResultView } from "./ValidationResultView";
|
||||
|
||||
/**
|
||||
* Validador livre: o utilizador cola um valor qualquer e a API identifica o tipo
|
||||
* (NIF, IBAN, CC, …) e se é válido, incluindo "quase" correspondências com o dígito errado.
|
||||
*/
|
||||
export function Validator({ autoFocus = false }: { autoFocus?: boolean }) {
|
||||
const [value, setValue] = useState("");
|
||||
const [matches, setMatches] = useState<DetectMatch[] | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const submit = async (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!value.trim()) return;
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
setMatches(await api.detect(value));
|
||||
} catch (err) {
|
||||
setError((err as Error).message);
|
||||
setMatches(null);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const valid = matches?.filter((m) => m.result.isValid) ?? [];
|
||||
const nearMisses = matches?.filter((m) => !m.result.isValid) ?? [];
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<form onSubmit={submit} className="flex flex-col gap-2 sm:flex-row">
|
||||
<Input
|
||||
value={value}
|
||||
onChange={(e) => {
|
||||
setValue(e.target.value);
|
||||
setMatches(null);
|
||||
}}
|
||||
placeholder="Cole um NIF, NISS, CC, IBAN, cartão, matrícula, EAN…"
|
||||
aria-label="Valor a validar"
|
||||
autoFocus={autoFocus}
|
||||
className="py-3 font-mono text-base"
|
||||
/>
|
||||
<Button type="submit" loading={loading} icon={<SearchCheckIcon className="h-4 w-4" />} className="py-3 sm:w-40">
|
||||
Validar
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
{error && <p className="text-sm text-red-600 dark:text-red-400">{error}</p>}
|
||||
|
||||
{matches && matches.length === 0 && (
|
||||
<ValidationResultView
|
||||
result={{ isValid: false, formatMatch: false, message: "Não foi reconhecido como nenhum dos tipos suportados." }}
|
||||
/>
|
||||
)}
|
||||
|
||||
{valid.map((m) => (
|
||||
<ValidationResultView key={m.generatorId} title={m.generatorName} result={m.result} />
|
||||
))}
|
||||
|
||||
{valid.length === 0 && nearMisses.map((m) => (
|
||||
<ValidationResultView key={m.generatorId} title={`Parece um ${m.generatorName}, mas…`} result={m.result} />
|
||||
))}
|
||||
|
||||
{valid.length > 0 && nearMisses.length > 0 && (
|
||||
<p className="text-xs text-gray-500 dark:text-gray-400">
|
||||
Também tem o formato de: {nearMisses.map((m) => (
|
||||
<Link key={m.generatorId} to={`/gerador/${m.generatorId}`} className="mr-2 underline">
|
||||
{m.generatorName}
|
||||
</Link>
|
||||
))}
|
||||
(mas não é válido como tal).
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
18
geradoresfe/src/components/ui/Badge.tsx
Normal file
18
geradoresfe/src/components/ui/Badge.tsx
Normal file
@@ -0,0 +1,18 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
|
||||
const tones = {
|
||||
neutral: "bg-gray-100 text-gray-700 dark:bg-zinc-800 dark:text-gray-300",
|
||||
blue: "bg-blue-50 text-blue-700 dark:bg-blue-950 dark:text-blue-300",
|
||||
green: "bg-green-50 text-green-700 dark:bg-green-950 dark:text-green-300",
|
||||
red: "bg-red-50 text-red-700 dark:bg-red-950 dark:text-red-300",
|
||||
amber: "bg-amber-50 text-amber-700 dark:bg-amber-950 dark:text-amber-300",
|
||||
};
|
||||
|
||||
export function Badge({ tone = "neutral", children, className }: { tone?: keyof typeof tones; children: ReactNode; className?: string }) {
|
||||
return (
|
||||
<span className={twMerge("inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-xs font-medium", tones[tone], className)}>
|
||||
{children}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -1,66 +1,36 @@
|
||||
// components/ui/Button.tsx
|
||||
import type { ReactNode } from "react";
|
||||
import type { ButtonHTMLAttributes, ReactNode } from "react";
|
||||
import { Loader2 } from "lucide-react";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
|
||||
type ButtonProps = React.ButtonHTMLAttributes<HTMLButtonElement> & {
|
||||
icon?: ReactNode;
|
||||
variant?: "primary" | "secondary" | "ghost" | "danger";
|
||||
loading?: boolean;
|
||||
loadingText?: string;
|
||||
fullWidth?: boolean;
|
||||
rounded?: boolean | "md" | "lg" | "xl" | "2xl" | "full";
|
||||
type ButtonProps = ButtonHTMLAttributes<HTMLButtonElement> & {
|
||||
icon?: ReactNode;
|
||||
variant?: "primary" | "secondary" | "ghost" | "danger";
|
||||
loading?: boolean;
|
||||
};
|
||||
|
||||
export function Button({
|
||||
icon,
|
||||
variant = "primary",
|
||||
children,
|
||||
className = "",
|
||||
type = "button",
|
||||
loading = false,
|
||||
loadingText,
|
||||
disabled,
|
||||
fullWidth = false,
|
||||
rounded = "2xl",
|
||||
...rest
|
||||
}: ButtonProps) {
|
||||
const base = twMerge(
|
||||
"inline-flex items-center justify-center gap-2 px-5 py-2.5 font-medium text-sm transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed shadow-sm hover:shadow-md",
|
||||
fullWidth && "w-full",
|
||||
typeof rounded === "string" ? `rounded-${rounded}` : rounded === true ? "rounded-md" : "rounded-2xl"
|
||||
);
|
||||
|
||||
const variants = {
|
||||
primary:
|
||||
"bg-blue-600 text-white hover:bg-blue-700 focus:ring-blue-500 dark:bg-blue-600 dark:hover:bg-blue-500",
|
||||
const variants = {
|
||||
primary: "bg-blue-600 text-white hover:bg-blue-700 focus-visible:ring-blue-500 dark:hover:bg-blue-500",
|
||||
secondary:
|
||||
"bg-zinc-100 text-zinc-900 hover:bg-zinc-200 focus:ring-zinc-400 dark:bg-zinc-700 dark:text-white dark:hover:bg-zinc-600",
|
||||
ghost:
|
||||
"bg-transparent text-zinc-700 hover:bg-zinc-100 focus:ring-zinc-300 dark:text-zinc-200 dark:hover:bg-zinc-800",
|
||||
danger:
|
||||
"bg-red-600 text-white hover:bg-red-700 focus:ring-red-500 dark:bg-red-600 dark:hover:bg-red-500",
|
||||
};
|
||||
"bg-zinc-100 text-zinc-900 hover:bg-zinc-200 focus-visible:ring-zinc-400 dark:bg-zinc-700 dark:text-white dark:hover:bg-zinc-600",
|
||||
ghost: "bg-transparent text-zinc-700 hover:bg-zinc-100 focus-visible:ring-zinc-300 dark:text-zinc-200 dark:hover:bg-zinc-800",
|
||||
danger: "bg-red-600 text-white hover:bg-red-700 focus-visible:ring-red-500 dark:hover:bg-red-500",
|
||||
};
|
||||
|
||||
return (
|
||||
<button
|
||||
type={type}
|
||||
className={twMerge(base, variants[variant], className)}
|
||||
disabled={disabled || loading}
|
||||
aria-busy={loading}
|
||||
{...rest}
|
||||
>
|
||||
{loading ? (
|
||||
<>
|
||||
<Loader2 className="animate-spin w-4 h-4" />
|
||||
{loadingText && <span>{loadingText}</span>}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{icon && <span className="flex items-center">{icon}</span>}
|
||||
{children}
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
export function Button({ icon, variant = "primary", children, className, type = "button", loading = false, disabled, ...rest }: ButtonProps) {
|
||||
return (
|
||||
<button
|
||||
type={type}
|
||||
className={twMerge(
|
||||
"inline-flex items-center justify-center gap-2 rounded-lg px-4 py-2 text-sm font-medium shadow-sm transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 dark:focus-visible:ring-offset-zinc-900",
|
||||
variants[variant],
|
||||
className,
|
||||
)}
|
||||
disabled={disabled || loading}
|
||||
aria-busy={loading}
|
||||
{...rest}
|
||||
>
|
||||
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : icon}
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
import { ReactNode } from "react";
|
||||
|
||||
export function ButtonGroup({ children }: { children: ReactNode }) {
|
||||
return <div className="flex flex-wrap w-full gap-x-2">{children}</div>;
|
||||
}
|
||||
@@ -1,27 +1,17 @@
|
||||
import { SunIcon, MoonIcon } from "@heroicons/react/24/outline";
|
||||
import { MoonIcon, SunIcon } from "lucide-react";
|
||||
import { useTheme } from "../../context/ThemeContext";
|
||||
|
||||
export function DarkModeToggle() {
|
||||
const { theme, toggleTheme } = useTheme();
|
||||
|
||||
const handleToggle = () => {
|
||||
console.log("Toggle clicado, tema antes:", theme);
|
||||
toggleTheme();
|
||||
};
|
||||
|
||||
console.log("Render DarkModeToggle, theme =", theme);
|
||||
|
||||
return (
|
||||
<button
|
||||
onClick={handleToggle}
|
||||
className="p-2 text-gray-700 hover:text-blue-500 dark:text-gray-300"
|
||||
aria-label="Alternar modo escuro"
|
||||
type="button"
|
||||
onClick={toggleTheme}
|
||||
className="rounded-md p-2 text-gray-700 hover:text-blue-600 dark:text-gray-300 dark:hover:text-blue-400"
|
||||
aria-label={theme === "dark" ? "Mudar para tema claro" : "Mudar para tema escuro"}
|
||||
>
|
||||
{theme === "dark" ? (
|
||||
<SunIcon className="w-6 h-6" />
|
||||
) : (
|
||||
<MoonIcon className="w-6 h-6" />
|
||||
)}
|
||||
{theme === "dark" ? <SunIcon className="h-5 w-5" /> : <MoonIcon className="h-5 w-5" />}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
import React from "react";
|
||||
import type { InputHTMLAttributes } from "react";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
|
||||
type InputProps = React.InputHTMLAttributes<HTMLInputElement>;
|
||||
type InputProps = InputHTMLAttributes<HTMLInputElement>;
|
||||
|
||||
export function Input({ className = "", ...props }: InputProps) {
|
||||
export function Input({ className, ...props }: InputProps) {
|
||||
return (
|
||||
<input
|
||||
className={
|
||||
"w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 " +
|
||||
className
|
||||
}
|
||||
className={twMerge(
|
||||
"w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900 placeholder:text-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500 dark:border-zinc-600 dark:bg-zinc-800 dark:text-gray-100",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -1,31 +1,27 @@
|
||||
import { CheckIcon, XIcon } from "lucide-react";
|
||||
import { CopyIcon } from "lucide-react";
|
||||
import { copyToClipboard } from "../../lib/clipboard";
|
||||
|
||||
type ResultDisplayProps = {
|
||||
value: string;
|
||||
validated: boolean | null;
|
||||
onChange?: (value: string) => void;
|
||||
label: string;
|
||||
};
|
||||
|
||||
export function ResultDisplay({ value, validated, onChange }: ResultDisplayProps) {
|
||||
const baseClasses = "flex items-center gap-2 px-3 py-2 border rounded-md text-sm w-full";
|
||||
const colors =
|
||||
validated === true
|
||||
? "border-green-500 text-green-700 bg-green-50 dark:text-green-400 dark:bg-green-950 dark:border-green-700"
|
||||
: validated === false
|
||||
? "border-red-500 text-red-700 bg-red-50 dark:text-red-400 dark:bg-red-950 dark:border-red-700"
|
||||
: "border-gray-300 text-gray-700 bg-gray-100 dark:text-gray-300 dark:bg-zinc-800 dark:border-gray-600";
|
||||
|
||||
export function ResultDisplay({ value, label }: ResultDisplayProps) {
|
||||
return (
|
||||
<div className={baseClasses + " " + colors}>
|
||||
<input
|
||||
type="text"
|
||||
readOnly={!onChange}
|
||||
value={value}
|
||||
onChange={(e) => onChange?.(e.target.value)}
|
||||
className="flex-1 bg-transparent outline-none font-mono truncate"
|
||||
/>
|
||||
{validated === true && <CheckIcon className="w-5 h-5" />}
|
||||
{validated === false && <XIcon className="w-5 h-5" />}
|
||||
<div className="flex items-center gap-2 rounded-lg border border-gray-300 bg-gray-50 px-3 py-2 dark:border-zinc-600 dark:bg-zinc-800">
|
||||
<output aria-label={`${label} gerado`} className="min-h-5 flex-1 truncate font-mono text-sm text-gray-900 dark:text-gray-100">
|
||||
{value || <span className="text-gray-400">—</span>}
|
||||
</output>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => copyToClipboard(value, label)}
|
||||
disabled={!value}
|
||||
className="rounded p-1 text-gray-500 hover:bg-gray-200 hover:text-blue-600 disabled:opacity-30 dark:hover:bg-zinc-700"
|
||||
title="Copiar"
|
||||
aria-label="Copiar"
|
||||
>
|
||||
<CopyIcon className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,35 +1,35 @@
|
||||
// components/ui/Select.tsx
|
||||
import React from "react";
|
||||
import { useId } from "react";
|
||||
|
||||
interface Option {
|
||||
label: string;
|
||||
value: string;
|
||||
}
|
||||
type Option = { label: string; value: string };
|
||||
|
||||
interface SelectProps {
|
||||
label?: string;
|
||||
options: Option[];
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
placeholder?: string;
|
||||
}
|
||||
|
||||
export const Select = ({ label, options, value, onChange, placeholder }: SelectProps) => {
|
||||
return (
|
||||
<div className="flex flex-col">
|
||||
{label && <label className="mb-1 font-medium text-gray-700 dark:text-gray-300">{label}</label>}
|
||||
<select
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
className="border border-gray-300 rounded-md px-3 py-2 bg-white dark:bg-zinc-800 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-blue-500 transition"
|
||||
>
|
||||
<option value="" disabled>{placeholder || "Selecionar..."}</option>
|
||||
{options.map((opt) => (
|
||||
<option key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
);
|
||||
type SelectProps = {
|
||||
label?: string;
|
||||
options: Option[];
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
};
|
||||
|
||||
export function Select({ label, options, value, onChange }: SelectProps) {
|
||||
const id = useId();
|
||||
return (
|
||||
<div className="flex flex-col gap-1">
|
||||
{label && (
|
||||
<label htmlFor={id} className="text-sm font-medium text-gray-700 dark:text-gray-300">
|
||||
{label}
|
||||
</label>
|
||||
)}
|
||||
<select
|
||||
id={id}
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
className="rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900 transition focus:outline-none focus:ring-2 focus:ring-blue-500 dark:border-zinc-600 dark:bg-zinc-800 dark:text-gray-100"
|
||||
>
|
||||
{options.map((opt) => (
|
||||
<option key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user