Reconstruindo a Torre de Babel com RequireJS

Preview:

Citation preview

Reconstruindo atorre de Babel

com RequireJSe outras bibliotecas legais

Criado por / Leo Moura @lfsmoura

Pedra de Rosetta

Internacionalização - desenvolver software de maneira quedê suporte ou seja facilmente adaptado a usuários de

diferentes línguas ou expectativas culturais.

i18n

"i" + "nternationalizatio".length + "n"// > "i18n"

l10n - localizationg11n - globalizationNLS - native language support

Linguistas estimam que o número de línguas existentesseja em torno de 6000> 70% da Internet não fala inglêsLocalizar para 8 línguas significa atingir 80% da populaçãomundial

Internacionalização - dificuldades

Greece, Iran, Lebanon, Syria, Palestine, Turkey, Macedonia,Bulgaria, Albania, and Sicily

Lost in Translation

Internacionalização é muito maisque traduzir strings

People have exactly one canonical full name.People have exactly N names, for any value of N.People’s names fit within a certain defined amount ofspace.People’s names are written in ASCII.People’s names are written in any single character set.People’s names are all mapped in Unicode code points.People’s names are case sensitive.People’s names are case insensitive.People’s names do not contain numbers.

My system will never have to deal with names from China.I can safely assume that this dictionary of bad wordscontains no people’s names in it.People have names.

Falsehoods programmers believe about names

Falsehoods programmers believe about adressess

Como as linguas podem variardireção (esquerda para direita, direita para a esquerda)formato de data e horaformato dos númerospluraissímbolos e pontuaçãounidades de medidatamanhos de folhas de impressãoatalhos e teclasquestões culturais

Estou ausente fui "almoçar"Estou ausente fui „almoçar“Estou ausente fui ”almoçar”Estou ausente fui «almoçar»Estou ausente fui 「almoçar」

Microsoft ChecklistLook for geo-political sensitivity issues (e.g., borders maybe disputed between neighboring countries)Run with Complex scripts and Right to Left (RTL) supportVerify all controls function correctly with the East Asian(IME)Verify switching the keyboard to a different mappingworks correctlyVerify ANSI, double-byte, and Unicode text are handledcorrectly for display, input, and elsewhere (e.g., double-byte characters will be split if treated as ANSI)Verify any language-dependant features work correctly

Javascript has a Unicode problem

Microsoft ChecklistVerify extended and non-standard characters aredisplayed and handled correctlyVerify controls in dialogs and elsewhere are aligned andsized correctly (e.g., text is not truncated)Verify any functionality affected by the localizationprocess works correctlyVerify data is ordered correctlyVerify tab order is correctVerify no unlocalized strings remainVerify hot keys are [sic] localzied

Show me the code

1. RequireJS + plugin i18n2. RequireJS + plugin Handlebars + FormatJS

Detectando a língua no servidorvar app = require('express')();var appLocales = ['de', 'en', 'fr'];

app.get('/', function (req, res) { var locale = req.acceptsLanguages(appLocales) || 'en'; // ...customize the response to locale});

BCP47

en - inglêsmas - Maasaipt-BR - Português do Brasiles-419 - Espanhol da América Latinazn-Hans - Chinês com caracteres simplificados

Usando o plugin i18n

Usando o plugin i18n

Usando o plugin i18n

// js/nls/main.jsdefine({ root: true, "pt-br": true});// js/nls/root/main.jsdefine({ greetings: "hello world", home: "Home", about: "About"});// js/nls/pt-br/main.jsdefine({ greetings: "Olá mundo", home: "Home", about: "Sobre"});

Usando o plugin i18n

requirejs(['i18n!nls/main'], function(lang) { console.log(lang);});

Configurando manualmente a língua

require.config({ config: { i18n: { locale: 'pt-br' } }});

Para formatar datas

Usando handlebars e FormatJS

Handlebars<div class="entry"> <h1>{{title}}</h1> <div class="body"> {{body}} </div> <ul> {{#each items}} <li>{{agree_button}}</li> {{/each}} </ul></div>

var context = {

items: [

{name: "Handlebars", emotion: "love"},

{name: "Mustache", emotion: "enjoy"},

{name: "Ember", emotion: "want to learn"}

]

};

Handlebars.registerHelper('agree_button', function() {

var emotion = Handlebars.escapeExpression(this.emotion),

name = Handlebars.escapeExpression(this.name);

return new Handlebars.SafeString(

"<button>I agree. I " + emotion + " " + name + "</button>"

);

});

var source = $("#entry-template").html();var template = Handlebars.compile(source);

require.config({ paths: { hbs: 'lib/require-handlebars-plugin/hbs' }, hbs: { helpers: false }});

require(['hbs!templates/main'], function(tplMain) { var text = tplMain();}

<!-- js/templates/main.hbs --> <div class="content"> <div> {{formatMessage (intlGet "messages.welcome")}} {{name}} </div> <footer> <p>{{formatDate date day="numeric" month="long" year="numeric"}}</p> </footer> </div>

// js/nls/pt-br.jsdefine({ locales: 'pt-BR', messages: { welcome: "Bem-vindo!" }});

requirejs(['hbs/handlebars', 'handlebars-intl', 'hbs!templates/main', 'nls/pt-BR'], function(Handlebars, HandlebarsIntl, mainTpl, intlData) { HandlebarsIntl.registerWith(Handlebars); var context = { name: 'Leo', price: 1000, date: new Date() }; var text = mainTpl(context, { data: {intl: intlData} }); document.body.innerHTML = text;});

Bem-vindo! Leo

24 de setembro de 2015

fr

pt-BR

<ul> <li>{{formatNumber num}}</li> <li>{{formatNumber completed style="percent"}}</li> <li>{{formatNumber price style="currency" currency="USD"}}</li></ul>

42 000 90 % 100,95 $US

42.000 90% US$100,95

en-US

pt-BR

<p>{{formatDate date day="numeric" month="long" year="numeric"}}</p>

September 24, 2015

24 de setembro de 2015

<p> <b>{{formatRelative postDate}}</b> <b>{{formatRelative postDate units="minute"}}</b></p>

yesterday1,320 minutes ago

<div> {{formatMessage (intlGet "messages.coffee_drinking") name=name numCups=numCups}}</div>

<div>{ coffee_drinking: "Usuário {name} {numCups, plural, \ =0 {não} \ other {} } tomou {numCups, plural,\ =0 {nenhuma xícara}\ =1 {uma xícara}\ other {# xícaras}} de café"}</div>

Usuário Leo não tomou nenhuma xícara de café

ConcluindoInternacionalização é mais do que traduzir stringsProduzir software internacionalizado compensa no longoprazoNão reinventar a rodaContratar um nativo ou profissionalIncorporar internacionalização nos testes

Muchas Gracias!@lfsmoura