Pt:Ubiquity 0.1 Author Tutoria: Difference between revisions

no edit summary
No edit summary
No edit summary
Line 64: Line 64:
Voltando ao exemplo. O centro do comando é a função <code>displayMessage()</code>, que exibe uma mensagem da maneira que o sistema operacional puder fazer.
Voltando ao exemplo. O centro do comando é a função <code>displayMessage()</code>, que exibe uma mensagem da maneira que o sistema operacional puder fazer.


You may be wondering why there is a hyphen in the name, instead of a space. That's because the Ubiquity natural language parser isn't yet smart enough to handle commands that are multiple words <i>and</i> arguments that are multiple words. It's something we'll be working on in the future.
Você deve estar espantado porque existe um hífen no nome, ao invés de um espaço. Isto porque a linguagem nativa do interpretador do Ubiquity não é ainda inteligente o bastante para tratar comandos constituídos de várias palavras e nem argumentos que são formados por múltiplas palavrass. Isto é algo a ser trabalhado no futuro.


== Using CreateCommand ==
== Usando o CreateCommand ==


For commands that are more complicated than our simple "hello-world" command, you can use the helper function <code>CmdUtils.CreateCommand()</code>, which takes an options dictionary. To redo the "hello-world" command using the convenience function, we'd write:
Para comandos que forem bem mais complexos que nosso simples comando "hello-world", podemos utilizar a função auxiliar <code>CmdUtils.CreateCommand()</code>, que utiliza um dicionário de opções. Para reescrever nosso comando "hello-world" utilizando esta conveniente função, nós escrevemos:


<pre>
<pre>
Line 79: Line 79:
</pre>
</pre>


This may not seem to be much of a win (and it isn't for simple commands) but as the commands become more complex, you'll see that it helps a lot. For one, you can name the command more freely with the method&mdash;unicode non-English characters are now fair game.
Isto pode não parecer vantajoso (e não é para comandos simples) mas assim que os comandos tornam-se cada vez mais complexos, irá se perceber que ele ajuda bastante. Uma das formas, é permitir que o nome do comando possa ser dado com maior liberdade através desse método&mdash; pois o uso caracteres unicode não ingleses é possível dentro dele.


There are a number of other useful functions in the CmdUtils namespace. We don't yet have full documentation for these commands, but you'll get a sense of the useful ones in this tutorial. For more detailed information, take a look at the [https://ubiquity.mozilla.com/hg/ubiquity-firefox/raw-file/tip/ubiquity/index.html automatically generated documentation] or [http://hg.toolness.com/ubiquity-firefox/file/9a6c9935da9f/ubiquity/chrome/content/cmdutils.js cmdutils.js].
Temos várias outras funções úteis dentro do namespace CmdUtils. Nós ainda não documentamos totalmente as funções deste comando, mas teremos a idéia da utilidade de algumas nesse tutorial. Para informações mais detalhadas, de uma olhada na [https://ubiquity.mozilla.com/hg/ubiquity-firefox/raw-file/tip/ubiquity/index.html documentação gerada automaticamente] ou [http://hg.toolness.com/ubiquity-firefox/file/9a6c9935da9f/ubiquity/chrome/content/cmdutils.js em cmdutils.js].


== Adding a Preview ==
== Acrescentando uma Previsão ==


http://img352.imageshack.us/img352/1002/picture3ex0.png
http://img352.imageshack.us/img352/1002/picture3ex0.png


Let's add a preview to our new command. Previews give the user feedback about what a command does before it's executed. Previews are great for providing rich visual feedback like displaying a graphical representation of atmospheric conditions when using the weather command as shown above. Previews have the full expressive power of HTML, including animations, so there's a lot you can do with them.
Vamos inserir uma previsão ao nosso novo comando. Previsões dão ao usuário uma idéia do que o comando faz antes que ele seja executado. Previsões são excelentes para providenciar uma resposta visual rica como a que é exibida quando é mostrada uma representação gráfica das condições atmosféricas quando utilizamos o comando weather mostradona figura acima. Previsões tem o pleno poder expressivo do HTML, incluindo animações, então há muita coisa que pode ser feita com elas.


One point of design: Preview code should never have side-effects. That is, a preview should never (without user interaction) change the state of the system.
Uma consideração: O código das previsões nunca terão efeitos sobre o outro lado. Isto é, uma previsão jamais (sem a intervenção do usuário) irá alterar o estado do sistema.


For the "hello-world" command, we don't need anything fancy: just some help text that is more descriptive than the default "Executes the hello-world command."
Para o comando "hello-world", nós não precisaremos fazer nada espetacular: apenas um pequeno texto de ajuda que o descreva melhor que o padrão "Executa o comando hello-world."


<pre>
<pre>
CmdUtils.CreateCommand({
CmdUtils.CreateCommand({
   name: "hello-world",
   name: "hello-world",
   preview: "Displays a <i>salutary</i> greeting to the planet.",
   preview: "Exibe uma <i>salutar</i> saudação ao planeta.",
   execute: function() {
   execute: function() {
     displayMessage( "Hello, World!" );
     displayMessage( "Hello, World!" );
Line 103: Line 103:
</pre>
</pre>


Here the preview is an HTML-formatted string. The preview can also be a function. We'll get to that in the next section.
Aqui a previsão é uma sequência de caracteres formatada com HTML. A previsão também pode ser uma função. Nós veremos isto na próxima seção.


= The Date Command: The Second Command =
= o Comando Date: O Segundo Comando =


== Setting the Selection ==
== Modificando uma Seleção ==


I often forget what day it is. That may be because I need to go outside more often, but, like any programmer, I generally solve my problem's symptoms with technology rather then addressing the root cause. My solution is to create a command that inserts the date at the location of the cursor.
Eu seguidamente me esqueço que dia é hoje. Isto talvez porque eu precise sair com muita freqüência, mas, como qualquer programador, geralmente eu resolvo meus problemas com tecnologia antes mesmo de saber a causa. Minha solução é criar um comando que insira a data na localização do cursor.


<pre>
<pre>
Line 121: Line 121:
</pre>
</pre>


The new function here is <code>setSelection()</code>. This inserts the passed-in text onto the page at the location of the cursor. If the cursor is in an editable text or rich-text fields, the text gets dumped there. If the cursor isn't in an editable area, <code>setSelection()</code> will still be able to insert the date. (Even when it isn't displayed, Firefox always keeps track of a cursor position. To see it, type F7.) Try going to a page, selecting some non-mutable text, and using the command. See, it works! This is particularly useful for commands like "translate", where you want to replace non-editable text with its translation.
A nova função usada aqui é <code>setSelection()</code>. Isto irá inserir o texto a ser passado pela função dentro da página onde estiver localizado o cursor. Se o cursor estiver sobre campos de texto editáveis ou sobre campos de rich-text, o texto será colocado lá. Se o cursor não estiver em uma área editável, a função <code>setSelection()</code> fará possível inserir a data. (Mesmo quando não é exibido, o Firefox sempre mantém registro da posição do cursor. Para ve-lo, pressione F7.) Experimente ir para uma página, selecionar algum texto não editável, e utilizar o comando. Veja, el trabalha! Isto é particularmente útil para comandos como "translate", onde queremos substituir o texto não editável pela sua tradução.


The <code>toLocaleDateString()</code> function is native to Javascript, so if you're not familiar with it check out the documentation for the Javascript [http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Date Date object].
A função <code>toLocaleDateString()</code> é nativa do Javascript, então se você não estiver familiarizado com ela verifique a documentação para o Javascript [http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Date Date object].


== A Better Preview ==
== A Better Preview ==
10

edits