Skip to content

Commit

Permalink
feat: update pt.json and create internationalization controller
Browse files Browse the repository at this point in the history
  • Loading branch information
gabriel-logan committed May 29, 2024
1 parent 425c4d1 commit a2fce77
Show file tree
Hide file tree
Showing 7 changed files with 105 additions and 10 deletions.
56 changes: 56 additions & 0 deletions docs/compareLangs.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
/* eslint-disable no-console */
const sourceFile = "en";
const targetFile = "pt";

const srcFile = require(`./src/locales/${sourceFile}/${sourceFile}.json`);
const tgtFile = require(`./src/locales/${targetFile}/${targetFile}.json`);

// rest of the code...

function findMissingTranslations(sourceMap, targetMap, prefix = "") {
let missingKeys = [];

Object.keys(sourceMap).forEach((key) => {
if (typeof sourceMap[key] === "object") {
missingKeys = [
...missingKeys,
...findMissingTranslations(
sourceMap[key],
targetMap[key] || {},
`${prefix}${key}.`,
),
];
} else if (!(key in (targetMap || {}))) {
missingKeys.push(`${prefix}${key}`);
}
});

return missingKeys;
}

const missingTranslations = findMissingTranslations(srcFile, tgtFile);

console.log(
missingTranslations.length
? missingTranslations
: ` No missing translations between "${sourceFile}" lang and "${targetFile}" lang`,
);

// The script will output the missing translations in the console.
// If there are no missing translations, the output will be an empty array.

/**
* [
'HomeLayout.Opengraph title',
'HomeLayout.Opengraph description',
'About.About_Page',
'About.About_Page_Description',
'Info.Info_Page',
'PrivacyPolices.Privacy Policy',
'Terms.Terms and Conditions of Multiform Validator library',
'DocumentationJsFunctions.Import',
'DocumentationJsFunctions.require',
'DocumentationJsFunctions.(optional boolean) - If set to',
'DocumentationJsFunctions.trim()'
]
*/
1 change: 1 addition & 0 deletions docs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
},
"dependencies": {
"next": "14.2.3",
"next-international": "^1.2.4",
"react": "^18",
"react-dom": "^18",
"react-icons": "^5.2.0",
Expand Down
8 changes: 8 additions & 0 deletions docs/src/locales/client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// locales/client.ts
"use client";
import { createI18nClient } from "next-international/client";

export const { useI18n, useScopedI18n, I18nProviderClient } = createI18nClient({
en: () => import("./en/en.json"),
pt: () => import("./pt/pt.json"),
});
3 changes: 0 additions & 3 deletions docs/src/locales/en/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,6 @@
"function is used to validate a Brazilian CNPJ (National Registry of Legal Entities) number. It returns an object containing the": "function is used to validate a Brazilian CNPJ (National Registry of Legal Entities) number. It returns an object containing the",
"and": "and",
"properties, indicating whether the CNPJ is valid and, in case of an error, the corresponding error message.": "properties, indicating whether the CNPJ is valid and, in case of an error, the corresponding error message.",
"Import": "Import",
"The function can be imported using ES6 syntax from the \"multiform-validator\" package:": "The function can be imported using ES6 syntax from the \"multiform-validator\" package:",
"Parameters": "Parameters",
"The function takes two parameters:": "The function takes two parameters:",
Expand All @@ -161,7 +160,6 @@
"properties, indicating whether the CPF is valid and, in case of an error, the corresponding error message.": "properties, indicating whether the CPF is valid and, in case of an error, the corresponding error message.",
"There are two ways to import the function:": "There are two ways to import the function:",
"Using": "Using",
"require": "require",
"The CPF number to be validated.": "The CPF number to be validated.",
"function extracts email addresses from a given text. If the optional": "function extracts email addresses from a given text. If the optional",
"parameter is set to": "parameter is set to",
Expand Down Expand Up @@ -225,7 +223,6 @@
"if the input string is empty or consists of only whitespace characters, and": "if the input string is empty or consists of only whitespace characters, and",
"The input string to check if it is empty or contains only whitespace characters.": "The input string to check if it is empty or contains only whitespace characters.",
"The function expects the input value to be passed as a string. If the input is not a string, the function throws a TypeError. It removes any leading and trailing whitespace from the input string using the.": "The function expects the input value to be passed as a string. If the input is not a string, the function throws a TypeError. It removes any leading and trailing whitespace from the input string using the.",
"trim()": "trim()",
"method and checks if the resulting string is empty (i.e., has a length of 0). If the input string consists of only whitespace characters, the function also returns.": "method and checks if the resulting string is empty (i.e., has a length of 0). If the input string consists of only whitespace characters, the function also returns.",
"as it considers such strings to be empty.": "as it considers such strings to be empty.",

Expand Down
19 changes: 13 additions & 6 deletions docs/src/locales/pt/pt.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,16 @@
"HelpMsg": "Você também pode ajudar o programador comprando um café no link abaixo, desde já agradeço (:"
},
"HomeLayout": {
"Title": "Validador Multiform",
"Description": "Biblioteca multilíngue feita para validação de vários campos de formulário, como: email, telefone, senha, CPF, CNPJ, cartão de crédito, números mágicos para validação de tipo MIME de imagem e muito mais.",
"Classification": "Biblioteca de Validação",
"Support me on Buy me a coffee": "Apoie-me no Buy me a coffee!"
"Title": "Multiform Validator",
"Opengraph title": "Multiform Validator - Sua Biblioteca de Validação Multilíngue",
"Opengraph description": "Biblioteca multilíngue feita para validação de vários campos de formulário, como: email, imagem, CPF, CNPJ, cartão de crédito, números mágicos e muito mais.",
"Description": "Biblioteca multilíngue feita para validação de vários campos de formulário, como: email, telefone, senha, CPF, CNPJ, cartão de crédito, números mágicos para validação de mimetype de imagem e muito mais.",
"Classification": "Biblioteca de Validação",
"Support me on Buy me a coffee": "Apoie-me no Buy me a coffee!"
},
"About": {
"About_Page": "Página Sobre",
"About_Page_Description": "Conheça Gabriel Logan, o criador da biblioteca multiform-validator, e saiba mais sobre sua paixão pelo desenvolvimento web, soluções inovadoras e dedicação à experiência do usuário.",
"about_title": "Olá, eu sou Gabriel Logan",
"about_intro": "Me considero um programador versátil com paixão tanto pelo desenvolvimento front-end quanto pelo back-end. Criar experiências web excepcionais é o que me motiva, e tenho muito orgulho do trabalho que produzo.",
"about_frontend": "Como desenvolvedor front-end, tenho um olhar atento para a experiência do usuário e o design de interface. Adoro transformar conceitos criativos em aplicativos web visualmente cativantes e interativos usando HTML, CSS e JavaScript. Da navegação perfeita às animações suaves, presto atenção em cada detalhe para garantir que meus projetos front-end exibam elegância e funcionalidade.",
Expand All @@ -46,6 +50,7 @@
"about_conclusion": "Em conclusão, sou Gabriel Logan, um programador apaixonado que mescla habilidades front-end e back-end para criar experiências web excepcionais. Minha mentalidade inovadora, atenção aos detalhes e dedicação à eficiência me levaram a desenvolver uma página inovadora que acredito que terá um impacto significativo no mundo da validação de formulários. À medida que o cenário digital continua a evoluir, estou na vanguarda, pronto para abraçar novos desafios e fazer a diferença por meio do meu trabalho excepcional em desenvolvimento web."
},
"Info": {
"Info_Page": "Página de Informações",
"info_title": "multiform-validator - Biblioteca Multi para Validação de Campos de Formulário",
"info_intro": "Apresentando multiform-validator, uma poderosa Biblioteca Multi desenvolvida por Gabriel Logan. Esta biblioteca versátil é projetada para validar inúmeros campos de formulário, incluindo endereços de e-mail, números de telefone, senhas, CPF (Cadastro de Pessoa Física), números de cartão de crédito e muito mais.",
"info_ensure": "Com o multiform-validator, você pode garantir que os dados enviados por meio de seus formulários sejam precisos e seguros. Esteja você criando um formulário de registro, processo de checkout ou qualquer sistema de entrada de dados, esta biblioteca tem tudo o que você precisa.",
Expand All @@ -56,6 +61,7 @@
"info_conclusion": "Portanto, se você está procurando uma solução abrangente para validação de campos de formulário, não procure mais do que o multiform-validator. Aproveite o poder desta biblioteca e tenha a certeza de que seu processo de coleta de dados será simplificado, preciso e seguro."
},
"PrivacyPolices": {
"Privacy Policy": "Política de Privacidade",
"privacy_title": "Políticas de Privacidade - Seus Dados Estão Seguros Conosco",
"privacy_intro": "Levamos sua privacidade a sério. Queremos assegurar que não coletamos nenhum dado em nosso site, e não utilizamos nenhum dado através da biblioteca \"multiform-validator\". Suas informações permanecem totalmente confidenciais, e sua privacidade é primordial para nós.",
"privacy_no_personal_data": "Ao visitar nosso site, fique tranquilo que nenhum dado pessoal, como seu nome, endereço de e-mail ou informações de contato, é coletado ou armazenado. Acreditamos em fornecer uma experiência de navegação segura e anônima para você.",
Expand All @@ -73,7 +79,8 @@
"We do not collect any personal data through this website, and your privacy is important to us.": "Não coletamos nenhum dado pessoal por meio deste site, e sua privacidade é importante para nós.",
"Unauthorized use of this website is strictly prohibited.": "O uso não autorizado deste site é estritamente proibido.",
"Your use of this website and any disputes arising are subject to the laws of [Your Country/Region].": "Seu uso deste site e quaisquer disputas que surgirem estão sujeitos às leis de [Seu País/Região].",
"Thank you for visiting our website and using our services. If you have any questions or concerns, please don’t hesitate to contact us.": "Obrigado por visitar nosso site e usar nossos serviços. Se você tiver alguma dúvida ou preocupação, não hesite em nos contatar."
"Thank you for visiting our website and using our services. If you have any questions or concerns, please don’t hesitate to contact us.": "Obrigado por visitar nosso site e usar nossos serviços. Se você tiver alguma dúvida ou preocupação, não hesite em nos contatar.",
"Terms and Conditions of Multiform Validator library": "Termos e Condições da biblioteca Multiform Validator"
},
"Manifest": {
"Name": "Multiform Validator - Sua Biblioteca de Validação Multilíngue",
Expand Down Expand Up @@ -165,7 +172,7 @@
"(optional boolean | string[]) - Either a boolean value indicating whether to clean after default domains or an array of custom domains to clean after. Default is": "(booleano opcional | string[]) - Um valor booleano indicando se deve limpar após domínios padrão ou uma matriz de domínios personalizados para limpar após. O padrão é",
"which means it won't clean the email addresses after default domains ['.br', '.io', '.pt', '.us', '.org', '.com'];. If set to": "o que significa que não limpará os endereços de e-mail após os domínios padrão ['.br', '.io', '.pt', '.us', '.org', '.com'];. Se definido como",
"it will clean after default domains. If set to an array of strings, it will clean after the specified custom domains.": "ele limpará após os domínios padrão. Se definido como uma matriz de strings, ele limpará após os domínios personalizados especificados.",
"(booleano opcional) - Se definido como": "(booleano opcional) - Se definido como",
"(optional boolean) - If set to": "(booleano opcional) - Se definido como",
"the function will remove duplicate emails from the output list. If set to": "a função removerá e-mails duplicados da lista de saída. Se definido como",
"or not provided, it will keep the duplicate emails in the output list.": "ou não fornecido, ele manterá os e-mails duplicados na lista de saída.",
"If no email address is found in the input text, the function will return the string 'No email found'.": "Se nenhum endereço de e-mail for encontrado no texto de entrada, a função retornará a string 'Nenhum e-mail encontrado'.",
Expand Down
7 changes: 7 additions & 0 deletions docs/src/locales/server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
// locales/server.ts
import { createI18nServer } from "next-international/server";

export const { getI18n, getScopedI18n, getStaticParams } = createI18nServer({
en: () => import("./en/en.json"),
pt: () => import("./pt/pt.json"),
});
21 changes: 20 additions & 1 deletion docs/yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -716,7 +716,7 @@ chokidar@^3.5.3:
optionalDependencies:
fsevents "~2.3.2"

client-only@0.0.1:
client-only@0.0.1, client-only@^0.0.1:
version "0.0.1"
resolved "https://registry.yarnpkg.com/client-only/-/client-only-0.0.1.tgz#38bba5d403c41ab150bff64a95c85013cf73bca1"
integrity sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==
Expand Down Expand Up @@ -1635,6 +1635,11 @@ internal-slot@^1.0.7:
hasown "^2.0.0"
side-channel "^1.0.4"

international-types@^0.8.1:
version "0.8.1"
resolved "https://registry.yarnpkg.com/international-types/-/international-types-0.8.1.tgz#c0e593d9911c1a23f64bbd6eb1abb2941fe2353f"
integrity sha512-tajBCAHo4I0LIFlmQ9ZWfjMWVyRffzuvfbXCd6ssFt5u1Zw15DN0UBpVTItXdNa1ls+cpQt3Yw8+TxsfGF8JcA==

is-alphabetical@^1.0.0:
version "1.0.4"
resolved "https://registry.yarnpkg.com/is-alphabetical/-/is-alphabetical-1.0.4.tgz#9e7d6b94916be22153745d184c298cbf986a686d"
Expand Down Expand Up @@ -2073,6 +2078,15 @@ natural-compare@^1.4.0:
resolved "https://registry.yarnpkg.com/natural-compare/-/natural-compare-1.4.0.tgz#4abebfeed7541f2c27acfb29bdbbd15c8d5ba4f7"
integrity sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==

next-international@^1.2.4:
version "1.2.4"
resolved "https://registry.yarnpkg.com/next-international/-/next-international-1.2.4.tgz#abe50b2aa3ba7ecf92d41f87537796a4b2dd0ba3"
integrity sha512-JQvp+h2iSgA/t8hu5S/Lwow1ZErJutQRdpnplxjv4VTlCiND8T95fYih8BjkHcVhQbtM+Wu9Mb1CM32wD9hlWQ==
dependencies:
client-only "^0.0.1"
international-types "^0.8.1"
server-only "^0.0.1"

next@14.2.3:
version "14.2.3"
resolved "https://registry.yarnpkg.com/next/-/next-14.2.3.tgz#f117dd5d5f20c307e7b8e4f9c1c97d961008925d"
Expand Down Expand Up @@ -2589,6 +2603,11 @@ semver@^7.5.4:
dependencies:
lru-cache "^6.0.0"

server-only@^0.0.1:
version "0.0.1"
resolved "https://registry.yarnpkg.com/server-only/-/server-only-0.0.1.tgz#0f366bb6afb618c37c9255a314535dc412cd1c9e"
integrity sha512-qepMx2JxAa5jjfzxG79yPPq+8BuFToHd1hm7kI+Z4zAq1ftQiP7HcxMhDDItrbtwVeLg/cY2JnKnrcFkmiswNA==

set-function-length@^1.2.1:
version "1.2.2"
resolved "https://registry.yarnpkg.com/set-function-length/-/set-function-length-1.2.2.tgz#aac72314198eaed975cf77b2c3b6b880695e5449"
Expand Down

0 comments on commit a2fce77

Please sign in to comment.