@@ -1,17 +1,19 @@
|
||||
import type { HTMLAttributes } from 'react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { useTempoUi } from '@/components/tempo-brand';
|
||||
|
||||
export default function InputError({
|
||||
message,
|
||||
className = '',
|
||||
...props
|
||||
}: HTMLAttributes<HTMLParagraphElement> & { message?: string }) {
|
||||
const { t } = useTempoUi();
|
||||
return message ? (
|
||||
<p
|
||||
{...props}
|
||||
className={cn('text-sm text-red-600 dark:text-red-400', className)}
|
||||
>
|
||||
{message}
|
||||
{t(message)}
|
||||
</p>
|
||||
) : null;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,54 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useTempoUi } from '@/components/tempo-brand';
|
||||
import { translateText } from '@/translation/service';
|
||||
import { protectTranslationTokens, restoreTranslationTokens } from '@/translation/utils';
|
||||
|
||||
// Bridge the original Trans calls to this platform's existing language context.
|
||||
export function Trans({ children }: { children: string }) {
|
||||
const { t } = useTempoUi();
|
||||
return <span>{t(children)}</span>;
|
||||
// Only the fixed public institutional texts using this component are sent to Tempo.
|
||||
const cache = new Map<string, string>();
|
||||
const pending = new Map<string, Promise<string>>();
|
||||
|
||||
function translateInstitutionalText(text: string, language: string): Promise<string> {
|
||||
const key = JSON.stringify([language, text]);
|
||||
const cached = cache.get(key);
|
||||
if (cached) return Promise.resolve(cached);
|
||||
const existing = pending.get(key);
|
||||
if (existing) return existing;
|
||||
|
||||
const protectedText = protectTranslationTokens(text);
|
||||
const request = translateText({
|
||||
text: protectedText.text,
|
||||
sourceLanguage: 'pt',
|
||||
targetLanguage: language,
|
||||
}).then(({ translatedText }) => {
|
||||
// Do not accept a response that lost an identifier, URL or protected term.
|
||||
for (const token of protectedText.replacements.keys()) {
|
||||
if (!translatedText.includes(token)) throw new Error('Translation lost a protected token');
|
||||
}
|
||||
const result = restoreTranslationTokens(translatedText, protectedText.replacements);
|
||||
// Tempo's API returns the input on upstream failure: do not cache it as success.
|
||||
if (result !== text) cache.set(key, result);
|
||||
return result;
|
||||
}).finally(() => pending.delete(key));
|
||||
pending.set(key, request);
|
||||
return request;
|
||||
}
|
||||
|
||||
export function Trans({ children }: { children: string }) {
|
||||
const { language, t } = useTempoUi();
|
||||
const localText = t(children);
|
||||
const [result, setResult] = useState<{ key: string; text: string } | null>(null);
|
||||
const key = JSON.stringify([language, children]);
|
||||
|
||||
useEffect(() => {
|
||||
if (language === 'pt' || localText !== children || !children.trim()) return;
|
||||
let active = true;
|
||||
translateInstitutionalText(children, language).then((text) => {
|
||||
if (active) setResult({ key, text });
|
||||
}).catch(() => {
|
||||
if (active) setResult(null);
|
||||
});
|
||||
return () => { active = false; };
|
||||
}, [children, key, language, localText]);
|
||||
|
||||
return <span data-no-translate>{result?.key === key ? result.text : localText}</span>;
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { ComponentProps, Ref } from 'react';
|
||||
import { useState } from 'react';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { useTempoUi } from '@/components/tempo-brand';
|
||||
|
||||
export default function PasswordInput({
|
||||
className,
|
||||
@@ -10,6 +11,7 @@ export default function PasswordInput({
|
||||
...props
|
||||
}: Omit<ComponentProps<'input'>, 'type'> & { ref?: Ref<HTMLInputElement> }) {
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
const { t } = useTempoUi();
|
||||
|
||||
return (
|
||||
<div className="relative">
|
||||
@@ -23,11 +25,7 @@ export default function PasswordInput({
|
||||
type="button"
|
||||
onClick={() => setShowPassword((prev) => !prev)}
|
||||
className="text-muted-foreground hover:text-foreground focus-visible:ring-ring absolute inset-y-0 right-0 flex items-center rounded-r-md px-3 focus-visible:ring-[3px] focus-visible:outline-none"
|
||||
aria-label={
|
||||
showPassword
|
||||
? 'Ocultar palavra-passe'
|
||||
: 'Mostrar palavra-passe'
|
||||
}
|
||||
aria-label={showPassword ? 'Ocultar palavra-passe' : 'Mostrar palavra-passe'}
|
||||
tabIndex={-1}
|
||||
>
|
||||
{showPassword ? (
|
||||
|
||||
@@ -226,14 +226,14 @@ export default function PortalHero({
|
||||
</p>
|
||||
|
||||
<form
|
||||
action="/oportunidades"
|
||||
action="/pesquisa"
|
||||
method="get"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
const value = new FormData(event.currentTarget).get(
|
||||
'q',
|
||||
);
|
||||
router.get('/oportunidades', {
|
||||
router.get('/pesquisa', {
|
||||
q:
|
||||
typeof value === 'string'
|
||||
? value.trim()
|
||||
@@ -241,14 +241,14 @@ export default function PortalHero({
|
||||
});
|
||||
}}
|
||||
role="search"
|
||||
aria-label="Pesquisar oportunidades"
|
||||
aria-label="Pesquisar no InvesteMoz"
|
||||
className="mt-7 w-full max-w-4xl"
|
||||
>
|
||||
<label
|
||||
htmlFor="portal-opportunity-search"
|
||||
className="mb-2 block text-left text-sm font-medium text-white/90"
|
||||
>
|
||||
Pesquisa rápida de oportunidades
|
||||
Pesquisa rápida no InvesteMoz
|
||||
</label>
|
||||
<div className="flex min-w-0 flex-col gap-2 rounded-2xl border border-white/30 bg-white p-1.5 shadow-2xl shadow-black/20 focus-within:ring-2 focus-within:ring-white focus-within:ring-offset-4 focus-within:ring-offset-[#101820] min-[400px]:flex-row">
|
||||
<input
|
||||
@@ -259,7 +259,7 @@ export default function PortalHero({
|
||||
aria-describedby="portal-opportunity-search-help"
|
||||
value={query}
|
||||
onChange={(event) => setQuery(event.target.value)}
|
||||
placeholder="Ex.: agronegócio, Nampula, energia..."
|
||||
placeholder="Ex.: agronegócio, Nampula, legislação..."
|
||||
className="h-12 w-full min-w-0 flex-1 rounded-xl border-0 bg-white px-4 text-base text-slate-900 outline-none placeholder:text-slate-500"
|
||||
/>
|
||||
<button
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
import { createContext, useContext } from 'react';
|
||||
import { PortalGroupedMenu } from '@/components/portal-grouped-menu';
|
||||
|
||||
export const MenuPlacement = createContext(false);
|
||||
|
||||
export function PortalMenu({ primary = false }: { primary?: boolean }) {
|
||||
const placed = useContext(MenuPlacement);
|
||||
return placed && !primary ? null : <PortalGroupedMenu />;
|
||||
}
|
||||
@@ -241,6 +241,48 @@ const translations: Record<string, Record<string, string>> = {
|
||||
},
|
||||
};
|
||||
|
||||
const sharedTranslations: Record<string, [string, string, string]> = {
|
||||
'Criar conta': ['Create account', 'Créer un compte', 'Crear cuenta'],
|
||||
'Entrar na sua conta': ['Sign in to your account', 'Connectez-vous à votre compte', 'Inicie sesión en su cuenta'],
|
||||
'Crie uma conta simples para continuar e acompanhar a sua operação. Não é necessário configurar MFA para participar.': ['Create an account to continue and follow your operation. You do not need to set up MFA to participate.', 'Créez un compte pour poursuivre et suivre votre opération. La configuration de l’authentification multifacteur n’est pas nécessaire pour participer.', 'Cree una cuenta para continuar y seguir su operación. No necesita configurar la autenticación multifactor para participar.'],
|
||||
'Entre para continuar a operação que escolheu. Os dados preenchidos permanecem guardados neste navegador.': ['Sign in to continue the operation you chose. Your entered data remains saved in this browser.', 'Connectez-vous pour poursuivre l’opération choisie. Les données saisies restent enregistrées dans ce navigateur.', 'Inicie sesión para continuar la operación elegida. Los datos introducidos permanecen guardados en este navegador.'],
|
||||
'Palavra-passe': ['Password', 'Mot de passe', 'Contraseña'],
|
||||
'Mostrar palavra-passe': ['Show password', 'Afficher le mot de passe', 'Mostrar contraseña'],
|
||||
'Ocultar palavra-passe': ['Hide password', 'Masquer le mot de passe', 'Ocultar contraseña'],
|
||||
'Confirmar palavra-passe': ['Confirm password', 'Confirmer le mot de passe', 'Confirmar contraseña'],
|
||||
'Nome': ['Name', 'Nom', 'Nombre'],
|
||||
'Nome completo': ['Full name', 'Nom complet', 'Nombre completo'],
|
||||
'Esqueceu a palavra-passe?': ['Forgot your password?', 'Mot de passe oublié ?', '¿Olvidó su contraseña?'],
|
||||
'Manter sessão iniciada': ['Keep me signed in', 'Rester connecté', 'Mantener la sesión iniciada'],
|
||||
'Ainda não tem conta?': ['Don’t have an account?', 'Vous n’avez pas de compte ?', '¿Aún no tiene cuenta?'],
|
||||
'Já tem conta?': ['Already have an account?', 'Vous avez déjà un compte ?', '¿Ya tiene cuenta?'],
|
||||
'Entrar com chave de acesso': ['Sign in with a passkey', 'Se connecter avec une clé d’accès', 'Iniciar sesión con clave de acceso'],
|
||||
'A autenticar…': ['Signing in…', 'Connexion en cours…', 'Iniciando sesión…'],
|
||||
'Ou continuar com email': ['Or continue with email', 'Ou continuer avec l’e-mail', 'O continuar con correo electrónico'],
|
||||
'O email ou a palavra-passe não correspondem aos nossos registos.': ['The email or password does not match our records.', 'L’adresse e-mail ou le mot de passe ne correspond pas à nos informations.', 'El correo electrónico o la contraseña no coinciden con nuestros registros.'],
|
||||
'A palavra-passe está incorrecta.': ['The password is incorrect.', 'Le mot de passe est incorrect.', 'La contraseña es incorrecta.'],
|
||||
'Atalho para o conteúdo': ['Skip link', 'Lien d’accès rapide', 'Enlace de acceso rápido'],
|
||||
'Saltar para o conteúdo': ['Skip to content', 'Aller au contenu', 'Ir al contenido'],
|
||||
'Caminho de navegação': ['Breadcrumb', 'Fil d’Ariane', 'Ruta de navegación'],
|
||||
'Contacto de apoio ao investidor': ['Investor support contact', 'Contact de l’assistance aux investisseurs', 'Contacto de apoyo al inversor'],
|
||||
'Contactar Apoio ao Investidor': ['Contact investor support', 'Contacter l’assistance aux investisseurs', 'Contactar con apoyo al inversor'],
|
||||
'Ambiente de homologação': ['Review environment', 'Environnement de validation', 'Entorno de validación'],
|
||||
'Homologação reservada à revisão da Tempo. Consulte o conteúdo público; entre na sua conta quando iniciar uma operação.': ['This review environment is reserved for Tempo. Browse public content; sign in when starting an operation.', 'Cet environnement de validation est réservé à Tempo. Consultez le contenu public ; connectez-vous pour commencer une opération.', 'Este entorno de validación está reservado para Tempo. Consulte el contenido público; inicie sesión al comenzar una operación.'],
|
||||
'Idioma da navegação': ['Navigation language', 'Langue de navigation', 'Idioma de navegación'],
|
||||
'Navegação institucional': ['Language', 'Langue', 'Idioma'],
|
||||
'Valores': ['Values', 'Valeurs', 'Valores'],
|
||||
'Ver menos': ['Show less', 'Voir moins', 'Ver menos'],
|
||||
'Ver mais': ['Show more', 'Voir plus', 'Ver más'],
|
||||
'Voltar': ['Back', 'Retour', 'Volver'],
|
||||
'Anos de Experiência': ['Years of experience', 'Années d’expérience', 'Años de experiencia'],
|
||||
'Projetos Realizados': ['Projects completed', 'Projets réalisés', 'Proyectos realizados'],
|
||||
};
|
||||
for (const [source, values] of Object.entries(sharedTranslations)) {
|
||||
(['en', 'fr', 'es'] as const).forEach((locale, index) => {
|
||||
translations[locale][source] = values[index];
|
||||
});
|
||||
}
|
||||
|
||||
const TempoUi = createContext({
|
||||
language: 'pt',
|
||||
setLanguage: (_language: string) => {},
|
||||
@@ -255,13 +297,17 @@ export function TempoUiProvider({ children }: { children: ReactNode }) {
|
||||
useEffect(() => {
|
||||
try {
|
||||
const saved = localStorage.getItem('tempo-navigation-language');
|
||||
if (saved && ['pt', 'en', 'fr', 'es'].includes(saved))
|
||||
if (saved && /^[a-zA-Z][a-zA-Z0-9-]{0,19}$/.test(saved))
|
||||
setCurrentLanguage(saved);
|
||||
} catch {
|
||||
/* Navigation remains usable without browser storage. */
|
||||
}
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
document.documentElement.lang = language;
|
||||
}, [language]);
|
||||
const setLanguage = (next: string) => {
|
||||
if (!/^[a-zA-Z][a-zA-Z0-9-]{0,19}$/.test(next)) return;
|
||||
setCurrentLanguage(next);
|
||||
try {
|
||||
localStorage.setItem('tempo-navigation-language', next);
|
||||
|
||||
@@ -8,6 +8,9 @@ import {
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import { useTempoUi } from '@/components/tempo-brand';
|
||||
import { getLanguages } from '@/translation/service';
|
||||
import { withPortugueseFirst } from '@/translation/utils';
|
||||
import type { TranslationLanguage } from '@/translation/types';
|
||||
|
||||
type Weather = { temp: number; description: string; humidity?: number };
|
||||
|
||||
@@ -97,12 +100,28 @@ export function TempoWeather() {
|
||||
}
|
||||
|
||||
export function TempoLanguageSelector() {
|
||||
const { language, setLanguage } = useTempoUi();
|
||||
const { language, setLanguage, t } = useTempoUi();
|
||||
const [languages, setLanguages] = useState<TranslationLanguage[]>([
|
||||
{ code: 'pt', name: 'Português' },
|
||||
{ code: 'en', name: 'English' },
|
||||
{ code: 'fr', name: 'Français' },
|
||||
{ code: 'es', name: 'Español' },
|
||||
]);
|
||||
const [available, setAvailable] = useState(true);
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
getLanguages(controller.signal).then((items) => {
|
||||
const portuguese = items.find((item) => item.code === 'pt');
|
||||
if (!portuguese) throw new Error('Portuguese model unavailable');
|
||||
setLanguages(withPortugueseFirst(items.filter((item) => item.code === 'pt' || !portuguese.targets || portuguese.targets.includes(item.code))));
|
||||
}).catch(() => { if (!controller.signal.aborted) setAvailable(false); });
|
||||
return () => controller.abort();
|
||||
}, []);
|
||||
return (
|
||||
<DropdownMenu modal={false}>
|
||||
<DropdownMenuTrigger
|
||||
className="tempo-utility-button"
|
||||
aria-label="Idioma da navegação"
|
||||
aria-label={t('Idioma da navegação')}
|
||||
>
|
||||
<Globe size={16} aria-hidden="true" />
|
||||
<span className="text-xs font-semibold uppercase">
|
||||
@@ -116,14 +135,10 @@ export function TempoLanguageSelector() {
|
||||
className="tempo-dropdown min-w-44"
|
||||
>
|
||||
<DropdownMenuLabel className="text-xs text-slate-500">
|
||||
Navegação institucional
|
||||
{t('Navegação institucional')}
|
||||
</DropdownMenuLabel>
|
||||
{[
|
||||
['pt', 'Português'],
|
||||
['en', 'English'],
|
||||
['fr', 'Français'],
|
||||
['es', 'Español'],
|
||||
].map(([code, name]) => (
|
||||
{!available && <DropdownMenuLabel className="text-xs text-slate-500">Tradução temporariamente indisponível</DropdownMenuLabel>}
|
||||
{languages.map(({ code, name }) => (
|
||||
<DropdownMenuItem
|
||||
key={code}
|
||||
onSelect={() => setLanguage(code)}
|
||||
|
||||
Reference in New Issue
Block a user