diff --git a/files/pt-br/mdn/at_ten/index.html b/files/pt-br/mdn/at_ten/index.html deleted file mode 100644 index 614f1bfe5e90c4..00000000000000 --- a/files/pt-br/mdn/at_ten/index.html +++ /dev/null @@ -1,41 +0,0 @@ ---- -title: 10 anos de MDN -slug: MDN/At_ten -tags: - - História - - MDN -translation_of: MDN_at_ten -original_slug: dez_anos_de_MDN ---- -
Celebrando 10 anos documentando sua Web.
- -
-
-

A história do MDN

- -

No início de 2005, um pequeno time de sonhadores se propôs a criar um novo e livre recurso online contruído pela comunidade para todos os desenvolvedores Web. Sua brilhante mas inconvêncional ideia se tornou o Mozilla Developer Network— recurso essencial para todas as tecnologias Web livres. Dez anos depois, nossa comunidade global está maior do que nunca, e juntos nós ainda estamos criando documentações, amostras de código e recursos de aprendizagem para todas as tecnologias Web livres, incluindo CSS, HTML, JavaScript e tudo mais que faz a Web livre tão poderosa quanto é.

- -

Aprenda mais about the history

- - -

Contribuindo com o MDN

- -

Por dez anos a comunidade do MDN tem documentado a Web livre. Desde corrigir pequenos erros a escrever uma API completamente nova todo mundo tem alguma coisa a oferecer, e nenhuma contribuição é menor ou maior que a outra. Nós temos mais de 90.000 páginas de conteúdo que tem sido escritas ou traduzidas por membros de nossa fantástica comunidade de Mozillians. Você pode se tornar um de nós.

- -

Aprenda mais about contributing

- -

- -

-
- -
{{TenthCampaignQuote}}
- - - -
    -
  1. 10 anos de MDN
  2. -
  3. A história do MDN
  4. -
  5. Contribuindo com o MDN
  6. -
-
diff --git a/files/pt-br/mdn/at_ten/index.md b/files/pt-br/mdn/at_ten/index.md new file mode 100644 index 00000000000000..d0eb61833d966f --- /dev/null +++ b/files/pt-br/mdn/at_ten/index.md @@ -0,0 +1,30 @@ +--- +title: 10 anos de MDN +slug: MDN/At_ten +tags: + - História + - MDN +translation_of: MDN_at_ten +original_slug: dez_anos_de_MDN +--- +Celebrando 10 anos documentando sua Web. + +## A história do MDN + +No início de 2005, um pequeno time de sonhadores se propôs a criar um novo e livre recurso online contruído pela comunidade para todos os desenvolvedores Web. Sua brilhante mas inconvêncional ideia se tornou o Mozilla Developer Network— recurso essencial para todas as tecnologias Web livres. Dez anos depois, nossa comunidade global está maior do que nunca, e juntos nós ainda estamos criando documentações, amostras de código e recursos de aprendizagem para todas as tecnologias Web livres, incluindo CSS, HTML, JavaScript e tudo mais que faz a Web livre tão poderosa quanto é. + +[Aprenda mais about the history](/pt-BR/docs/MDN_at_ten/History_of_MDN) + +## Contribuindo com o MDN + +Por dez anos a comunidade do MDN tem documentado a Web livre. Desde corrigir pequenos erros a escrever uma API completamente nova todo mundo tem alguma coisa a oferecer, e nenhuma contribuição é menor ou maior que a outra. Nós temos mais de 90.000 páginas de conteúdo que tem sido escritas ou traduzidas por membros de nossa fantástica comunidade de Mozillians. Você pode se tornar um de nós. + +[Aprenda mais about contributing](/pt-BR/docs/MDN_at_ten/Contributing_to_MDN) + +{{TenthCampaignQuote}} + +## Subnav + +1. [10 anos de MDN](/pt-BR/docs/MDN_at_ten/) +2. [A história do MDN](/pt-BR/docs/MDN_at_ten/History_of_MDN) +3. [Contribuindo com o MDN](/pt-BR/docs/MDN_at_ten/Contributing_to_MDN) diff --git a/files/pt-br/mdn/community/contributing/getting_started/index.html b/files/pt-br/mdn/community/contributing/getting_started/index.html deleted file mode 100644 index 2e15fbd2e5c3aa..00000000000000 --- a/files/pt-br/mdn/community/contributing/getting_started/index.html +++ /dev/null @@ -1,59 +0,0 @@ ---- -title: Primeiros Passos no MDN -slug: MDN/Community/Contributing/Getting_started -tags: - - Documentação - - Primeiros Passos - - Guia - - MDN - - Projeto MDN - - Novos Contribuidores -original_slug: MDN/Contribute/Getting_started ---- -
{{MDNSidebar}}
- -

Somos uma comunidade aberta de desenvolvedores construindo recursos para uma web melhor, independente de marca, navegador ou plataforma. Qualquer pessoa pode contribuir e cada contribuição nos torna mais fortes. Juntos podemos conduzir inovações na Web para servir ao bem maior. E começa aqui, com você.

- -

Cada parte do MDN (documentações, demos e o próprio site) são criados por uma comunidade aberta de desenvolvedores. Por favor, junte-se a nós!

- -

4 passos simples para o MDN

- -

MDN é uma fonte de código aberto na qual qualquer pessoa pode adicionar ou editar conteúdo. Você não precisa ser um programador ou saber muito sobre tecnologia. Existe uma variedade de tarefas que precisam ser feitas, das mais simples (Revisão e correção de erros de digitação) até as mais complexas (escrever documentação de API).

- -

Contribuir é fácil e seguro. Caso você cometa algum erro, este pode ser facilmente corrigido. Se você não sabe exatamente como as coisas deveriam parecer, ou se a sua gramática não é assim tão boa, não se preocupe! Temos uma equipe cujo trabalho é garantir que o conteúdo do MDN esteja o melhor possível. Alguém verificará seu trabalho para garantir que esteja correto e bem escrito. Compartilhe o que você sabe e siga seus pontos fortes.

- -

Passo 1: Crie uma conta no GitHub

- -

Para começar a contribuir no MDN, você precisa criar uma conta no GitHub.

- - -

Passo 2: Escolha uma tarefa

- -

Agora que você está logado, leia as descrições dos diferentes tipos de tarefas disponíveis na página principal de Contribuição, e escolha a que te agradar mais. Você pode escolher qualquer tarefa que gostar para iniciar sua contribuição.

- -

Passo 3: Faça a tarefa

- -

Assim que decidir que tipo de tarefa você quer fazer, procure uma página específica, exemplo de código e quaisquer outros recursos disponíveis para trabalhar e faça!

- -

Passo 4: Peça ajuda

- -

Se você não tiver certeza do que fazer em qualquer momento, então você está mais que bem-vindo para pedir ajuda. Existem algumas opções diferentes de ajuda:

- - - -

Não se preocupe em fazer tudo perfeito; outros colaboradores do MDN estão aqui para ajudar a corrigir os erros que passaram despercebidos.

- -

Guias completos úteis para iniciantes

- -

Nós esperamos que os contribuidores do MDN tenham uma certa quantidade de conhecimento prévio antes de começar a trabalhar no conteúdo. Se você é novo nos tópicos a seguir, nós aconselhamos que você visite os links fornecidos para te ajudar a começar mais rapidamente:

- - diff --git a/files/pt-br/mdn/community/contributing/getting_started/index.md b/files/pt-br/mdn/community/contributing/getting_started/index.md new file mode 100644 index 00000000000000..1192b01bb5bf8b --- /dev/null +++ b/files/pt-br/mdn/community/contributing/getting_started/index.md @@ -0,0 +1,54 @@ +--- +title: Primeiros Passos no MDN +slug: MDN/Community/Contributing/Getting_started +tags: + - Documentação + - Primeiros Passos + - Guia + - MDN + - Projeto MDN + - Novos Contribuidores +original_slug: MDN/Contribute/Getting_started +--- +{{MDNSidebar}} + +Somos uma comunidade aberta de desenvolvedores construindo recursos para uma web melhor, independente de marca, navegador ou plataforma. Qualquer pessoa pode contribuir e cada contribuição nos torna mais fortes. Juntos podemos conduzir inovações na Web para servir ao bem maior. E começa aqui, com você. + +Cada parte do MDN (documentações, demos e o próprio site) são criados por uma comunidade aberta de desenvolvedores. Por favor, junte-se a nós! + +## 4 passos simples para o MDN + +MDN é uma fonte de código aberto na qual **qualquer pessoa** pode adicionar ou editar conteúdo. Você não precisa ser um programador ou saber muito sobre tecnologia. Existe uma variedade de tarefas que precisam ser feitas, das mais simples (Revisão e correção de erros de digitação) até as mais complexas (escrever documentação de API). + +Contribuir é fácil e seguro. Caso você cometa algum erro, este pode ser facilmente corrigido. Se você não sabe exatamente como as coisas deveriam parecer, ou se a sua gramática não é assim tão boa, não se preocupe! Temos uma equipe cujo trabalho é garantir que o conteúdo do MDN esteja o melhor possível. Alguém verificará seu trabalho para garantir que esteja correto e bem escrito. Compartilhe o que você sabe e siga seus pontos fortes. + +### Passo 1: Crie uma conta no GitHub + +Para começar a contribuir no MDN, você precisa [criar uma conta no GitHub](https://github.com/mdn/content/#setup). + +### Passo 2: Escolha uma tarefa + +Agora que você está logado, leia as descrições dos diferentes tipos de tarefas disponíveis na [página principal de Contribuição](/pt-BR/docs/MDN/Contribute), e escolha a que te agradar mais. Você pode escolher qualquer tarefa que gostar para iniciar sua contribuição. + +### Passo 3: Faça a tarefa + +Assim que decidir que tipo de tarefa você quer fazer, procure uma página específica, exemplo de código e quaisquer outros recursos disponíveis para trabalhar e faça! + +### Passo 4: Peça ajuda + +Se você não tiver certeza do que fazer em qualquer momento, então você está mais que bem-vindo para pedir ajuda. Existem algumas opções diferentes de ajuda: + +- Se você quer falar conosco de forma síncrona e perguntar sobre o MDN em si, junte-se a discussão no [chat da Documentação Web do MDN](https://chat.mozilla.org/#/room/#mdn:mozilla.org) no [Matrix](https://wiki.mozilla.org/Matrix). +- Você também pode enviar um email para . +- Se você está aprendendo desenvolvimento web e está emperrado em um problema de código, nós temos [fórums ativos](https://discourse.mozilla.org/c/mdn/learn/250) nos quais você pode fazer perguntas e obter ajuda. + +Não se preocupe em fazer tudo perfeito; outros colaboradores do MDN estão aqui para ajudar a corrigir os erros que passaram despercebidos. + +## Guias completos úteis para iniciantes + +Nós esperamos que os contribuidores do MDN tenham uma certa quantidade de conhecimento prévio antes de começar a trabalhar no conteúdo. Se você é novo nos tópicos a seguir, nós aconselhamos que você visite os links fornecidos para te ajudar a começar mais rapidamente: + +- Tecnologias Web: Se você é novo com HTML, CSS, JavaScript, etc., confira nossos tutoriais para [Aprender desenvolvimento web](/pt-BR/docs/Learn). +- Código aberto: Se você nunca contribuiu com um projeto de código aberto antes, leia [Etiqueta básica para projetos de código aberto](/pt-BR/docs/MDN/Contribute/Open_source_etiquette). +- Git e GitHub: Se você não está familiarizado com estas ferramentas, [GitHub para iniciantes](/pt-BR/docs/MDN/Contribute/GitHub_beginners) vai te ajudar a começar. +- Estrutura de repositórios do MDN: Se você não está certo sobre qual repositório editar para mudar diferentes partes do conteúdo do MDN, [Onde está tudo no MDN?](/pt-BR/docs/MDN/Contribute/Where_is_everything) será seu ponto de entrada para os lugares certos. diff --git a/files/pt-br/mdn/community/contributing/our_repositories/index.html b/files/pt-br/mdn/community/contributing/our_repositories/index.html deleted file mode 100644 index 3705547a32eb5d..00000000000000 --- a/files/pt-br/mdn/community/contributing/our_repositories/index.html +++ /dev/null @@ -1,35 +0,0 @@ ---- -title: Onde está tudo no MDN? Um guia para nossos repositórios -slug: MDN/Community/Contributing/Our_repositories -tags: - - Boas práticas - - Comunidade - - GitHub - - MDN - - Iniciantes - - Repositórios -original_slug: MDN/Contribute/Where_is_everything ---- -

{{MDNSidebar}}

- -

MDN é um projeto complexo com muitas partes móveis. É fácil começar a contribuir para o site, se você sabe um pouco sobre GitHub e está começando com algum erro de escrita simples ou pequenas melhorias de código. Contudo, quando você começa a fazer contribuições significantes como adicionar páginas completamente novas, você vai notar que alguns pedaços de conteúdo não estão no código fonte da página e, ao invés disso, vem de algum outro lugar.

- -

Este artigo age como um guia rápido para encontrar diferentes repositórios que você precisa editar e atualizar para mudar diferentes partes do conteúdo do MDN.

- -

Repositórios principais

- - - -

Outros repositórios

- - diff --git a/files/pt-br/mdn/community/contributing/our_repositories/index.md b/files/pt-br/mdn/community/contributing/our_repositories/index.md new file mode 100644 index 00000000000000..bcad7584b81f58 --- /dev/null +++ b/files/pt-br/mdn/community/contributing/our_repositories/index.md @@ -0,0 +1,31 @@ +--- +title: Onde está tudo no MDN? Um guia para nossos repositórios +slug: MDN/Community/Contributing/Our_repositories +tags: + - Boas práticas + - Comunidade + - GitHub + - MDN + - Iniciantes + - Repositórios +original_slug: MDN/Contribute/Where_is_everything +--- +{{MDNSidebar}} + +MDN é um projeto complexo com muitas partes móveis. É fácil começar a contribuir para o site, se você sabe um pouco sobre GitHub e está começando com algum erro de escrita simples ou pequenas melhorias de código. Contudo, quando você começa a fazer contribuições significantes como adicionar páginas completamente novas, você vai notar que alguns pedaços de conteúdo não estão no código fonte da página e, ao invés disso, vem de algum outro lugar. + +Este artigo age como um guia rápido para encontrar diferentes repositórios que você precisa editar e atualizar para mudar diferentes partes do conteúdo do MDN. + +## Repositórios principais + +- **Conteúdo principal**: . O repositório mais importante para o conteúdo do MDN — Aqui é onde todo o conteúdo base, em inglês, do site está armazenado, e onde você vai fazer mudanças padrões para o conteúdo da página. +- **Plataforma MDN**: . Aqui é onde a plataforma MDN é armazenada, e onde você vai se quiser fazer mudanças de alto nível na estrutura de páginas do MDN ou no maquinário de renderização. +- **Dados de compatibilidade do Browser**: . Aqui é onde os dados usados para gerar as tabelas de compatibilidade dos browsers em nossas páginas de referências são armazenados (exemplo). Vá aqui para fazer mudanças nos dados de compatibilidade! +- **Exemplos interativos**: . Este repositório armazena o renderizador de código e blocos de código de exemplo que juntos produzem os belos, editáveis e copiáveis exemplos encontrados no topo de muitas de nossas páginas de referência (exemplo). Edite esses exemplos aqui. +- **Conteúdo traduzido**: . Aqui é onde mora nosso conteúdo localizado. Vá aqui se você quiser ajudar a traduzir páginas em qualquer um de nossos locais mantidos ativamente. +- **Dados CSS**: . Originalmente previsto para ser um repositório que guarda os dados gerais do MDN, o repositório agora tem o propósito de guardar dados sobre funcionalidades do CSS como sintaxe formal, herança, valor computado, tipos de animação, etc. Ele é usado para gerar seções nas páginas de referências de CSS como uma definição formal (exemplo) e sintaxe formal (exemplo). + +## Outros repositórios + +- **Repositório de demos**. O GitHub da organização do MDN contém um grande número de repositórios de demonstração, por exemplo [css-examples](https://github.com/mdn/css-examples), [dom-examples](https://github.com/mdn/dom-examples), [webaudio-examples](https://github.com/mdn/webaudio-examples). Estes, no geral, contém exemplos autônomos que são frequentemente ligados as páginas do MDN, mas, ocasionalmente, você vai encontrar algum destes exemplos embutidos em uma página usando uma chamada macro como esta — \\{{EmbedGHLiveSample("css-examples/learn/tasks/grid/grid1.html", '100%', 700)}}. Se você quer editar o exemplo autônomo, ele sempre será encontrado em algum destes repositórios de exemplos. +- **MDN-minimalist**: . As informações base de estilização do MDN. Se você quer ajudar a melhorar o estilo CSS do MDN, este é o lugar para visitar. diff --git a/files/pt-br/mdn/community/index.html b/files/pt-br/mdn/community/index.html deleted file mode 100644 index aa6f272bc7ffe8..00000000000000 --- a/files/pt-br/mdn/community/index.html +++ /dev/null @@ -1,61 +0,0 @@ ---- -title: Envie sugestões sobre o MDN -slug: MDN/Community -tags: - - Documentação - - Guía - - MDN Meta -translation_of: MDN/Contribute/Feedback -original_slug: MDN/Contribute/Feedback ---- -
{{MDNSidebar}}
- -
{{IncludeSubnav("/en-US/docs/MDN")}}
- -

Bem-vindo ao Mozilla Developer Network! Se você tem sugestões, ou está tendo problemas usando MDN, este é o lugar certo para estar. O fato de que você está interessado em oferecer um feedback, faz de você mais uma parte da comunidade Mozilla e agradecemos antecipadamente por seu interesse.

- -

Você tem várias opções para oferecer suas idéias. Este artigo irá ajudá-lo a fazê-lo.

- -

Atualizar a documentação

- -

Primeiro de tudo, se você ver algum problema com a documentação, você deve sempre se sentir livre para corrigir por si mesmo.

- -
    -
  1. Você pode efetuar o login com sua conta do Github ou do Persona.
  2. -
  3. Após efetuar o login, clique no botão Editar (em azul) em qualquer página para que o editor seja aberto.
  4. -
  5. Clique no botão Publicar (em verde) quando você terminar suas correções.
  6. -
- -

A Documentação aqui é uma wiki, e é curada por uma equipe de voluntários e funcionários remunerados, então não seja tímido — sua gramática não precisa ser perfeita. Nós vamos arrumar se você cometer um erro; sem nenhum problema!

- -

Para mais informações sobre contribuir com a documentação da MDN, veja:

- - - -

Junte-se à conversação

- -

Fale conosco! Existem algumas maneiras de entrar em contato com outras pessoas que trabalham no conteúdo do MDN.

- -

Chat

- -

-

Email

- - -

Discussões de longo-prazo acontecem em nossa mailing list, dev-mdc@lists.mozilla.org. você postar na lista sem se inscrever nela, mas neste caso, sua postagem deve ser aprovada por um moderador, o que significa que levará mais tempo para que outros possam vê-lo. Você pode visualizar e postar em dev-mdc através de sua escolha de formatos:

- -

{{ DiscussionList("dev-mdc", "mozilla.dev.mdc") }}

- -

Relatar um problema

- -

Problemas na documentação

- -

se você encontrar um problema na documentação e não puder corrigí-lo por qualquer motivo, você pode reportar um problema! Você pode usar este formulário para qualquer problema de documentação, seja uma correção simples ou uma solicitação para um conteúdo completamente novo. Como mencionado antes, nós convidamos você para contribuir com alterações por si mesmo, mas esta opção também está disponível para você.

- -

Problemas no site

- -

se você encontrar problemas com o web site do MDN, ou tem idéias para novos recursos para o site, você pode enviar um ticket para a equipe de desenvolvimento MDN.

diff --git a/files/pt-br/mdn/community/index.md b/files/pt-br/mdn/community/index.md new file mode 100644 index 00000000000000..21f6c2c8d38e1e --- /dev/null +++ b/files/pt-br/mdn/community/index.md @@ -0,0 +1,53 @@ +--- +title: Envie sugestões sobre o MDN +slug: MDN/Community +tags: + - Documentação + - Guía + - MDN Meta +translation_of: MDN/Contribute/Feedback +original_slug: MDN/Contribute/Feedback +--- +{{MDNSidebar}}{{IncludeSubnav("/en-US/docs/MDN")}} + +Bem-vindo ao Mozilla Developer Network! Se você tem sugestões, ou está tendo problemas usando MDN, este é o lugar certo para estar. O fato de que você está interessado em oferecer um feedback, faz de você mais uma parte da comunidade Mozilla e agradecemos antecipadamente por seu interesse. + +Você tem várias opções para oferecer suas idéias. Este artigo irá ajudá-lo a fazê-lo. + +## Atualizar a documentação + +Primeiro de tudo, se você ver algum problema com a documentação, você deve sempre se sentir livre para corrigir por si mesmo. + +1. Você pode efetuar o [login](/pt-BR/docs/MDN/Contribute/Howto/Create_an_MDN_account) com sua conta do [Github](https://github.com/) ou do [Persona](https://www.persona.org/). +2. Após efetuar o login, clique no botão **Editar** (em azul) em qualquer página para que o [editor](/pt-BR/docs/MDN/Contribute/Editor) seja aberto. +3. Clique no botão **Publicar** (em verde) quando você terminar suas correções. + +A Documentação aqui é uma wiki, e é curada por uma equipe de voluntários e funcionários remunerados, então não seja tímido — sua gramática não precisa ser perfeita. Nós vamos arrumar se você cometer um erro; sem nenhum problema! + +Para mais informações sobre contribuir com a documentação da MDN, veja: + +- [Começando](/pt-BR/docs/Project:en/Project:Getting_started) +- [Contribuindo para o MDN](/pt-BR/docs/MDN/Contribute) +- [Guia do Editor MDN](/pt-BR/docs/MDN/Contribute/Editor) + +## Junte-se à conversação + +Fale conosco! Existem algumas maneiras de entrar em contato com outras pessoas que trabalham no conteúdo do MDN. + +### Chat + +### Email + +Discussões de longo-prazo acontecem em nossa mailing list, [dev-mdc@lists.mozilla.org](https://lists.mozilla.org/listinfo/dev-mdc). você postar na lista sem se inscrever nela, mas neste caso, sua postagem deve ser aprovada por um moderador, o que significa que levará mais tempo para que outros possam vê-lo. Você pode visualizar e postar em dev-mdc através de sua escolha de formatos: + +{{ DiscussionList("dev-mdc", "mozilla.dev.mdc") }} + +## Relatar um problema + +### Problemas na documentação + +se você encontrar um problema na documentação e não puder corrigí-lo por qualquer motivo, você pode [reportar um problema](https://github.com/mdn/sprints/issues/new?template=issue-template.md&projects=mdn/sprints/2&labels=user-report)! Você pode usar este formulário para qualquer problema de documentação, seja uma correção simples ou uma solicitação para um conteúdo completamente novo. Como mencionado antes, nós convidamos você para contribuir com alterações por si mesmo, mas esta opção também está disponível para você. + +### Problemas no site + +se você encontrar problemas com o web site do MDN, ou tem idéias para novos recursos para o site, você pode [enviar um ticket para a equipe de desenvolvimento MDN](https://bugzilla.mozilla.org/form.mdn). diff --git a/files/pt-br/mdn/contribute/howto/index.html b/files/pt-br/mdn/contribute/howto/index.html deleted file mode 100644 index 582632ca4be34e..00000000000000 --- a/files/pt-br/mdn/contribute/howto/index.html +++ /dev/null @@ -1,9 +0,0 @@ ---- -title: Guia de contribuição -slug: MDN/Contribute/Howto -translation_of: MDN/Contribute/Howto -original_slug: MDN/Contribute/guia ---- -
{{MDNSidebar}}

Os seguintes artigos fornecem orientações passo-a-passo para realização de tarefas específicas no MDN.

- -

{{LandingPageListSubpages}}

diff --git a/files/pt-br/mdn/contribute/howto/index.md b/files/pt-br/mdn/contribute/howto/index.md new file mode 100644 index 00000000000000..8705c52733bc16 --- /dev/null +++ b/files/pt-br/mdn/contribute/howto/index.md @@ -0,0 +1,11 @@ +--- +title: Guia de contribuição +slug: MDN/Contribute/Howto +translation_of: MDN/Contribute/Howto +original_slug: MDN/Contribute/guia +--- +{{MDNSidebar}} + +Os seguintes artigos fornecem orientações passo-a-passo para realização de tarefas específicas no MDN. + +{{LandingPageListSubpages}} diff --git a/files/pt-br/mdn/contribute/index.html b/files/pt-br/mdn/contribute/index.html deleted file mode 100644 index 6eceaf42cbace9..00000000000000 --- a/files/pt-br/mdn/contribute/index.html +++ /dev/null @@ -1,20 +0,0 @@ ---- -title: Contribuindo para o MDN -slug: MDN/Contribute -tags: - - Guía - - MDN Meta - - Página de destino -translation_of: MDN/Contribute ---- -
{{MDNSidebar}}
- -
{{IncludeSubnav("/pt-BR/docs/MDN")}}
- -

Bem-vindo! Ao visitar esta página, você deu o primeiro passo para se tornar um colaborador da MDN.

- -

Os guias listados aqui cobrem todos os aspectos de contribuição para a MDN, incluindo guias de estilo, guia de utilização do nosso editor e ferramentas e muito mais. Por favor, assegure-se de ler (e estar em conformidade) com os Termos da Mozilla antes de editar ou criar qualquer página.

- -

Se você não contribuiu com a MDN anteriormente, o guia de primeiros passos pode lhe ajudar a selecionar uma tarefa para começar a ajudar.

- -

{{LandingPageListSubPages()}}

diff --git a/files/pt-br/mdn/contribute/index.md b/files/pt-br/mdn/contribute/index.md new file mode 100644 index 00000000000000..5abcb63c366dd2 --- /dev/null +++ b/files/pt-br/mdn/contribute/index.md @@ -0,0 +1,18 @@ +--- +title: Contribuindo para o MDN +slug: MDN/Contribute +tags: + - Guía + - MDN Meta + - Página de destino +translation_of: MDN/Contribute +--- +{{MDNSidebar}}{{IncludeSubnav("/pt-BR/docs/MDN")}} + +Bem-vindo! Ao visitar esta página, você deu o primeiro passo para se tornar um colaborador da MDN. + +Os guias listados aqui cobrem todos os aspectos de contribuição para a MDN, incluindo guias de estilo, guia de utilização do nosso editor e ferramentas e muito mais. Por favor, assegure-se de ler (e estar em conformidade) com os [Termos da Mozilla](https://www.mozilla.org/en-US/about/legal/terms/mozilla/) antes de editar ou criar qualquer página. + +Se você não contribuiu com a MDN anteriormente, o guia de [primeiros passos](/pt-BR/docs/MDN/Primeiros_Passos) pode lhe ajudar a selecionar uma tarefa para começar a ajudar. + +{{LandingPageListSubPages()}} diff --git a/files/pt-br/mdn/contribute/processes/index.html b/files/pt-br/mdn/contribute/processes/index.html deleted file mode 100644 index 72ba36fde9e303..00000000000000 --- a/files/pt-br/mdn/contribute/processes/index.html +++ /dev/null @@ -1,7 +0,0 @@ ---- -title: Processos de documentação -slug: MDN/Contribute/Processes -translation_of: MDN/Contribute/Processes -original_slug: MDN/Contribute/Processos ---- -
{{MDNSidebar}}

O projeto de documentação do MDN é enorme; há um grande número de tecnologias para cobrir e nós temos centenas de colaboradores em todo o mundo. Para ajudar a trazer ordem ao caos, temos processos padrões a seguir quando se trabalha em tarefas específicas relacionadas com a documentação. Aqui você vai encontrar os guias para esses processos.

diff --git a/files/pt-br/mdn/contribute/processes/index.md b/files/pt-br/mdn/contribute/processes/index.md new file mode 100644 index 00000000000000..4df19cc888ec9d --- /dev/null +++ b/files/pt-br/mdn/contribute/processes/index.md @@ -0,0 +1,9 @@ +--- +title: Processos de documentação +slug: MDN/Contribute/Processes +translation_of: MDN/Contribute/Processes +original_slug: MDN/Contribute/Processos +--- +{{MDNSidebar}} + +O projeto de documentação do MDN é enorme; há um grande número de tecnologias para cobrir e nós temos centenas de colaboradores em todo o mundo. Para ajudar a trazer ordem ao caos, temos processos padrões a seguir quando se trabalha em tarefas específicas relacionadas com a documentação. Aqui você vai encontrar os guias para esses processos. diff --git a/files/pt-br/mdn/index.html b/files/pt-br/mdn/index.html deleted file mode 100644 index 1d722781a0ff20..00000000000000 --- a/files/pt-br/mdn/index.html +++ /dev/null @@ -1,21 +0,0 @@ ---- -title: O projeto MDN -slug: MDN -tags: - - MDN Meta - - Página de destino -translation_of: MDN ---- -
{{MDNSidebar}}
- -

O MDN Web Docs é uma wiki onde nós documentamos a Web aberta, as tecnologias Mozilla e outros tópicos de desenvolvedores. Qualquer pessoa é bem-vinda para adicionar e editar conteúdo. Você não precisa ser um programador ou saber muito sobre tecnologia; há muitas tarefas diferentes que precisam ser executadas, desde os simples (corrigir erros de leitura e erros de correção) até as mais complexas (escrever a documentação da API).

- -

A missão do MDN Web Docs é fornecer aos desenvolvedores as informações necessárias para criar facilmente na plataforma web. Nós convidamos você a ajudar!

- -

Nós precisamos da sua ajuda! É fácil. Não se preocupe em pedir permissão ou em cometer erros. Por outro lado, por favor, conheça a comunidade MDN; estamos aqui para ajudá-lo! A documentação abaixo, pode te ajudar a começar.

- -
    -
  • Início rápido para iniciantes Você é novo no MDN e quer aprender como ajudar a torná-lo melhor? Comece aqui!
  • -
  • Eu sou um usuário avançado Acesse nosso guia completo e aprofundado para os colaboradores do MDN para aprender mais quando você se sentir confortável.
  • -
  • Compartilhe Se você ama o MDN, compartilhe a nossa a rede! Encontre o material necessário, como arte, ferramentas e guias para promover o MDN.
  • -
diff --git a/files/pt-br/mdn/index.md b/files/pt-br/mdn/index.md new file mode 100644 index 00000000000000..507ff919541a87 --- /dev/null +++ b/files/pt-br/mdn/index.md @@ -0,0 +1,19 @@ +--- +title: O projeto MDN +slug: MDN +tags: + - MDN Meta + - Página de destino +translation_of: MDN +--- +{{MDNSidebar}} + +O **MDN Web Docs** é uma wiki onde nós documentamos a Web aberta, as tecnologias Mozilla e outros tópicos de desenvolvedores. Qualquer pessoa é bem-vinda para adicionar e editar conteúdo. Você não precisa ser um programador ou saber muito sobre tecnologia; há muitas tarefas diferentes que precisam ser executadas, desde os simples (corrigir erros de leitura e erros de correção) até as mais complexas (escrever a documentação da API). + +A missão do MDN Web Docs é fornecer aos desenvolvedores as informações necessárias para criar facilmente na plataforma web. Nós convidamos você a ajudar! + +Nós precisamos da sua ajuda! É fácil. Não se preocupe em pedir permissão ou em cometer erros. Por outro lado, por favor, conheça a [comunidade MDN](/pt-BR/docs/MDN/Comunidade); estamos aqui para ajudá-lo! A documentação abaixo, pode te ajudar a começar. + +- [Início rápido para iniciantes](/pt-BR/docs/MDN/Primeiros_Passos) Você é novo no MDN e quer aprender como ajudar a torná-lo melhor? Comece aqui! +- [Eu sou um usuário avançado](/pt-BR/docs/MDN/Contribute) Acesse nosso guia completo e aprofundado para os colaboradores do MDN para aprender mais quando você se sentir confortável. +- [Compartilhe](/pt-BR/docs/MDN/Promote) Se você ama o MDN, compartilhe a nossa a rede! Encontre o material necessário, como arte, ferramentas e guias para promover o MDN. diff --git a/files/pt-br/mdn/tools/index.html b/files/pt-br/mdn/tools/index.html deleted file mode 100644 index 4affbd278a09bb..00000000000000 --- a/files/pt-br/mdn/tools/index.html +++ /dev/null @@ -1,15 +0,0 @@ ---- -title: Ferramentas do MDN -slug: MDN/Tools -tags: - - Landing - - MDN Meta -translation_of: MDN/Tools ---- -
{{MDNSidebar}}
- -
{{IncludeSubnav("/pt-BR/docs/MDN")}}
- -

MDN oferece ferramentas tornando fácil o acompanhamento do progresso, gerenciamento de conteúdo e manter o site com as últimas atualizações.

- -

{{LandingPageListSubpages}}

diff --git a/files/pt-br/mdn/tools/index.md b/files/pt-br/mdn/tools/index.md new file mode 100644 index 00000000000000..c647258504c144 --- /dev/null +++ b/files/pt-br/mdn/tools/index.md @@ -0,0 +1,13 @@ +--- +title: Ferramentas do MDN +slug: MDN/Tools +tags: + - Landing + - MDN Meta +translation_of: MDN/Tools +--- +{{MDNSidebar}}{{IncludeSubnav("/pt-BR/docs/MDN")}} + +MDN oferece ferramentas tornando fácil o acompanhamento do progresso, gerenciamento de conteúdo e manter o site com as últimas atualizações. + +{{LandingPageListSubpages}} diff --git a/files/pt-br/mdn/tools/kumascript/index.html b/files/pt-br/mdn/tools/kumascript/index.html deleted file mode 100644 index 67f0772f742e84..00000000000000 --- a/files/pt-br/mdn/tools/kumascript/index.html +++ /dev/null @@ -1,500 +0,0 @@ ---- -title: KumaScript -slug: MDN/Tools/KumaScript -tags: - - Guide - - Kuma - - KumaScript - - MDN Meta - - NeedsContent - - NeedsTranslation - - Site-wide - - Tools - - TopicStub -translation_of: MDN/Tools/KumaScript ---- -
{{MDNSidebar}}

Overview

- -

On the Kuma platform that powers MDN, the template system for automating aspects of content on the wiki is called KumaScript. KumaScript is powered by server-side JavaScript, implemented using Node.js. This article provides basic information on how to use KumaScript.

- -

For a detailed overview and Q&A of KumaScript, watch the MDN dev team's KumaScript Fireside Chat (the meeting starts at 10 minutes into the video). KumaScript replaced DekiScript, which was the template language for MindTouch, the previous platform used by MDN.

- -

What is KumaScript?

- -
    -
  • A way to reuse and localize content that appears repeatedly between documents (e.g., compatibility labels, section navigation, warning banners).
  • -
  • A way to build documents out of content pulled from other documents.
  • -
  • A way to fetch and include content from other web sites and services (e.g., Bugzilla).
  • -
- -

What KumaScript is not

- -
    -
  • KumaScript does not support interactive scripting of the kind that can accept form submissions.
  • -
  • KumaScript does not have access to a database, files, or any other way to store information persistently.
  • -
  • KumaScript does not support site personalization based on the user currently logged in.
  • -
  • KumaScript does not have access to user information, only to the content and metadata of a wiki page being viewed.
  • -
- -

Basics

- -

KumaScript is used on MDN in embedded JavaScript templates. These templates can be invoked in document content by any MDN author, through the use of macros.

- -

A script in KumaScript is a template, and each template is a file in the macros directory of the KumaScript repository on Github. A template looks like this:

- -
<% for (var i = 0; i < $0; i++) { %>
-Hello #<%= i %>
-<% } %>
- -

Invoking a template is done with a macro, which can be used anywhere in any wiki content. A macro looks like this:

- -
\{{ hello("3") }}
- -

The output of the macro looks like this:

- -
Hello #0
-Hello #1
-Hello #2
- -

Macro syntax

- -

KumaScript templates are invoked in document content with macros, like this:

- -
\{{ templateName("arg0", "arg1", ..., "argN") }}
-
- -

Macro syntax consists of these rules:

- -
    -
  • Macros start and end with \{{ and \}} characters.
  • -
  • The first part of the macro is the name of a template. The lowercase value of this name should match the lowercase value of one of the filenames under the macros directory of KumaScript.
  • -
  • A template can accept parameters, and this parameter list starts and ends with parentheses.
  • -
  • All non-numeric parameters must be in quotes. Numbers can be left unquoted.
  • -
- -

Using JSON as a macro parameter

- -

As a semi-experimental feature (not guaranteed to work), you can supply a JSON object for the first and only parameter, like so:

- -
\{{ templateName({ "Alpha":"one", "Beta":["a","b","c"], "Foo":"http:\/\/mozilla.org\/" }) }}
-
- -

The data from this macro is available in template code as an object in the $0 argument (e.g., $0.Alpha, $0.Beta, $0.Foo). This also allows you to express complex data structures in macro parameters that are hard or impossible to do with a simple list of parameters.

- -

Note that this parameter style is very picky — it must adhere to JSON syntax exactly, which has some requirements about escaping characters that are easy to miss (e.g., all forward slashes are escaped). When in doubt, try running your JSON through a validator.

- -

How to write "\{{" in text

- -

Since the character sequence "\{{" is used to indicate the start of a macro, this can be troublesome if you actually just want to use "\{{" and "}}" in a page. It will probably produce DocumentParsingError messages.

- -

In this case, you can escape the first brace with a backslash, like so: \\{

- -

Template syntax

- -

Each KumaScript template is a file under the macros directory of KumaScript. You create and edit these files as you would the files of any open-source project on GitHub (see the KumaScript README for more information).

- -

KumaScript templates are processed by an embedded JavaScript template engine with a few simple rules:

- -
    -
  • Within a template, the parameters passed in from the macro are available as the variables $0, $1, $2, and so on. The entire list of parameters is also available in a template as the variable arguments.
  • -
  • Most text is treated as output and included in the output stream.
  • -
  • JavaScript variables and expressions can be inserted into the output stream with these blocks: -
      -
    • <%= expr %> — the value of a JavaScript expression is escaped for HTML before being included in output (e.g., characters like < and > are turned into &lt; and &gt;).
    • -
    • <%- expr %> — the value of a JavaScript expression is included in output without any escaping. (Use this if you want to dynamically build markup or use the results of another template that may include markup.)
    • -
    • It is an error to include semicolons inside these blocks.
    • -
    -
  • -
  • Anything inside a <% %> block is interpreted as JavaScript. This can include loops, conditionals, etc.
  • -
  • Nothing inside a <% %> block can ever contribute to the output stream. But, you can transition from JS mode to output mode using <% %>—for example: -
    <% for (var i = 0; i < $0; i++) { %>
    -Hello #<%= i %>
    -<% } %>
    -
    - -

    Note how the JavaScript code is contained in <% ... %>, and output happens in the space between %> ... <%. The for loop in JS can begin with one <% %> block, transition to output mode, and finish up in a second <% %> JS block.

    -
  • -
  • For more details on EJS syntax, check out the upstream module documentation.
  • -
- -

Tips

- -

You can see a list of macros and how they are used on MDN on the macros dashboard.

- -

Advanced Features

- -

Beyond the basics, the KumaScript system offers some advanced features.

- -

Environment variables

- -

When the wiki makes a call to the KumaScript service, it passes along some context on the current document that KumaScript makes available to templates as variables:

- -
-
env.path
-
The path to the current wiki document
-
env.url
-
The full URL to the current wiki document
-
env.id
-
A short, unique ID for the current wiki document
-
env.files
-
An array of the files attached to the current wiki document; each object in the array is as described under File objects below
-
env.review_tags
-
An array of the review tags on the article ("technical", "editorial", etc.)
-
env.locale
-
The locale of the current wiki document
-
env.title
-
The title of the current wiki document
-
env.slug
-
The URL slug of the current wiki document
-
env.tags
-
An array list of tag names for the current wiki document
-
env.modified
-
Last modified timestamp for the current wiki document
-
env.cache_control
-
Cache-Control header sent in the request for the current wiki document, useful in deciding whether to invalidate caches
-
- -

File objects

- -

Each file object has the following fields:

- -
-
title
-
The attachment's title
-
description
-
A textual description of the current revision of the file
-
filename
-
The file's name
-
size
-
The size of the file in bytes
-
author
-
The username of the person who uploaded the file
-
mime
-
The MIME type of the file
-
url
-
The URL at which the file can be found
-
- -

Working with tag lists

- -

The env.tags and env.review_tags variables return arrays of tags. You can work with these in many ways, of course, but here are a couple of suggestions.

- -
Looking to see if a specific tag is set
- -

You can look to see if a specific tag exists on a page like this:

- -
if (env.tags.indexOf("tag") != −1) {
-  // The page has the tag "tag"
-}
-
- -
Iterating over all the tags on a page
- -

You can also iterate over all the tags on a page, like this:

- -
env.tag.forEach(function(tag) {
-  // do whatever you need to do, such as:
-  if (tag.indexOf("a") == 0) {
-    // this tag starts with "a" - woohoo!
-  }
-});
- -

APIs and Modules

- -

KumaScript offers some built-in methods and APIs for KumaScript macros. Macros can also use module.exports to export new API methods.

- -

API changes require updating the KumaScript engine or macros via a pull request to the KumaScript repository.

- -

Built-in methods

- -

This manually-maintained documentation is likely to fall out of date with the code. With that in mind, you can always check out the latest state of built-in APIs in the KumaScript source. But here is a selection of useful methods exposed to templates:

- -
-
md5(string)
-
Returns an MD5 hex digest of the given string.
-
template("name", ["arg0", "arg1", ..., "argN"])
-

Executes and returns the result of the named template with the given list of parameters.

-

Example: <%- template("warning", ["foo", "bar", "baz"]) %>.

-

Example using the domxref macro: <%- template("domxref", ["Event.bubbles", "bubbles"]) %>.

-

This is a JavaScript function. So, if one of the parameters is an arg variable like $2, do not put it in quotes. Like this: <%- template("warning", [$1, $2, "baz"]) %>. If you need to call another template from within a block of code, do not use <% ... %>. Example: myvar = "<li>" + template("LXRSearch", ["ident", "i", $1]) + "</li>";

-
require(name)
-

Loads another template as a module; any output is ignored. Anything assigned to module.exports in the template is returned.

-

Used in templates like so: <% var my_module = require('MyModule'); %>.

-
cacheFn(key, timeout, function_to_cache)
-
Using the given key and cache entry lifetime, cache the results of the given function. Honors the value of env.cache_control to invalidate cache on no-cache, which can be sent by a logged-in user hitting shift-refresh.
-
request
-
Access to mikeal/request, a library for making HTTP requests. Using this module in KumaScript templates is not yet very friendly, so you may want to wrap usage in module APIs that simplify things.
-
log.debug(string)
-
Outputs a debug message into the script log on the page (i.e. the big red box that usually displays errors).
-
- -

Built-in API modules

- -

There's only one API built in at the moment, in the kuma namespace. You can see the most up to date list of methods under kuma from the KumaScript source code, but here are a few:

- -
-
kuma.inspect(object)
-
Renders any JS object as a string, handy for use with log.debug(). See also: node.js util.inspect().
-
- -
-
kuma.htmlEscape(string)
-
Escapes the characters &, <, >, " to &amp, &lt;, &gt;, &quot;, respectively.
-
kuma.url
-
See also: node.js url module.
-
kuma.fetchFeed(url)
-
Fetch an RSS feed and parse it into a JS object. See also: InsertFeedLinkList
-
- -

Creating modules

- -

Using the built-in require() method, you can load a template as a module to share common variables and methods between templates. A module can be defined in a template like this:

- -
<%
-module.exports = {
-    add: function (a, b) {
-        return a + b;
-    }
-}
-%>
-
- -

Assuming this template is saved under https://github.com/mdn/kumascript/tree/master/macros as MathLib.ejs, you can use it in another template like so:

- -
<%
-var math_lib = require("MathLib");
-%>
-The result of 2 + 2 = <%= math_lib.add(2, 2) %>
-
- -

And, the output of this template will be:

- -
The result of 2 + 2 = 4
-
- -

Auto-loaded modules

- -

There are a set of modules editable as wiki templates that are automatically loaded and made available to every template. This set is defined in the configuration file for the KumaScript service - any changes to this requires an IT bug to edit configuration and a restart of the service.

- -

For the most part, these attempt to provide stand-ins for legacy DekiScript features to ease template migration. But, going forward, these can be used to share common variables and methods between templates:

- - - -

Note: You might notice that the DekiScript modules use a built-in method named buildAPI(), like so:

- -
<% module.exports = buildAPI({
-    StartsWith: function (str, sub_str) {
-        return (''+str).indexOf(sub_str) === 0;
-    }
-}); %>
-
- -

The reason for this is because DekiScript is case-insensitive when it comes to references to API methods, whereas JavaScript is strict about uppercase and lowercase in references. So, buildAPI() is a hack to try to cover common case variations in DekiScript calls found in legacy templates.

- -
-

With that in mind, please do not use buildAPI() in new modules.

-
- -

Tips and caveats

- -

Debugging

- -

A useful tip when debugging. You can use the log.debug() method to output text to the scripting messages area at the top of the page that's running your template. Note that you need to be really sure to remove these when you're done debugging, as they're visible to all users! To use it, just do something like this:

- -
<%- log.debug("Some text goes here"); %>
-
- -

You can, of course, create more complex output using script code if it's helpful.

- -

Caching

- -

KumaScript templates are heavily cached to improve performance. For the most part, this works great to serve up content that doesn't change very often. But, as a logged-in user, you have two options to force a page to be regenerated, in case you notice issues with scripting:

- -
    -
  • Hit Refresh in your browser. This causes KumaScript to invalidate its cache for the content on the current page by issuing a request with a Cache-Control: max-age=0 header.
  • -
  • Hit Shift-Refresh in your browser. This causes KumaScript to invalidate cache for the current page, as well as for any templates or content used by the current page by issuing a request with a Cache-Control: no-cache header.
  • -
- -

Using search keywords to open template pages

- -

When using templates, it's common to open the template's code in a browser window to review the comments at the top, which are used to document the template, its parameters, and how to use it properly. To quickly access templates, you can create a Firefox search keyword, which gives you a shortcut you can type in the URL box to get to a template more easily.

- -

To create a search keyword, open the bookmarks window by choosing "Show all bookmarks" in the Bookmarks menu, or by pressing Control-Shift-B (Command-Shift-B on Mac). Then from the utility ("Gear") menu in the Library window that appears, choose "New Bookmark...".

- -

This causes the bookmark editing dialog to appear. Fill that out as follows:

- -
-
Name
-
A suitable name for your search keyword; "Open MDN Template" is a good one.
-
Location
-
https://github.com/mdn/kumascript/blob/master/macros/%s
-
Tags {{optional_inline}}
-
A list of tags used to organize your bookmarks; these are entirely optional and what (if any) tags you use is up to you.
-
Keyword
-
The shortcut text you wish to use to access the template. Ideally, this should be something short and quick to type, such as simply "t" or "mdnt".
-
Description {{optional_inline}}
-
A suitable description explaining what the search keyword does.
-
- -

The resulting dialog looks something like this:

- -

- -

Then click the "Add" button to save your new search keyword. From then on, typing your keyword, then a space, then the name of a macro will open that macro in your current tab. So if you used "t" as the keyword, typing t ListSubpages will show you the page at {{TemplateLink("ListSubpages")}}.

- -

Cookbook

- -

This section will list examples of common patterns for templates used on MDN, including samples of legacy DekiScript templates and their new KumaScript equivalents.

- -

Force templates used on a page to be reloaded

- -

It bears repeating: To force templates used on a page to be reloaded after editing, hit Shift-Reload. Just using Reload by itself will cause the page contents to be regenerated, but using cached templates and included content. A Shift-Reload is necessary to invalidate caches beyond just the content of the page itself.

- -

Recovering from "Unknown Error"

- -

Sometimes, you'll see a scripting message like this when you load a page:

- -
Kumascript service failed unexpectedly: <class 'httplib.BadStatusLine'>
- -

This is probably a temporary failure of the KumaScript service. If you Refresh the page, the error may disappear. If that doesn't work, try a Shift-Refresh. If, after a few tries, the error persists - file an IT bug for Mozilla Developer Network to ask for an investigation.

- -

Broken wiki.languages() macros

- -

On some pages, you'll see a scripting error like this:

- -
Syntax error at line 436, column 461: Expected valid JSON object as the parameter of the preceding macro but...
-
- -

If you edit the page, you'll probably see a macro like this at the bottom of the page:

- -
\{{ wiki.languages({ "zh-tw": "zh_tw/Core_JavaScript_1.5_教學/JavaScript_概要", ... }) }}
-
- -

To fix the problem, just delete the macro. Or, replace the curly braces on either side with HTML comments <!-- --> to preserve the information, like so:

- -
<!-- wiki.languages({ "zh-tw": "zh_tw/Core_JavaScript_1.5_教學/JavaScript_概要", ... }) -->
-
- -

Because Kuma supports localization differently, these macros aren't actually needed any more. But, they've been left intact in case we need to revisit the relationships between localized pages. Unfortunately, it seems like migration has failed to convert some of them properly.

- -

Finding the Current Page's Language

- -

In KumaScript, the locale of the current document is exposed as an environment variable:

- -
var lang = env.locale;
-
- -

The env.locale variable should be reliable and defined for every document.

- -

Reading the contents of a page attachment

- -

You can read the contents of an attached file by using the mdn.getFileContent() function, like this:

- -
<%
-  var contents = mdn.getFileContent(fileUrl);
-  ... do stuff with the contents ...
-%>
-
- -

or

- -
<%-mdn.getFileContent(fileObject)%>
-
- -

In other words, you may specify either the URL of the file to read or as a file object. The file objects for a page can be accessed through the array env.files. So, for example, to embed the contents of the first file attached to the article, you can do this:

- -
<%-mdn.getFileContent(env.files[0])%>
-
- -
Note: You probably don't want to try to embed the contents of a non-text file this way, as the raw contents would be injected as text. This is meant to let you access the contents of text attachments.
- -

If the file isn't found, an empty string is returned. There is currently no way to tell the difference between an empty file and a nonexistent one. But if you're putting empty files on the wiki, you're doing it wrong.

- -

Localizing template content

- -

Templates are not translated like wiki pages, rather any single template might be used for any number of locales.

- -

So the main way to output content tailored to the current document locale is to pivot on the value of env.locale. There are many ways to do this, but a few patterns are common in the conversion of legacy DekiScript templates:

- -

If/else blocks in KumaScript

- -

The KumaScript equivalent of this can be achieved with simple if/else blocks, like so:

- -
<% if ("fr" == env.locale) { %>
-<%- template("CSSRef") %> « <a title="Référence_CSS/Extensions_Mozilla" href="/fr/docs/Référence_CSS/Extensions_Mozilla">Référence CSS:Extensions Mozilla</a>
-<% } else if ("ja" == env.locale) { %>
-<%- template("CSSRef") %> « <a title="CSS_Reference/Mozilla_Extensions" href="/ja/docs/CSS_Reference/Mozilla_Extensions">CSS リファレンス:Mozilla 拡張仕様</a>
-<% } else if ("pl" == env.locale) { %>
-<%- template("CSSRef") %> « <a title="Dokumentacja_CSS/Rozszerzenia_Mozilli" href="/pl/docs/Dokumentacja_CSS/Rozszerzenia_Mozilli">Dokumentacja CSS:Rozszerzenia Mozilli</a>
-<% } else if ("de" == env.locale) { %>
-<%- template("CSSRef") %> « <a title="CSS_Referenz/Mozilla_CSS_Erweiterungen" href="/de/docs/CSS_Referenz/Mozilla_CSS_Erweiterungen">CSS Referenz: Mozilla Erweiterungen</a>
-<% } else { %>
-<%- template("CSSRef") %> « <a title="CSS_Reference/Mozilla_Extensions" href="/en-US/docs/CSS_Reference/Mozilla_Extensions">CSS Reference:Mozilla Extensions</a>
-<% } %>
-
- -

Depending on what text editor is your favorite, you may be able to copy & paste from the browser-based editor and attack this pattern with a series of search/replace regexes to get you most of the way there.

- -

My favorite editor is MacVim, and a series of regexes like this does the bulk of the work with just a little manual clean up following:

- -
%s#<span#^M<span#g
-%s#<span lang="\(.*\)" .*>#<% } else if ("\1" == env.locale) { %>#g
-%s#<span class="script">template.Cssxref(#<%- template("Cssxref", [#
-%s#)</span> </span>#]) %>
-
- -

Your mileage may vary, and patterns change slightly from template to template. That's why the migration script was unable to just handle this automatically, after all.

- -

String variables and switch

- -

Rather than switch between full chunks of markup, you can define a set of strings, switch them based on locale, and then use them to fill in placeholders in a single chunk of markup:

- -
<%
-var s_title = 'Firefox for Developers';
-switch (env.locale) {
-    case 'de':
-        s_title = "Firefox für Entwickler";
-        break;
-    case 'fr':
-        s_title = "Firefox pour les développeurs";
-        break;
-    case 'es':
-        s_title = "Firefox para desarrolladores";
-        break;
-};
-%>
-<span class="title"><%= s_title %></span>
-
- -

Use mdn.localString()

- -

A recent addition to the MDN:Common module is mdn.localString(), used like this:

- -
<%
-var s_title = mdn.localString({
-  "en-US": "Firefox for Developers",
-  "de": "Firefox für Entwickler",
-  "es": "Firefox para desarrolladores"
-});
-%>
-<span class="title"><%= s_title %></span>
-
- -

This is more concise than the switch statement, and may be a better choice where a single string is concerned. However, if many strings need to be translated (e.g., as in CSSRef), a switch statement might help keep all the strings grouped by locale and more easily translated that way.

- -

When the object does not have the appropriate locale, the value of "en-US" is used as the initial value.

- -

See also

- - diff --git a/files/pt-br/mdn/tools/kumascript/index.md b/files/pt-br/mdn/tools/kumascript/index.md new file mode 100644 index 00000000000000..71d6e54d42ddbb --- /dev/null +++ b/files/pt-br/mdn/tools/kumascript/index.md @@ -0,0 +1,516 @@ +--- +title: KumaScript +slug: MDN/Tools/KumaScript +tags: + - Guide + - Kuma + - KumaScript + - MDN Meta + - NeedsContent + - NeedsTranslation + - Site-wide + - Tools + - TopicStub +translation_of: MDN/Tools/KumaScript +--- +{{MDNSidebar}} + +## Overview + +On the [Kuma](/pt-BR/docs/MDN/Kuma) platform that powers MDN, the template system for automating aspects of content on the wiki is called [KumaScript](https://github.com/mdn/kumascript). KumaScript is powered by server-side JavaScript, implemented using [Node.js](https://nodejs.org/en/). This article provides basic information on how to use KumaScript. + +For a detailed overview and Q\&A of KumaScript, watch the MDN dev team's [KumaScript Fireside Chat](https://vreplay.mozilla.com/replay/showRecordDetails.html?sortBy=date&viewCount=1¤tPage=1&groupBy=combo&roomFilter=&usernameFilter=&searchFilter=&usernameFullFilter=&myManager=-1&adminManager=0&webCast=0&command=&recId=1082&auxMessage=&auxMessage1=&lang=en&langChanged=&tenantFilter=&securityTab=) (the meeting starts at 10 minutes into the video). KumaScript replaced DekiScript, which was the template language for MindTouch, the previous platform used by MDN. + +### What is KumaScript? + +- A way to reuse and localize content that appears repeatedly between documents (e.g., compatibility labels, section navigation, warning banners). +- A way to build documents out of content pulled from other documents. +- A way to fetch and include content from other web sites and services (e.g., Bugzilla). + +### What KumaScript is not + +- KumaScript does not support interactive scripting of the kind that can accept form submissions. +- KumaScript does not have access to a database, files, or any other way to store information persistently. +- KumaScript does not support site personalization based on the user currently logged in. +- KumaScript does not have access to user information, only to the content and metadata of a wiki page being viewed. + +## Basics + +KumaScript is used on MDN in [embedded JavaScript templates](https://github.com/visionmedia/ejs). These templates can be invoked in document content by any MDN author, through the use of macros. + +A script in KumaScript is a _template_, and each template is a file in [the macros directory of the KumaScript repository](https://github.com/mdn/kumascript/tree/master/macros) on Github. A [template](https://github.com/mdn/kumascript/blob/master/macros/hello.ejs "hello.ejs") looks like this: + +``` +<% for (var i = 0; i < $0; i++) { %> +Hello #<%= i %> +<% } %> +``` + +Invoking a template is done with a _macro_, which can be used anywhere in any wiki content. A macro looks like this: + +``` +\{{ hello("3") }} +``` + +The output of the macro looks like this: + +``` +Hello #0 +Hello #1 +Hello #2 +``` + +### Macro syntax + +KumaScript templates are invoked in document content with macros, like this: + +``` +\{{ templateName("arg0", "arg1", ..., "argN") }} +``` + +Macro syntax consists of these rules: + +- Macros start and end with `\{{ and \}}` characters. +- The first part of the macro is the name of a template. The lowercase value of this name should match the lowercase value of one of the filenames under [the macros directory of KumaScript](https://github.com/mdn/kumascript/tree/master/macros). +- A template can accept parameters, and this parameter list starts and ends with parentheses. +- All non-numeric parameters must be in quotes. Numbers can be left unquoted. + +#### Using JSON as a macro parameter + +As a semi-experimental feature (not guaranteed to work), you can supply a JSON object for the first and only parameter, like so: + +``` +\{{ templateName({ "Alpha":"one", "Beta":["a","b","c"], "Foo":"http:\/\/mozilla.org\/" }) }} +``` + +The data from this macro is available in template code as an object in the `$0` argument (e.g., `$0.Alpha`, `$0.Beta`, `$0.Foo`). This also allows you to express complex data structures in macro parameters that are hard or impossible to do with a simple list of parameters. + +Note that this parameter style is very picky — it must adhere to [JSON syntax](http://json.org/) exactly, which has some requirements about escaping characters that are easy to miss (e.g., all forward slashes are escaped). When in doubt, [try running your JSON through a validator](http://jsonlint.com/). + +#### How to write "\\{{" in text + +

Since the character sequence "\{{" is used to indicate the start of a macro, this can be troublesome if you actually just want to use "\{{" and "}}" in a page. It will probably produce `DocumentParsingError` messages.In this case, you can escape the first brace with a backslash, like so: `\\{` + +### Template syntax + +Each KumaScript template is a file under [the macros directory of KumaScript](https://github.com/mdn/kumascript/tree/master/macros). You create and edit these files as you would the files of any open-source project on GitHub (see [the KumaScript README](https://github.com/mdn/kumascript) for more information). + +KumaScript templates are processed by an [embedded JavaScript template engine](https://github.com/visionmedia/ejs) with a few simple rules: + +- Within a template, the parameters passed in from the macro are available as the variables `$0`, `$1`, `$2`, and so on. The entire list of parameters is also available in a template as the variable `arguments`. +- Most text is treated as output and included in the output stream. +- JavaScript variables and expressions can be inserted into the output stream with these blocks: + + - `<%= expr %>` — the value of a JavaScript expression is escaped for HTML before being included in output (e.g., characters like `<` and `>` are turned into `<` and `>`). + - `<%- expr %>` — the value of a JavaScript expression is included in output without any escaping. (Use this if you want to dynamically build markup or use the results of another template that may include markup.) + - It is an error to include semicolons inside these blocks. + +- Anything inside a `<% %>` block is interpreted as JavaScript. This can include loops, conditionals, etc. +- Nothing inside a `<% %>` block can ever contribute to the output stream. But, you can transition from JS mode to output mode using `<% %>`—for example: + + ``` + <% for (var i = 0; i < $0; i++) { %> + Hello #<%= i %> + <% } %> + ``` + + Note how the JavaScript code is contained in `<% ... %>`, and output happens in the space between `%> ... <%`. The `for` loop in JS can begin with one `<% %>` block, transition to output mode, and finish up in a second `<% %>` JS block. + +- For more details on EJS syntax, [check out the upstream module documentation](https://github.com/visionmedia/ejs). + +### Tips + +You can see a list of macros and how they are used on MDN on the [macros dashboard](/en-US/dashboards/macros). + +## Advanced Features + +Beyond the basics, the KumaScript system offers some advanced features. + +### Environment variables + +When the wiki makes a call to the KumaScript service, it passes along some context on the current document that KumaScript makes available to templates as variables: + +- `env.path` + - : The path to the current wiki document +- `env.url` + - : The full URL to the current wiki document +- `env.id` + - : A short, unique ID for the current wiki document +- `env.files` + - : An array of the files attached to the current wiki document; each object in the array is as described under [File objects](#file_objects) below +- `env.review_tags` + - : An array of the review tags on the article ("technical", "editorial", etc.) +- `env.locale` + - : The locale of the current wiki document +- `env.title` + - : The title of the current wiki document +- `env.slug` + - : The URL slug of the current wiki document +- `env.tags` + - : An array list of tag names for the current wiki document +- `env.modified` + - : Last modified timestamp for the current wiki document +- `env.cache_control` + - : `Cache-Control` header sent in the request for the current wiki document, useful in deciding whether to invalidate caches + +#### File objects + +Each file object has the following fields: + +- `title` + - : The attachment's title +- `description` + - : A textual description of the current revision of the file +- `filename` + - : The file's name +- `size` + - : The size of the file in bytes +- `author` + - : The username of the person who uploaded the file +- `mime` + - : The MIME type of the file +- `url` + - : The URL at which the file can be found + +#### Working with tag lists + +The `env.tags` and `env.review_tags` variables return arrays of tags. You can work with these in many ways, of course, but here are a couple of suggestions. + +##### Looking to see if a specific tag is set + +You can look to see if a specific tag exists on a page like this: + +```js +if (env.tags.indexOf("tag") != −1) { + // The page has the tag "tag" +} +``` + +##### Iterating over all the tags on a page + +You can also iterate over all the tags on a page, like this: + +```js +env.tag.forEach(function(tag) { + // do whatever you need to do, such as: + if (tag.indexOf("a") == 0) { + // this tag starts with "a" - woohoo! + } +}); +``` + +### APIs and Modules + +KumaScript offers some built-in methods and APIs for KumaScript macros. Macros can also use `module.exports` to export new API methods. + +API changes require updating the KumaScript engine or macros via a pull request to the [KumaScript repository](https://github.com/mdn/kumascript). + +#### Built-in methods + +This manually-maintained documentation is likely to fall out of date with the code. With that in mind, [you can always check out the latest state of built-in APIs in the KumaScript source](https://github.com/mdn/kumascript/blob/master/lib/kumascript/api.js#L175). But here is a selection of useful methods exposed to templates: + +- `md5(string)` + - : Returns an MD5 hex digest of the given string. +- `template("name", ["arg0", "arg1", ..., "argN"])` + + - : Executes and returns the result of the named template with the given list of parameters. + + Example: `<%- template("warning", ["foo", "bar", "baz"]) %>`. + + Example using the `domxref` macro: `<%- template("domxref", ["Event.bubbles", "bubbles"]) %>`. + + This is a JavaScript function. So, if one of the parameters is an arg variable like $2, do not put it in quotes. Like this: `<%- template("warning", [$1, $2, "baz"]) %>`. If you need to call another template from within a block of code, do not use `<%` ... `%>`. Example: `myvar = "

  • " + template("LXRSearch", ["ident", "i", $1]) + "
  • ";` + +- `require(name)` + + - : Loads another template as a module; any output is ignored. Anything assigned to `module.exports` in the template is returned. + + Used in templates like so: `<% var my_module = require('MyModule'); %>`. + +- `cacheFn(key, timeout, function_to_cache)` + - : Using the given key and cache entry lifetime, cache the results of the given function. Honors the value of `env.cache_control` to invalidate cache on `no-cache`, which can be sent by a logged-in user hitting shift-refresh. +- `request` + - : Access to [`mikeal/request`](https://github.com/mikeal/request), a library for making HTTP requests. Using this module in KumaScript templates is not yet very friendly, so you may want to wrap usage in module APIs that simplify things. +- `log.debug(string)` + - : Outputs a debug message into the script log on the page (i.e. the big red box that usually displays errors). + +#### Built-in API modules + +There's only one API built in at the moment, in the `kuma` namespace. You can see the most up to date list of methods under `kuma` from [the KumaScript source code](https://github.com/mdn/kumascript/blob/master/lib/kumascript/api.js#L74), but here are a few: + +- `kuma.inspect(object)` + - : Renders any JS object as a string, handy for use with `log.debug()`. See also: [node.js `util.inspect()`](http://nodejs.org/api/util.html#util_util_inspect_object_options). + + + +- `kuma.htmlEscape(string)` + - : Escapes the characters `&, <, >, "` to `&, <, >, "`, respectively. +- `kuma.url` + - : See also: [node.js `url` module](http://nodejs.org/api/url.html). +- `kuma.fetchFeed(url)` + - : Fetch an RSS feed and parse it into a JS object. See also: [`InsertFeedLinkList`](https://github.com/mdn/kumascript/blob/master/macros/InsertFeedLinkList.ejs) + +#### Creating modules + +Using the built-in `require()` method, you can load a template as a module to share common variables and methods between templates. A module can be defined in a template like this: + +``` +<% +module.exports = { + add: function (a, b) { + return a + b; + } +} +%> +``` + +Assuming this template is saved under as `MathLib.ejs`, you can use it in another template like so: + +``` +<% +var math_lib = require("MathLib"); +%> +The result of 2 + 2 = <%= math_lib.add(2, 2) %> +``` + +And, the output of this template will be: + +``` +The result of 2 + 2 = 4 +``` + +#### Auto-loaded modules + +There are a set of modules editable as wiki templates that are automatically loaded and made available to every template. This set is defined in the configuration file for the KumaScript service - any changes to this requires an IT bug to edit configuration and a restart of the service. + +For the most part, these attempt to provide stand-ins for legacy DekiScript features to ease template migration. But, going forward, these can be used to share common variables and methods between templates: + +- `mdn.*` - [MDN-Common](https://github.com/mdn/kumascript/blob/master/macros/MDN-Common.ejs "MDN:Common") +- `Page.*` - [DekiScript-Page](https://github.com/mdn/kumascript/blob/master/macros/DekiScript-Page.ejs "DekiScript:Page") +- `String.*` - [DekiScript-String](https://github.com/mdn/kumascript/blob/master/macros/DekiScript-String.ejs "DekiScript:String") +- `Uri.*` - [DekiScript-Uri](https://github.com/mdn/kumascript/blob/master/macros/DekiScript-Uri.ejs "DekiScript:Uri") +- `Web.*` - [DekiScript-Web](https://github.com/mdn/kumascript/blob/master/macros/DekiScript-Web.ejs "DekiScript:Web") +- `Wiki.*` - [DekiScript-Wiki](https://github.com/mdn/kumascript/blob/master/macros/DekiScript-Wiki.ejs "DekiScript:Wiki") + +**Note:** You might notice that the DekiScript modules use a built-in method named `buildAPI()`, like so: + +``` +<% module.exports = buildAPI({ + StartsWith: function (str, sub_str) { + return (''+str).indexOf(sub_str) === 0; + } +}); %> +``` + +The reason for this is because DekiScript is case-insensitive when it comes to references to API methods, whereas JavaScript is strict about uppercase and lowercase in references. So, `buildAPI()` is a hack to try to cover common case variations in DekiScript calls found in legacy templates. + +> **Nota:** With that in mind, please do not use `buildAPI()` in new modules. + +## Tips and caveats + +### Debugging + +A useful tip when debugging. You can use the `log.debug()` method to output text to the scripting messages area at the top of the page that's running your template. Note that you need to be really sure to remove these when you're done debugging, as they're visible to all users! To use it, just do something like this: + +``` +<%- log.debug("Some text goes here"); %> +``` + +You can, of course, create more complex output using script code if it's helpful. + +### Caching + +KumaScript templates are heavily cached to improve performance. For the most part, this works great to serve up content that doesn't change very often. But, as a logged-in user, you have two options to force a page to be regenerated, in case you notice issues with scripting: + +- Hit Refresh in your browser. This causes KumaScript to invalidate its cache for the content on the current page by issuing a request with a `Cache-Control: max-age=0` header. +- Hit Shift-Refresh in your browser. This causes KumaScript to invalidate cache for the current page, as well as for any templates or content used by the current page by issuing a request with a `Cache-Control: no-cache` header. + +### Using search keywords to open template pages + +When using templates, it's common to open the template's code in a browser window to review the comments at the top, which are used to document the template, its parameters, and how to use it properly. To quickly access templates, you can create a Firefox [search keyword](http://kb.mozillazine.org/Using_keyword_searches), which gives you a shortcut you can type in the URL box to get to a template more easily. + +To create a search keyword, open the bookmarks window by choosing "Show all bookmarks" in the Bookmarks menu, or by pressing Control-Shift-B (Command-Shift-B on Mac). Then from the utility ("Gear") menu in the Library window that appears, choose "New Bookmark...". + +This causes the bookmark editing dialog to appear. Fill that out as follows: + +- Name + - : A suitable name for your search keyword; "Open MDN Template" is a good one. +- Location + + - : + + https://github.com/mdn/kumascript/blob/master/macros/%s + +- Tags {{optional_inline}} + - : A list of tags used to organize your bookmarks; these are entirely optional and what (if any) tags you use is up to you. +- Keyword + - : The shortcut text you wish to use to access the template. Ideally, this should be something short and quick to type, such as simply "t" or "mdnt". +- Description {{optional_inline}} + - : A suitable description explaining what the search keyword does. + +The resulting dialog looks something like this: + +![](https://mdn.mozillademos.org/files/14432/Screen%20Shot%202016-11-28%20at%203.08.39%20PM.png) + +Then click the "Add" button to save your new search keyword. From then on, typing your keyword, then a space, then the name of a macro will open that macro in your current tab. So if you used "t" as the keyword, typing t ListSubpages will show you the page at {{TemplateLink("ListSubpages")}}. + +## Cookbook + +This section will list examples of common patterns for templates used on MDN, including samples of legacy DekiScript templates and their new KumaScript equivalents. + +### Force templates used on a page to be reloaded + +It bears repeating: To force templates used on a page to be reloaded after editing, hit Shift-Reload. Just using Reload by itself will cause the page contents to be regenerated, but using cached templates and included content. A Shift-Reload is necessary to invalidate caches beyond just the content of the page itself. + +### Recovering from "Unknown Error" + +Sometimes, you'll see a scripting message like this when you load a page: + +``` +Kumascript service failed unexpectedly: +``` + +This is probably a temporary failure of the KumaScript service. If you Refresh the page, the error may disappear. If that doesn't work, try a Shift-Refresh. If, after a few tries, the error persists - [file an IT bug](https://bugzilla.mozilla.org/enter_bug.cgi?product=mozilla.org&format=itrequest) for Mozilla Developer Network to ask for an investigation. + +### Broken wiki.languages() macros + +On some pages, you'll see a scripting error like this: + +``` +Syntax error at line 436, column 461: Expected valid JSON object as the parameter of the preceding macro but... +``` + +If you edit the page, you'll probably see a macro like this at the bottom of the page: + +``` +\{{ wiki.languages({ "zh-tw": "zh_tw/Core_JavaScript_1.5_教學/JavaScript_概要", ... }) }} +``` + +To fix the problem, just delete the macro. Or, replace the curly braces on either side with HTML comments `` to preserve the information, like so: + +``` + +``` + +Because Kuma supports localization differently, these macros aren't actually needed any more. But, they've been left intact in case we need to revisit the relationships between localized pages. Unfortunately, it seems like migration has failed to convert some of them properly. + +### Finding the Current Page's Language + +In KumaScript, the locale of the current document is exposed as an environment variable: + +``` +var lang = env.locale; +``` + +The `env.locale` variable should be reliable and defined for every document. + +### Reading the contents of a page attachment + +You can read the contents of an attached file by using the `mdn.getFileContent()` function, like this: + +``` +<% + var contents = mdn.getFileContent(fileUrl); + ... do stuff with the contents ... +%> +``` + +or + +``` +<%-mdn.getFileContent(fileObject)%> +``` + +In other words, you may specify either the URL of the file to read or as a file object. The file objects for a page can be accessed through the array `env.files`. So, for example, to embed the contents of the first file attached to the article, you can do this: + +``` +<%-mdn.getFileContent(env.files[0])%> +``` + +> **Nota:** You probably don't want to try to embed the contents of a non-text file this way, as the raw contents would be injected as text. This is meant to let you access the contents of text attachments. + +If the file isn't found, an empty string is returned. There is currently no way to tell the difference between an empty file and a nonexistent one. But if you're putting empty files on the wiki, you're doing it wrong. + +### Localizing template content + +Templates are not translated like wiki pages, rather any single template might be used for any number of locales. + +So the main way to output content tailored to the current document locale is to pivot on the value of `env.locale`. There are many ways to do this, but a few patterns are common in the conversion of legacy DekiScript templates: + +#### If/else blocks in KumaScript + +The KumaScript equivalent of this can be achieved with simple if/else blocks, like so: + +``` +<% if ("fr" == env.locale) { %> +<%- template("CSSRef") %> « Référence CSS:Extensions Mozilla +<% } else if ("ja" == env.locale) { %> +<%- template("CSSRef") %> « CSS リファレンス:Mozilla 拡張仕様 +<% } else if ("pl" == env.locale) { %> +<%- template("CSSRef") %> « Dokumentacja CSS:Rozszerzenia Mozilli +<% } else if ("de" == env.locale) { %> +<%- template("CSSRef") %> « CSS Referenz: Mozilla Erweiterungen +<% } else { %> +<%- template("CSSRef") %> « CSS Reference:Mozilla Extensions +<% } %> +``` + +Depending on what text editor is your favorite, you may be able to copy & paste from the browser-based editor and attack this pattern with a series of search/replace regexes to get you most of the way there. + +My favorite editor is MacVim, and a series of regexes like this does the bulk of the work with just a little manual clean up following: + +``` +%s##<% } else if ("\1" == env.locale) { %>#g +%s#template.Cssxref(#<%- template("Cssxref", [# +%s#) #]) %> +``` + +Your mileage may vary, and patterns change slightly from template to template. That's why the migration script was unable to just handle this automatically, after all. + +#### String variables and switch + +Rather than switch between full chunks of markup, you can define a set of strings, switch them based on locale, and then use them to fill in placeholders in a single chunk of markup: + +``` +<% +var s_title = 'Firefox for Developers'; +switch (env.locale) { + case 'de': + s_title = "Firefox für Entwickler"; + break; + case 'fr': + s_title = "Firefox pour les développeurs"; + break; + case 'es': + s_title = "Firefox para desarrolladores"; + break; +}; +%> +<%= s_title %> +``` + +#### Use `mdn.localString()` + +A recent addition to the `MDN:Common` module is `mdn.localString()`, used like this: + +``` +<% +var s_title = mdn.localString({ + "en-US": "Firefox for Developers", + "de": "Firefox für Entwickler", + "es": "Firefox para desarrolladores" +}); +%> +<%= s_title %> +``` + +This is more concise than the switch statement, and may be a better choice where a single string is concerned. However, if many strings need to be translated (e.g., as in [CSSRef](https://github.com/mdn/kumascript/blob/master/macros/CSSRef.ejs "CSSRef")), a switch statement might help keep all the strings grouped by locale and more easily translated that way. + +When the object does not have the appropriate locale, the value of "en-US" is used as the initial value. + +## See also + +- [Getting started with Kuma](http://kuma.readthedocs.io/en/latest/ "Getting started with Kuma") +- [KumaScript reference](https://github.com/mdn/kumascript "Project:en/KumaScript reference") +- [Kuma wiki](https://wiki.mozilla.org/MDN/Kuma) diff --git a/files/pt-br/mdn/tools/kumascript/troubleshooting/index.html b/files/pt-br/mdn/tools/kumascript/troubleshooting/index.html deleted file mode 100644 index 6a432f6377737b..00000000000000 --- a/files/pt-br/mdn/tools/kumascript/troubleshooting/index.html +++ /dev/null @@ -1,64 +0,0 @@ ---- -title: Solucionando problemas de erros de KumaScript -slug: MDN/Tools/KumaScript/Troubleshooting -tags: - - Erros - - Ferramentas - - Guía - - KumaScript - - MDN Meta -translation_of: MDN/Tools/KumaScript/Troubleshooting -original_slug: MDN/Tools/KumaScript/Solucionando_problemas_de_erros_de_KumaScript ---- -
    {{MDNSidebar}}
    -

    Erros de KumaScript aparecendo numa página podem ser muito desagradáveis aos leitores, mostrando grandes e medonhas caixas vermelhas, mas felizmente qualquer pessoa com uma conta MDN pode editar um documento e consertar tais tipos de erros. Quando uma página possui algum erro, ela é adicionada na lista de documentos com erros. Editores do site passam por essa lista regularmente para achar e consertar erros. Este artigo detalha os quatro tipos de erros de KumaScript, e alguns passos que você pode fazer para consertá-los.

    -
    - -

    Erro tipo DocumentParsingError

    - -

    DocumentParsingError erros aparecem quando o KumaScript tem problemas para entender alguma coisa no próprio documento. A causa mais comum é um erro de sintaxe em alguma macro.

    - -

    Verifique:

    - -
    -
    Uso de chaves sem a intenção de chamar uma macro.
    -
    Se você pretende escrever \{ num documento sem usar macro, você pode escapar as chaves com uma barra invertida \ da seguinte forma: \\{
    -
    Uso de caractére especial nos parâmetros de uma macro.
    -
    Se você pretende usar aspas duplas " ou barra invertida \ dentro de algum parâmetro para uma macro, eles podem ser escapados através de uma barra invertida \ da seguinte forma: \\ or \"
    -
    Falta de vírgula para separar parâmetros de macro.
    -
    Parâmetros de macro precisam ser separados por uma vírgula (,) exceto no último parâmetro (ou se for único); por exemplo \{\{compat("html.elements.link", 2)}}.
    -
    Tags HTML aparecendo dentro de uma chamada de macro
    -
    Se você aplicar estilos a uma macro, geralmente não irá funcionar, pois uma tag </code> pode aparecer dentro do código fonte da macro, causado erros de sintaxe na macro. Verifique a visão de código-fonte para ver o código que foi gerado, e remova qualquer estilo desnecessário.
    -
    - -
      -
    - -

    Erro tipo TemplateLoadingError

    - -

    TemplateLoadingError erros aparecendo quando um KumaScript tem problemas de encontrar qual macro incluir numa página.

    - -

    Verifique:

    - -
    -
    Nomes com erro ortográfico ou macros renomeadas.
    -
    Você pode ver a lista de macros conhecidas no Repositório do Github.
    -
    - -
    -

    Dica: Você pode tornar mais rápido e fácil avançar para uma macro específica adicionando uma busca por palavras-chave no Firefox. Veja {{SectionOnPage("/en-US/docs/MDN/Contribute/Tools/KumaScript", "Using search keywords to open template pages")}} para um guia passo-a-passo de criar uma busca para isso.

    -
    - -

    Erro tipo TemplateExecutionError

    - -

    TemplateExecutionError erros aparecem quando KumaScript encontra erros na macro. Esses erros só podem ser consertados por usuários administradores e precisam ser reportados como bugs.

    - -

    Antes de reportar um erro, verifique se ele ainda não foi consertado. Você pode fazer isso forçando o KumaScript a te dar uma cópia fresca da página segurando Shift enquanto atualiza a página (Shift + Ctrl + R no Windows/Linux, Shift + Cmd + R no Mac).

    - -

    Se os erros persistirem, reporte um bug, incluindo a URL da página e o texto do erro.

    - -

    Erro tipo Error & Unknown

    - -

    Este é um tipo de erro que aparece quando o erro não pertence aos outros tipos de erros.

    - -

    Verifique se existe alguma solução de contorno ou correção para o problema e reporte bugs persistentes como descrito em TemplateExecutionError.

    diff --git a/files/pt-br/mdn/tools/kumascript/troubleshooting/index.md b/files/pt-br/mdn/tools/kumascript/troubleshooting/index.md new file mode 100644 index 00000000000000..e69c0078d53bd3 --- /dev/null +++ b/files/pt-br/mdn/tools/kumascript/troubleshooting/index.md @@ -0,0 +1,57 @@ +--- +title: Solucionando problemas de erros de KumaScript +slug: MDN/Tools/KumaScript/Troubleshooting +tags: + - Erros + - Ferramentas + - Guía + - KumaScript + - MDN Meta +translation_of: MDN/Tools/KumaScript/Troubleshooting +original_slug: MDN/Tools/KumaScript/Solucionando_problemas_de_erros_de_KumaScript +--- +{{MDNSidebar}} + +Erros de [KumaScript](/pt-BR/docs/MDN/Kuma/Introduction_to_KumaScript) aparecendo numa página podem ser muito desagradáveis aos leitores, mostrando grandes e medonhas caixas vermelhas, mas felizmente qualquer pessoa com uma conta MDN pode editar um documento e consertar tais tipos de erros. Quando uma página possui algum erro, ela é adicionada na lista de [documentos com erros](/docs/with-errors). Editores do site passam por essa lista regularmente para achar e consertar erros. Este artigo detalha os quatro tipos de erros de KumaScript, e alguns passos que você pode fazer para consertá-los. + +## Erro tipo _DocumentParsingError_ + +`DocumentParsingError` erros aparecem quando o KumaScript tem problemas para entender alguma coisa no próprio documento. A causa mais comum é um erro de sintaxe em alguma [macro](/pt-BR/docs/MDN/Contribute/Content/Macros). + +Verifique: + +- Uso de chaves sem a intenção de chamar uma macro. + - : Se você pretende escrever \\{ num documento sem usar macro, você pode escapar as chaves com uma barra invertida \ da seguinte forma: `\\{` +- Uso de caractére especial nos parâmetros de uma macro. + - : Se você pretende usar aspas duplas " ou barra invertida \ dentro de algum parâmetro para uma macro, eles podem ser escapados através de uma barra invertida \ da seguinte forma: `\\` or `\"` +- Falta de vírgula para separar parâmetros de macro. + - : Parâmetros de macro precisam ser separados por uma vírgula (,) exceto no último parâmetro (ou se for único); por exemplo `\{\{compat("html.elements.link", 2)}}`. +- Tags HTML aparecendo dentro de uma chamada de macro + - : Se você aplicar estilos a uma macro, geralmente não irá funcionar, pois uma tag `
    ` pode aparecer dentro do código fonte da macro, causado erros de sintaxe na macro. Verifique a visão de código-fonte para ver o código que foi gerado, e remova qualquer estilo desnecessário. + + + +## Erro tipo _TemplateLoadingError_ + +`TemplateLoadingError` erros aparecendo quando um KumaScript tem problemas de encontrar qual [macro](/pt-BR/docs/MDN/Contribute/Content/Macros) incluir numa página. + +Verifique: + +- Nomes com erro ortográfico ou macros renomeadas. + - : Você pode ver a lista de macros conhecidas no [Repositório do Github](https://github.com/mdn/kumascript/tree/master/macros). + +> **Nota:** **Dica:** Você pode tornar mais rápido e fácil avançar para uma macro específica adicionando uma [busca por palavras-chave](http://kb.mozillazine.org/Using_keyword_searches) no Firefox. Veja {{SectionOnPage("/en-US/docs/MDN/Contribute/Tools/KumaScript", "Using search keywords to open template pages")}} para um guia passo-a-passo de criar uma busca para isso. + +## Erro tipo _TemplateExecutionError_ + +`TemplateExecutionError` erros aparecem quando KumaScript encontra erros na macro. Esses erros só podem ser consertados por usuários administradores e precisam ser reportados como _bugs_. + +Antes de reportar um erro, verifique se ele ainda não foi consertado. Você pode fazer isso forçando o KumaScript a te dar uma cópia fresca da página segurando Shift enquanto atualiza a página (Shift + Ctrl + R no Windows/Linux, Shift + Cmd + R no Mac). + +Se os erros persistirem, [reporte um _bug_](https://bugzilla.mozilla.org/enter_bug.cgi?product=Mozilla_Developer_Network&component=General#h=detail|bug), incluindo a URL da página e o texto do erro. + +## Erro tipo _Error_ & _Unknown_ + +Este é um tipo de erro que aparece quando o erro não pertence aos outros tipos de erros. + +Verifique se existe alguma solução de contorno ou correção para o problema e reporte _bugs_ persistentes como descrito em [TemplateExecutionError](#TemplateExecutionError). diff --git a/files/pt-br/mdn/writing_guidelines/howto/creating_moving_deleting/index.html b/files/pt-br/mdn/writing_guidelines/howto/creating_moving_deleting/index.html deleted file mode 100644 index 01f74966afe404..00000000000000 --- a/files/pt-br/mdn/writing_guidelines/howto/creating_moving_deleting/index.html +++ /dev/null @@ -1,148 +0,0 @@ ---- -title: Criando e editando páginas -slug: MDN/Writing_guidelines/Howto/Creating_moving_deleting -tags: - - Colaborando - - Colaborar - - Contribuindo - - Criando - - Editando - - MDN - - nova pagina -translation_of: MDN/Contribute/Howto/Create_and_edit_pages -original_slug: MDN/Contribute/Howto/Create_and_edit_pages ---- -
    {{MDNSidebar}}
    - -

    As duas tarefas mais básicas sobre MDN que quase todo contribuinte MDN irá eventualmente executar são para editar uma página já existente ou criar uma nova. Este artigo aborda os conceitos básicos de como fazer cada uma delas.

    - -

    Editando uma página existente

    - -

    É fácil editar:

    - -
      -
    • Clique no botão editar próximo ao topo na direita no canto da página.
    • -
    • A página recarregará com opções de formatação, assim, você pode adicionar ou deletar informação diretamente na página.
    • -
    • Você pode adicionar parágrafos, deletar texto, inserir cabeçalhos, e mais das tarefas básicas que envolvem edição de textos.
    • -
    - -

    Ver mudanças

    - -

    Para ver como suas mudanças ficaram:

    - -
      -
    • Clique no botão "Visualizar mudanças" (dentro da função de editar) acima do título da página.
    • -
    • Isso abre uma páǵina de pré-visualização que inclui sua revisão em uma nova janela ou aba.
    • -
    • Cada vez que você clica nesse botão, ele recarrega sua página de pré-visualização com as últimas mudanças feitas.
    • -
    - -

    Tenha cuidado! Pré-visualizar uma página não salva as alterações, sendo assim, se lembre de não fechar a página que você está editando sem salvar o conteúdo.

    - -

    Revisão de comentário

    - -

    Depois que você pré-visualizou suas mudanças, você deve querer salvar sua revisão. Antes de salvar, procure pela caixa de comentários de revisão abaixo da sessão de título da página e deixe um comentário para informar a outros voluntários o que você mudou e o motivo. Por exemplo, você pode ter adicionado uma nova sessão, mudado algumas palavras para fazer a terminologia mais consistente, reescrito um parágrafo para esclarecer o idioma, ou removido informação porque é redundante.

    - -

    Tags

    - -

    Você pode adicionar ou remover tags que descrevam o conteúdo da página. Veja como adicionar tags às páginas corretamente para mais informações em que as tags se aplicam.

    - -

    Precisa de revisão?

    - -

    Se você quiser que um contribuidor experiente revise suas edições, você pode requisitar uma revisão técnica (para códigos, APIs, ou tecnologias), uma revisão editorial (textual, de gramática ou conteúdo), ou uma revisão de template (para código KumaScript) se certificando que a caixa está marcada, antes que você salve.

    - -

    Anexar arquivos

    - -

    Se você quiser anexar um arquivo a uma página para adicionar uma ilustração ou tornar o conteúdo mais claro, o anexo pode ir no final da página.

    - -

    Salve, descarte ou continue editando

    - -

    Quando você termina uma edição com seu preview, você pode salvar seu trabalho e comentários clicando no botão verde "Salvar alterações" à direita do título da página. Se você mudar de ideia, pode descartar suas edições clicando no botão vermelho "Descartar alterações", também à direita do título da página.

    - -

    Pressionar Enter no comentário da revisão é equivalente a clicar em "Salvar e continuar editando".

    - -

    Criando uma nova página

    - -

    Se você não sabe onde colocar seu artigo, não se preocupe sobre isso! Coloque-o em qualquer local e nós vamos encontrá-lo e movê-lo para onde ele pertence, ou mesclá-lo em conteúdo existente se for mais apropriado. Você também não precisa se preocupar sobre deixar tudo perfeito. Nós temos gnomos ajudantes felizes que vão ajudá-lo deixar seu conteúdo lindo.

    - -

    Há algumas maneiras de criar uma nova página:

    - - - - - -

    Como na maioria das wikis, na MDN é possível criar links para uma página que ainda não existe. Por exemplo, um autor pode criar uma lista de todos os membros de uma API, antes de criar as páginas para esses membros. Na MDN, links para página inexistentes geralmente são exibidos em vermelho.

    - -

    Para criar um link para uma "página inexistente":

    - -
      -
    1. Certifique-se que você está logado na MDN. (Se você não estiver, vai receber um erro 404).
    2. -
    3. Clique no link "página inexistente". O MDN Editor UI abrirá, pronto para você criar a página inexistente.
    4. -
    5. Escreva o conteúdo da página e salve-a.
    6. -
    - - - -

    Para criar uma nova página sem linkar de outra página, informe o nome único de uma página na barra de endereços do seu navegador. Por exemplo, se você inserir:

    - -
    https://developer.mozilla.org/en-US/docs/FooBar
    - -

    O MDN cria uma nova página com o título "FooBar" e abre o editor para você inserir o conteúdo nessa página. Veja a sessão "Editando uma página existente" nesse artigo para ver como usar o editor.

    - -

    Subpágina de uma página existente

    - -

    Para criar uma subpágina que você quer que seja filha de uma página existente:

    - -
      -
    1. Na página "pai", clique no menu Avançado (o ícone de engrenagem na barra de ferramentas) e clique em Nova subpágina.
    2. -
    3. Digite um título para o documento no campo Título.
    4. -
    5. Mude o Slug se necessário (por exemplo, se o título for muito longo e você quiser um título menor). Esse campo é gerado automaticamente pelo editor, substituindo underlines por espaços no título. Nesse caso, você pode mudar apenas a última parte da URL do documento.
    6. -
    - -

    Clone de uma página existente

    - -

    Se houver uma página existente cujo formato você quer usar numa página nova, você pode clonar essa página e mudar seu conteúdo

    - -
      -
    1. Na página original, clique no menu Avançado (o ícone de engrenagem na barra de ferramentas) e clique em Clonar essa página. O editor vai abrir para que você mude seu conteúdo.
    2. -
    3. Mude o Título da página conforme apropriado. O campo Slug é atualizado automaticamente quando você muda o campo Título.
    4. -
    5. Se necessário, mude o caminho do campo Slug para colocar o documento em uma parte diferente da hierarquia dele.
    6. -
    7. No campo TOC, selecione os níveis de cabeçalho que você quer que sejam automaticamente exibidos na tabela de conteúdo da página, ou "Sem tabela de conteúdos" se a página não precisar de uma.
    8. -
    9. Escreva o conteúdo da página e salve suas alterações. Veja a sessão "Editando uma página existente" nesse artigo para ver como usar o editor.
    10. -
    - - - -

    Esse método é um pouco híbrido. Você pode criar um link em outra página, e clicar no link que você inseriu, para criar a nova página.

    - -
      -
    1. Digite o nome da página nova em qualquer lugar (que faça sentido) no texto de uma página existente.
    2. -
    3. Selecione o nome e clique no ícone de link () na barra de ferramentas do editor. A caixa de diálogo para "Atualizar Link" vai abrir com o texto selecionado no campo "Linkar para".
    4. -
    5. "/pt-BR/docs/" é inserido por padrão no começo do campo URL. Insira o nome da página depois de "/pt-BR/docs/". (O nome da página não tem de ser o mesmo texto do link).
    6. -
    7. Clique em OK para criar e inserir o link.
    8. -
    - -

    Se a página já não existir, o link é mostrado em vermelho. Se a página já existir, o link é mostrado em azul. Se você quiser criar uma nova página mas o título da página que você quer já estiver sendo usado, verifique primeiro se não faz mais sentido ajudar a editar o conteúdo existente. Senão, pense num título diferente para sua nova página e crie um link para ela. Veja o guia para nomear páginas.

    - -

    Para adicionar conteúdo para sua nova página, clique no link vermelho que você acabou de criar (depois de salvar e fechar o editor). A nova página abre no modo de edição, assim você pode começar a editar o conteúdo. Veja a sessão "Editando uma página existente" nesse artigo para ver como usar o editor.

    - -

    Atualizando o conteúdo da página

    - -

    O suporte do MDN para macros KumaScript e transclusão de conteúdo de uma página para outra pode algumas vezes ser dificultada pela necessidade de fazer um cache das páginas geradas para melhorar a performance. Páginas são feitas do seu código-fonte, e a saída é cacheada para requisições futuras. A partir de lá, quaisquer macros (templates) ou transclusões (utilizando a macro Page) na página não vão refletir mudanças feitar para o macro, a saída do macro, ou o conteúdo do material transcluso.

    - -
      -
    • Para atualizar a página manualmente, você pode forçar uma atualização no seu browser. MDN detecta esse gatilho e a página é refeita, inserindo a atualização feita pela saída do macro e o conteúdo da página.
    • -
    • Você também pode configurar páginas para serem refeitas periodicamente. Isso não deve ser feito a não ser que você precise que a página seja atualizada frequentemente. Veja regeneração de página para detalhes.
    • -
    - -

    Veja também

    - - diff --git a/files/pt-br/mdn/writing_guidelines/howto/creating_moving_deleting/index.md b/files/pt-br/mdn/writing_guidelines/howto/creating_moving_deleting/index.md new file mode 100644 index 00000000000000..d99fa8669be333 --- /dev/null +++ b/files/pt-br/mdn/writing_guidelines/howto/creating_moving_deleting/index.md @@ -0,0 +1,132 @@ +--- +title: Criando e editando páginas +slug: MDN/Writing_guidelines/Howto/Creating_moving_deleting +tags: + - Colaborando + - Colaborar + - Contribuindo + - Criando + - Editando + - MDN + - nova pagina +translation_of: MDN/Contribute/Howto/Create_and_edit_pages +original_slug: MDN/Contribute/Howto/Create_and_edit_pages +--- +{{MDNSidebar}} + +As duas tarefas mais básicas sobre MDN que quase todo contribuinte MDN irá eventualmente executar são para editar uma página já existente ou criar uma nova. Este artigo aborda os conceitos básicos de como fazer cada uma delas. + +## Editando uma página existente + +É fácil editar: + +- Clique no botão editar próximo ao topo na direita no canto da página. +- A página recarregará com opções de formatação, assim, você pode adicionar ou deletar informação diretamente na página. +- Você pode adicionar parágrafos, deletar texto, inserir cabeçalhos, e mais das tarefas básicas que envolvem edição de textos. + +### Ver mudanças + +Para ver como suas mudanças ficaram: + +- Clique no botão "Visualizar mudanças" (dentro da função de editar) acima do título da página. +- Isso abre uma páǵina de pré-visualização que inclui sua revisão em uma nova janela ou aba. +- Cada vez que você clica nesse botão, ele recarrega sua página de pré-visualização com as últimas mudanças feitas. + +Tenha cuidado! Pré-visualizar uma página _não salva_ as alterações, sendo assim, se lembre de não fechar a página que você está editando sem salvar o conteúdo. + +### Revisão de comentário + +Depois que você pré-visualizou suas mudanças, você deve querer salvar sua revisão. Antes de salvar, procure pela caixa de comentários de revisão abaixo da sessão de título da página e deixe um comentário para informar a outros voluntários o que você mudou e o motivo. Por exemplo, você pode ter adicionado uma nova sessão, mudado algumas palavras para fazer a terminologia mais consistente, reescrito um parágrafo para esclarecer o idioma, ou removido informação porque é redundante. + +### Tags + +Você pode adicionar ou remover tags que descrevam o conteúdo da página. Veja [como adicionar tags às páginas corretamente](/pt-BR/docs/MDN/Contribute/guia/Como-marcar-as-paginas-corretamente) para mais informações em que as tags se aplicam. + +### Precisa de revisão? + +Se você quiser que um contribuidor experiente revise suas edições, você pode requisitar uma revisão técnica (para códigos, APIs, ou tecnologias), uma revisão editorial (textual, de gramática ou conteúdo), ou uma revisão de template (para código KumaScript) se certificando que a caixa está marcada, antes que você salve. + +### Anexar arquivos + +Se você quiser anexar um arquivo a uma página para adicionar uma ilustração ou tornar o conteúdo mais claro, o anexo pode ir no final da página. + +### Salve, descarte ou continue editando + +Quando você termina uma edição com seu preview, você pode salvar seu trabalho e comentários clicando no botão verde "Salvar alterações" à direita do título da página. Se você mudar de ideia, pode descartar suas edições clicando no botão vermelho "Descartar alterações", também à direita do título da página. + +Pressionar **Enter** no comentário da revisão é equivalente a clicar em "Salvar e continuar editando". + +## Criando uma nova página + +Se você não sabe onde colocar seu artigo, **não se preocupe sobre isso!** Coloque-o em qualquer local e nós vamos encontrá-lo e movê-lo para onde ele pertence, ou mesclá-lo em conteúdo existente se for mais apropriado. Você também não precisa se preocupar sobre deixar tudo perfeito. Nós temos gnomos ajudantes felizes que vão ajudá-lo deixar seu conteúdo lindo. + +Há algumas maneiras de criar uma nova página: + +- [Link para "página inexistente"](#link-para-pagina-inexistente) +- [Nova página sem link](#nova-pagina-sem-link) +- [Subpágina de uma página existente](#subpagina-de-uma-pagina-existente) +- [Clone de uma página existente](#clone-de-uma-pagina-existente) +- [Link para página existente](#link-para-uma-pagina-existente) + +### Link para uma página inexistente + +Como na maioria das wikis, na MDN é possível criar links para uma página que ainda não existe. Por exemplo, um autor pode criar uma lista de todos os membros de uma API, antes de criar as páginas para esses membros. Na MDN, links para página inexistentes geralmente são exibidos em vermelho. + +Para criar um link para uma "página inexistente": + +1. Certifique-se que você está logado na MDN. (Se você não estiver, vai receber um erro 404). +2. Clique no link "página inexistente". O [MDN Editor UI](/pt-BR/docs/MDN/Contribute/Editor) abrirá, pronto para você criar a página inexistente. +3. Escreva o conteúdo da página e salve-a. + +### Nova página sem link + +_Para criar uma nova página sem linkar de outra página_, informe o nome único de uma página na barra de endereços do seu navegador. Por exemplo, se você inserir: + +```html +https://developer.mozilla.org/en-US/docs/FooBar +``` + +O MDN cria uma nova página com o título "FooBar" e abre o editor para você inserir o conteúdo nessa página. Veja a sessão "[Editando uma página existente](<#Editando uma págia existente>)" nesse artigo para ver como usar o editor. + +### Subpágina de uma página existente + +Para criar uma subpágina que você quer que seja filha de uma página existente: + +1. Na página "pai", clique no menu **Avançado** (o ícone de engrenagem na barra de ferramentas) e clique em **Nova subpágina**. +2. Digite um título para o documento no campo **Título**. +3. Mude o **Slug** se necessário (por exemplo, se o título for muito longo e você quiser um título menor). Esse campo é gerado automaticamente pelo editor, substituindo underlines por espaços no título. Nesse caso, você pode mudar apenas a última parte da URL do documento. + +### Clone de uma página existente + +Se houver uma página existente cujo formato você quer usar numa página nova, você pode clonar essa página e mudar seu conteúdo + +1. Na página original, clique no menu **Avançado** (o ícone de engrenagem na barra de ferramentas) e clique em **Clonar essa página**. O editor vai abrir para que você mude seu conteúdo. +2. Mude o **Título** da página conforme apropriado. O campo **Slug** é atualizado automaticamente quando você muda o campo **Título**. +3. Se necessário, mude o caminho do campo **Slug** para colocar o documento em uma parte diferente da hierarquia dele. +4. No campo **TOC**, selecione os níveis de cabeçalho que você quer que sejam automaticamente exibidos na tabela de conteúdo da página, ou "Sem tabela de conteúdos" se a página não precisar de uma. +5. Escreva o conteúdo da página e salve suas alterações. Veja a sessão "[Editando uma página existente](<#Editando uma págia existente>)" nesse artigo para ver como usar o editor. + +### Link para uma página existente + +Esse método é um pouco híbrido. Você pode criar um link em outra página, e clicar no link que você inseriu, para criar a nova página. + +1. Digite o nome da página nova em qualquer lugar (que faça sentido) no texto de uma página existente. +2. Selecione o nome e clique no **ícone de link (![](https://developer.mozilla.org/files/3810/link-icon.png))** na barra de ferramentas do editor. A caixa de diálogo para "**Atualizar Link"** vai abrir com o texto selecionado no campo "**Linkar para**". +3. "/pt-BR/docs/" é inserido por padrão no começo do campo URL. Insira o nome da página depois de "/pt-BR/docs/". (O nome da página não tem de ser o mesmo texto do link). +4. Clique em OK para criar e inserir o link. + +Se a página já não existir, o link é mostrado em vermelho. Se a página já existir, o link é mostrado em azul. Se você quiser criar uma nova página mas o título da página que você quer já estiver sendo usado, verifique primeiro se não faz mais sentido ajudar a editar o conteúdo existente. Senão, pense num título diferente para sua nova página e crie um link para ela. Veja o [guia para nomear páginas](/pt-BR/docs/MDN/Contribute/Content/Style_guide). + +Para adicionar conteúdo para sua nova página, clique no link vermelho que você acabou de criar (depois de salvar e fechar o editor). A nova página abre no modo de edição, assim você pode começar a editar o conteúdo. Veja a sessão "[Editando uma página existente](<#Editando uma págia existente>)" nesse artigo para ver como usar o editor. + +## Atualizando o conteúdo da página + +O suporte do MDN para macros KumaScript e transclusão de conteúdo de uma página para outra pode algumas vezes ser dificultada pela necessidade de fazer um cache das páginas geradas para melhorar a performance. Páginas são feitas do seu código-fonte, e a saída é cacheada para requisições futuras. A partir de lá, quaisquer macros (templates) ou transclusões (utilizando a macro Page) na página não vão refletir mudanças feitar para o macro, a saída do macro, ou o conteúdo do material transcluso. + +- Para atualizar a página manualmente, você pode forçar uma atualização no seu browser. MDN detecta esse gatilho e a página é refeita, inserindo a atualização feita pela saída do macro e o conteúdo da página. +- Você também pode configurar páginas para serem refeitas periodicamente. Isso não deve ser feito a não ser que você precise que a página seja atualizada frequentemente. Veja [regeneração de página](/pt-BR/docs/MDN/Contribute/Tools/Page_regeneration) para detalhes. + +## Veja também + +- [Guia do editor do MDN](/pt-BR/docs/MDN/Contribute/Editor) +- [Guia de estilos do MDN](/pt-BR/docs/MDN/Contribute/Content/Style_guide) diff --git a/files/pt-br/mdn/writing_guidelines/howto/tag/index.html b/files/pt-br/mdn/writing_guidelines/howto/tag/index.html deleted file mode 100644 index 16a58689f2a496..00000000000000 --- a/files/pt-br/mdn/writing_guidelines/howto/tag/index.html +++ /dev/null @@ -1,395 +0,0 @@ ---- -title: Como adicionar etiquetas às páginas corretamente -slug: MDN/Writing_guidelines/Howto/Tag -tags: - - Contribua - - Etiquetas - - Filtro - - Glossário - - Guia(2) - - Howto - - Iniciante - - Introdução - - MDN Meta - - Tags - - Tutorial -translation_of: MDN/Contribute/Howto/Tag -original_slug: MDN/Contribute/Howto/Tag ---- -
    {{MDNSidebar}}
    {{IncludeSubnav("/pt-BR/docs/MDN")}}
    - -

    As etiquetas dos artigos são uma forma importante de ajudar visitantes a encontrar o conteúdo procurado. Há muitas etiquetas usadas para ajudar a organizar as informações na MDN. Esta página vai lhe ensinar a melhor maneira de rotular as páginas, a fim de fazer com que as informações sejam organizadas, classificadas e localizadas mais facilmente. Cada página pode ser marcada por etiquetas que ajudam a classificar seu conteúdo.

    - -

    Você pode encontrar uma boa ajuda quanto às etiquetas em páginas na seção 'etiquetando', em nosso guia de edição.

    - -

    Observe que o uso adequado de etiquetas é importante; nós estamos cada vez mais usando automação para gerar listas de conteúdo, páginas de destino e ligação cruzada de artigos. Falhar em marcar artigos corretamente (como indicado abaixo) pode impedir que os mesmos sejam listados precisamente.

    - -

    Métodos de marcações usadas na MDN

    - -

    Há muitas maneiras das etiquetas serem usadas na MDN:

    - -
    -
    Categorização
    -
    Qual o tipo desse documento? É uma referência? Um tutorial? Uma página de destino? As etiquetas podem ser usadas em filtros de busca, então elas são realmente importantes!
    -
    Identificação de tópico
    -
    Que tópico esse artigo envolve? É sobre uma API? O DOM? Gráficos? Estas também são importantes, pois elas podem ser usadas em filtros de buscas.
    -
    Estado da tecnologia
    -
    Qual é o estado dessa tecnologia? Isto não é padrão? Obsoleto ou moderno? Experimental?
    -
    Nível de habilidade
    -
    Para tutoriais e guias, quão avançado é o material do artigo?
    -
    Metadados do documento
    -
    Os escritores da MDN usam rótulos que informam quais páginas precisam de melhorias e de quais tipos.
    -
    - -

    Guia de tipos de marcação

    - -

    Aqui está um guia rápido sobre os tipos de etiquetas e os possíveis valores para elas.

    - -

    Categoria do Documento

    - -

    Quando você rotula um artigo com uma destas categorias, você ajuda ferramentas automáticas a gerarem mais precisamente as páginas de entrada, tabela de conteúdos e assim por diante. Nosso novo sitema de pesquisa também vai usar esses termos para que nossos visitantes possam localizar referências e guias mais fácilmente.

    - -

    Nós usamos os seguintes nomes de categorias como termos de etiquetamento padrão:

    - -
    -
    Intro
    -
    O artigo fornece um material introdutório sobre algum tópico. Idealmente, cada área de tecnologia deveria ter apenas uma "introdução".
    -
    Featured
    -
    O artigo é crucial e será exibido com relevância nas páginas de entrada. Use esta etiqueta moderadamente (nunca mais do que três páginas em cada área da documentação).
    -
    Reference
    -
    O artigo contém material de referência sobre uma API, elementos, atributos, propriedades, ou coisas semelhantes.
    -
    Landing
    -
    Indica que esta é uma página de entrada.
    -
    Guide
    -
    O artigo é um guia ou um tutorial.
    -
    Example
    -
    O artigo é uma página de amostra de código, ou tem exemplos de códigos (isto é, pedaços de códigos úteis, não uma linha de "exemplo de sintaxe") .
    -
    - -

    Tópico

    - -

    Ao identificar o assunto tratado por um artigo você ajuda a gerar melhores resultados de pesquisa, assim como páginas de entrada e outros auxílios de navegação.

    - -

    Apesar de ser permitida certa flexibilidade, ao passo que novos assuntos são identificados, preferimos que estas etiquetas tenham os mesmos nomes das APIs, ou tecnologias, demonstradas na página. Alguns exemplos:

    - -
      -
    • HTML
    • -
    • CSS
    • -
    • JavaScript (Lembre-se do "S" maiúsculo!)
    • -
    • Document
    • -
    • DOM
    • -
    • API usada em todas as interfaces, métodos e propriedades
    • -
    • Method usada em todo método de alguma API
    • -
    • Property usada em toda propriedade de alguma API
    • -
    • Graphics gráficos
    • -
    • Firefox OS
    • -
    • Gecko
    • -
    • XUL
    • -
    • XPCOM
    • -
    • SVG
    • -
    • WebGL
    • -
    • Element elemento
    • -
    • Node
    • -
    • Tools ferramentas
    • -
    • Web
    • -
    - -

    No geral, se uma interface que possui várias páginas relacionadas a ela, como Node (que possui várias páginas sobre seus muitos métodos e propriedades), seu nome é uma boa etiqueta para identificar um tópico, assim como o nome de uma tecnologia abragente, ou seu tipo. Uma página sobre WebGL pode ser marcada com as tags Gráficos/Graphics e WebGL, por exemplo, e uma página sobre elementos {{HTMLElement("canvas")}} pode ser marcada com as etiquetas HTML, Elementos/Element, Tela/Canvas, e Gráficos/Graphics.

    - -

    Estado da tecnologia

    - -

    Para ajudar a entender se uma tecnologia é viável ou não, nós usamos as etiquetas que descrevem em que ponto estão as suas especificações. Fazer isso não detalha tanto quanto explicar, de fato, qual é a especificação e onde, nesse processo, a tecnologia está (para isto usamos uma tabela de "Especificações"), mas ajuda os leitores a julgar, rapidamente, se usar a tecnologia descrita no artigo é, ou não, uma boa ideia.

    - -

    Alguns valores possíveis para estas etiquetas:

    - -
    -
    Read-only
    -
    Aplique esta etiqueta para páginas que descrevem atributos ou propriedades que são "somente leitura".
    -
    - -
    -
    Non-standard
    -
    Indica que a tecnologia ou API não pertence a qualquer padrão, mas é considerada estável no(s) navegador(es) que a tem implementada. Se você não usar esta etiqueta os leitores vão presumir que o artigo é padronizado. A tabela de compatibilidade da página deve esclarecer quais navegadores suportam essa tecnologia ou API.
    -
    Deprecated
    -
    A tecnologia ou API abrigada na página foi marcada como obsoleta na especificação e é esperado que seja, eventualmente, removida mas está, em geral, ainda presente nas versões mais recentes de navegadores.
    -
    Obsolete
    -
    Foi decidido que a tecnologia ou API está ultrapassada e, assim, foi removida (ou está em processo de remoção) de todas as versões mais recentes de navegadores.
    -
    Experimental
    -
    A tecnologia ou API não é padronizada, ainda é experimental e pode, ou não, vir a ser parte da especificação. Também está sujeita a alterações no mecanismo do navegador (tipicamente, apenas uma) que a implementa.
    -
    Needs Privileges
    -
    A API requer acesso privilegiado ao aparelho no qual o código está rodando.
    -
    Certified Only
    -
    A API funciona, apenas, em código certificado.
    -
    - -

    Estas etiquetas não são desculpa para não inserir uma tabela de compatibilidade em seu artigo!

    - -

    Nível de habilidade

    - -

    A etiqueta de nível de habilidade é usada, apenas, em guias e tutoriais (ou seja, páginas marcadas como Guias) a fim de auxiliar quem os procura a escolher tutoriais baseados na familiaridade com a tecnologia. Existem trés valores para esta etiqueta:

    - -
    -
    Beginner
    -
    Artigos escritos com a intenção de introduzir uma nova tecnologia, para iniciantes.
    -
    Intermediate
    -
    Artigos para quem já tem experiência com a tecnologia, mas ainda não a domina completamente.
    -
    Advanced
    -
    Artigos que levam ao limite as capacidades de quem lê e da tecnologia.
    -
    - -

    Metadados do documento

    - -

    Os escritores da MDN usam etiquetas para identificar artigos que precisam de determinados tipos de trabalho. Segue uma lista das que mais usamos:

    - -
    -
    junk
    -
    Este artigo precisa ser deletado.
    -
    NeedsContent
    -
    Este artigo é um esboço, ou a informação está, de alguma forma, incompleta. Esta etiqueta significa que alguém precisa revisar o conteúdo e adicionar detalhes e/ou terminar a escrita do artigo.
    -
    NeedsExample
    -
    O artigo precisa de um ou mais exemplos para ilustrar melhor seu objetivo, de acordo com o sistema de exemplos dinâmicos.
    -
    NeedsLiveSamples
    -
    Este arigo necessita que um, ou mais, de seus exemplos sejam modificados para incluir o uso do sistema de exemplos dinâmicos.
    -
    NeedsUpdate
    -
    O artigo está desatualizado.
    -
    l10n:exclude
    -
    Não vale a pena traduzir este artigo e ele não aparecerá nas páginas sobre as situações das traduções.
    -
    l10n:priority
    -
    Este artigo é importante e deve ser visto como prioridade para os tradutores da MDN. É mostrado em uma tabela de maior importância nas páginas sobre as situações das traduções.
    -
    - -

    Mapa Literário Web

    - -

    O projeto WebMaker, através do Mapa Literário para a Web, definiu as habilidades necessárias para aperfeiçoar a leitura, a escrita e a participação na Web. Nós usamos essas habilidades literárias em forma de etiquetas, na MDN, para ajudar nossos utilizadores a encontrar as melhores respostas às suas necessidades:

    - -
    -
    Navigation
    -
    Este artigo inclui informação sobre como navegar pela web.
    -
    WebMechanics
    -
    Este artigo tem informação de como a web é organizada e como ela funciona.
    -
    Search
    -
    Este artigo explica como localizar informação, pessoas e recursos na web.
    -
    Credibility
    -
    A instrução neste artigo ajuda os leitores a entender como avaliar, criticamente, a informação encontrada na web.
    -
    Security
    -
    Este artigo provê informação de como manter sistemas, identidades e conteúdo seguros.
    -
    Composing
    -
    Este artigo explica como criar e selecionar conteúdo para a web.
    -
    Remixing
    -
    Este artigo ensina como modificar recursos já existentes na web para criar algo novo.
    -
    Design
    -
    Documentação sobre como aprimorar a estética visual e a experiência dos utilizadores.
    -
    Accessibility
    -
    Documentos que descrevem como desenvolver conteúdo com acessibilidade, o que significa permitir que o máximo possível de pessoas possa acessá-lo, ainda que as suas habilidades sejam limitadas de alguma forma.
    -
    CodingScripting
    -
    Como programar e/ou criar experiências interativas na web.
    -
    infrastructure
    -
    Este documento explica as partes técnicas da internete.
    -
    Sharing
    -
    O conteúdo deste artigo fala sobre as várias maneiras de criar recursos com outras pessoas.
    -
    Collaborating
    -
    Este artigo provê informação de como trabalhar em conjunto com outras pessoas.
    -
    Community
    -
    Este artigo detalha como se envolver com as comunidades da Web e entender como elas funcionam.
    -
    Privacy
    -
    Este material ajuda a examinar as consequências de compatilhar dados online.
    -
    OpenPractices
    -
    Este artigo demonstra como manter a Web acessível a todas as pessoas.
    -
    - -

    Colocando tudo junto

    - -

    Para cada página você aplica vários tipos de etiquetas, por exemplo:

    - -
    -
    Um tutorial sobre WebGL para iniciantes
    -
    WebGL, Gráficos, Graphics, Guia, Guide, Iniciante, Beginner
    -
    Referência para elementos {{HTMLElement("canvas")}}
    -
    Canvas, Tela, HTML, Element, Elementos, Graphics Reference, Referencial Gráfico
    -
    Uma página de entrada para as ferramentas de desenvolvedores voltados ao Firefox OS
    -
    Tools, Ferramentas, Firefox OS, Landing, Destino
    -
    - -

    Etiquetas e filtros de busca

    - -

    Filtros de busca não vão funcionar apropriadamente, a não ser que marquemos as páginas da MDN corretamente. Aqui está uma tabela dos filtros de pesquisa e sua busca correspondente.

    - -
    -

    Observação: Se várias etiquetas estiverem listadas abaixo de "Nome da etiqueta", isso significa que, pelo menos, uma delas precisa estar presente para o artigo estar propriamente marcado.

    -
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    Grupo do filtroNome do filtro de pesquisaNome da etiqueta
    TópicoOpen Web AppsApps
    HTMLHTML
    CSSCSS
    JavaScriptJavaScript
    APIs e DOMAPI
    TelasCanvas
    SVGSVG
    MathMLMathML
    WebGLWebGL
    XULXUL
    MarketplaceMarketplace
    FirefoxFirefox
    Firefox para AndroidFirefox Mobile
    Firefox para ComputadoresFirefox Desktop
    Firefox OSFirefox OS
    Dispositivos MóveisMobile
    Desenvolvimento WebWeb Development
    Complementos & ExtensõesAdd-ons || Extensions || Plugins || Themes
    JogosGames
    Nível de habilidadeSou EspecialistaAdvanced
    Nível IntermediárioIntermediate
    Estou ComeçandoBeginner
    Tipo de documentoDocumentosEsta vai restringir a busca ao teor dos documentos, deixando de fora Hacks e outros conteúdos MDN.
    DemosIsto vai incluir as demonstrações (Demo Studio) nos resultados da busca.
    FerramentasTools
    Exemplos de CódigosExample
    Guia & TutorialGuide
    Perfis de desenvolvedoresEsta inclui os perfis de desenvolvedores da comunidade MDN nos resultados da busca.
    Recursos ExternosIsto é alguma coisa que a equipe de desenvolvimento vai ter que solucionar.
    - -

    Problemas de etiquetas que você pode consertar

    - -

    Há vários tipos de problemas de rotulagem que você pode ajudar a resolver:

    - -
    -
    Sem etiquetas
    -
    Geralmente os artigos devem ter, no minimo, as etiquetas de "categória" e "tópico". Comumente outras etiquetas podem ser adicionadas mas, se você ajudar a garantir que o requesito minimo delas esteja presente, você já terá uma documentação maravilhosa!
    -
    Etiquetas que não seguem nossos padrões
    -
    Por favor, conserte qualquer documento cujas etiquetas não sigam as normas estabelecidas nesta página. Leve em consideração que, devido a um erro no Kuma, algumas etiquetas traduzidas (como Référence) podem aparecer em algumas páginas em inglês. Há uma chance bem grande destas etiquetas voltarem após serem deletadas, então, não se acanhe em consertá-las, até o erro ser corrigiido.
    -
    Etiquetas incorretas
    -
    Se você estiver lendo um artigo sobre HTML e este estiver marcado com "JavaScript", provavelmente há algo errado! Da mesma forma, se um artigo discutir os detalhes internos da Mozilla mas exibir uma etiqueta "Web", provavelmente existe algo errado aí, também. Remova essas tetiquetas e adicione as corretas, se elas ainda não estiverem lá. Por favor, também corrija etiquetas escritas incorretamente (p.ex. "javascript" não está de todo errada, uma vez que etiquetas não consideram maiúsculas, ou minúsculas, mas vamos ter capricho!: )
    -
    Carência de Etiquetas
    -
    Se um artigo tem algumas, mas não todas as etiquetas de que precisa, sinta-se à vontade para adicionar mais. Por exemplo: se uma página de referência de JavaScript estiver (corretamente) marcada com "JavaScript" e nada mais além disso, agradecemos se você inserir a etiqueta "Referência/Reference" lá, também!
    -
    Etiquetas indesejáveis (spam)
    -
    Esta besta asquerosa é o mais revoltante dos problemas de etiquetas: Algum verme da Web depositou suas excreções nas etiquetass de uma página (como "Programa Grátis!" ou "Ei, eu estava navegando pela sua página e queria perguntar se você me ajudaria a resolver esse problema que estou tendo com o Flash travando o tempo todo"). Temos que remover estas "etiquetas" assim que possível! Elas são horrendas, difíceis de manejar se esperarmos demais, e atrapalham muito a {{Glossary("SEO")}}.
    -
    - -

    Se você vir um (ou mais) destes problemas, por favor, registre-se, ou entre na MDN e clique no botão "EDITAR", no canto superior direito da página. Quando o editor carregar, role até o pé da página e você verá as etiquetas. Para mais detalhes da interface de marcação, leia a seção "As caixas de etiquetas" do Guia do editor da MDN.

    diff --git a/files/pt-br/mdn/writing_guidelines/howto/tag/index.md b/files/pt-br/mdn/writing_guidelines/howto/tag/index.md new file mode 100644 index 00000000000000..4eacaf2eb593ce --- /dev/null +++ b/files/pt-br/mdn/writing_guidelines/howto/tag/index.md @@ -0,0 +1,250 @@ +--- +title: Como adicionar etiquetas às páginas corretamente +slug: MDN/Writing_guidelines/Howto/Tag +tags: + - Contribua + - Etiquetas + - Filtro + - Glossário + - Guia(2) + - Howto + - Iniciante + - Introdução + - MDN Meta + - Tags + - Tutorial +translation_of: MDN/Contribute/Howto/Tag +original_slug: MDN/Contribute/Howto/Tag +--- +{{MDNSidebar}}{{IncludeSubnav("/pt-BR/docs/MDN")}} + +As etiquetas dos artigos são uma forma importante de ajudar visitantes a encontrar o conteúdo procurado. Há muitas etiquetas usadas para ajudar a organizar as informações na MDN. Esta página vai lhe ensinar a melhor maneira de rotular as páginas, a fim de fazer com que as informações sejam organizadas, classificadas e localizadas mais facilmente. Cada página pode ser marcada por etiquetas que ajudam a classificar seu conteúdo. + +Você pode encontrar uma boa ajuda quanto às etiquetas em páginas na seção 'etiquetando', em nosso [guia de edição](/pt-BR/docs/MDN/Contribute/Editor/Basics#The_tags_box). + +Observe que o uso adequado de etiquetas é importante; nós estamos cada vez mais usando automação para gerar listas de conteúdo, páginas de destino e ligação cruzada de artigos. Falhar em marcar artigos corretamente (como indicado abaixo) pode impedir que os mesmos sejam listados precisamente. + +## Métodos de marcações usadas na MDN + +Há muitas maneiras das etiquetas serem usadas na MDN: + +- Categorização + - : Qual o tipo desse documento? É uma referência? Um tutorial? Uma página de destino? As etiquetas podem ser usadas em filtros de busca, então elas são realmente importantes! +- Identificação de tópico + - : Que tópico esse artigo envolve? É sobre uma API? O DOM? Gráficos? Estas também são importantes, pois elas podem ser usadas em filtros de buscas. +- Estado da tecnologia + - : Qual é o estado dessa tecnologia? Isto não é padrão? Obsoleto ou moderno? Experimental? +- Nível de habilidade + - : Para tutoriais e guias, quão avançado é o material do artigo? +- Metadados do documento + - : Os escritores da MDN usam rótulos que informam quais páginas precisam de melhorias e de quais tipos. + +## Guia de tipos de marcação + +Aqui está um guia rápido sobre os tipos de etiquetas e os possíveis valores para elas. + +### Categoria do Documento + +Quando você rotula um artigo com uma destas categorias, você ajuda ferramentas automáticas a gerarem mais precisamente as páginas de entrada, tabela de conteúdos e assim por diante. Nosso novo sitema de pesquisa também vai usar esses termos para que nossos visitantes possam localizar referências e guias mais fácilmente. + +Nós usamos os seguintes nomes de categorias como termos de etiquetamento padrão: + +- `Intro` + - : O artigo fornece um material introdutório sobre algum tópico. Idealmente, cada área de tecnologia deveria ter apenas uma "introdução". +- `Featured` + - : O artigo é crucial e será exibido com relevância nas páginas de entrada. Use esta etiqueta moderadamente (nunca mais do que três páginas em cada área da documentação). +- `Reference` + - : O artigo contém material de referência sobre uma API, elementos, atributos, propriedades, ou coisas semelhantes. +- `Landing` + - : Indica que esta é uma página de entrada. +- `Guide` + - : O artigo é um guia ou um tutorial. +- `Example` + - : O artigo é uma página de amostra de código, ou tem exemplos de códigos (isto é, pedaços de códigos úteis, não uma linha de "exemplo de sintaxe") . + +### Tópico + +Ao identificar o assunto tratado por um artigo você ajuda a gerar melhores resultados de pesquisa, assim como páginas de entrada e outros auxílios de navegação. + +Apesar de ser permitida certa flexibilidade, ao passo que novos assuntos são identificados, preferimos que estas etiquetas tenham os mesmos nomes das APIs, ou tecnologias, demonstradas na página. Alguns exemplos: + +- `HTML` +- `CSS` +- `JavaScript` (Lembre-se do "S" maiúsculo!) +- `Document` +- `DOM` +- `API` usada em todas as interfaces, métodos e propriedades +- `Method` usada em todo método de alguma API +- `Property` usada em toda propriedade de alguma API +- `Graphics` gráficos +- `Firefox OS` +- `Gecko` +- `XUL` +- `XPCOM` +- `SVG` +- `WebGL` +- `Element` elemento +- `Node` +- `Tools` ferramentas +- `Web` + +No geral, se uma interface que possui várias páginas relacionadas a ela, como [Node](/pt-BR/docs/Web/API/Node "/en-US/docs/Web/API/Node") (que possui várias páginas sobre seus muitos métodos e propriedades), seu nome é uma boa etiqueta para identificar um tópico, assim como o nome de uma tecnologia abragente, ou seu tipo. Uma página sobre _WebGL_ pode ser marcada com as tags `Gráficos/Graphics` e `WebGL`, por exemplo, e uma página sobre elementos {{HTMLElement("canvas")}} pode ser marcada com as etiquetas `HTML`, `Elementos/Element`, `Tela/Canvas`, e `Gráficos/Graphics`. + +### Estado da tecnologia + +Para ajudar a entender se uma tecnologia é viável ou não, nós usamos as etiquetas que descrevem em que ponto estão as suas especificações. Fazer isso não detalha tanto quanto explicar, de fato, qual é a especificação e onde, nesse processo, a tecnologia está (para isto usamos uma tabela de "Especificações"), mas ajuda os leitores a julgar, rapidamente, se usar a tecnologia descrita no artigo é, ou não, uma boa ideia. + +Alguns valores possíveis para estas etiquetas: + +- `Read-only` + - : Aplique esta etiqueta para páginas que descrevem atributos ou propriedades que são "somente leitura". + + + +- `Non-standard` + - : Indica que a tecnologia ou API não pertence a qualquer padrão, mas é considerada estável no(s) navegador(es) que a tem implementada. Se você não usar esta etiqueta os leitores vão presumir que o artigo é padronizado. A tabela de compatibilidade da página deve esclarecer quais navegadores suportam essa tecnologia ou API. +- `Deprecated` + - : A tecnologia ou API abrigada na página foi marcada como obsoleta na especificação e é esperado que seja, eventualmente, removida mas está, em geral, ainda presente nas versões mais recentes de navegadores. +- `Obsolete` + - : Foi decidido que a tecnologia ou API está ultrapassada e, assim, foi removida (ou está em processo de remoção) de todas as versões mais recentes de navegadores. +- `Experimental` + - : A tecnologia ou API não é padronizada, ainda é experimental e pode, ou não, vir a ser parte da especificação. Também está sujeita a alterações no mecanismo do navegador (tipicamente, apenas uma) que a implementa. +- `Needs Privileges` + - : A API requer acesso privilegiado ao aparelho no qual o código está rodando. +- `Certified Only` + - : A API funciona, apenas, em código certificado. + +Estas etiquetas não são desculpa para não inserir uma [tabela de compatibilidade](/pt-BR/docs/Project:Compatibility_tables) em seu artigo! + +### Nível de habilidade + +A etiqueta de nível de habilidade é usada, apenas, em guias e tutoriais (ou seja, páginas marcadas como Guias) a fim de auxiliar quem os procura a escolher tutoriais baseados na familiaridade com a tecnologia. Existem trés valores para esta etiqueta: + +- `Beginner` + - : Artigos escritos com a intenção de introduzir uma nova tecnologia, para iniciantes. +- `Intermediate` + - : Artigos para quem já tem experiência com a tecnologia, mas ainda não a domina completamente. +- `Advanced` + - : Artigos que levam ao limite as capacidades de quem lê e da tecnologia. + +### Metadados do documento + +Os escritores da MDN usam etiquetas para identificar artigos que precisam de determinados tipos de trabalho. Segue uma lista das que mais usamos: + +- `junk` + - : Este artigo precisa ser deletado. +- `NeedsContent` + - : Este artigo é um esboço, ou a informação está, de alguma forma, incompleta. Esta etiqueta significa que alguém precisa revisar o conteúdo e adicionar detalhes e/ou terminar a escrita do artigo. +- `NeedsExample` + - : O artigo precisa de um ou mais exemplos para ilustrar melhor seu objetivo, de acordo com o [sistema de exemplos dinâmicos.](/pt-BR/docs/MDN/Contribute/Structures/Live_samples) +- `NeedsLiveSamples` + - : Este arigo necessita que um, ou mais, de seus exemplos sejam modificados para incluir o uso do [sistema de exemplos dinâmicos](/pt-BR/docs/MDN/Contribute/Structures/Live_samples). +- `NeedsUpdate` + - : O artigo está desatualizado. +- `l10n:exclude` + - : Não vale a pena traduzir este artigo e ele não aparecerá nas páginas sobre as situações das traduções. +- `l10n:priority` + - : Este artigo é importante e deve ser visto como prioridade para os tradutores da MDN. É mostrado em uma tabela de maior importância nas páginas sobre as situações das traduções. + +### Mapa Literário Web + +O projeto _[WebMaker](https://webmaker.org)_, através do [Mapa Literário para a _Web_](https://webmaker.org/literacy)_,_ definiu as habilidades necessárias para aperfeiçoar a leitura, a escrita e a participação na _Web_. Nós usamos essas habilidades literárias em forma de etiquetas, na MDN, para ajudar nossos utilizadores a encontrar as melhores respostas às suas necessidades: + +- `Navigation` + - : Este artigo inclui informação sobre como navegar pela _web_. +- `WebMechanics` + - : Este artigo tem informação de como a _web_ é organizada e como ela funciona. +- `Search` + - : Este artigo explica como localizar informação, pessoas e recursos na _web_. +- `Credibility` + - : A instrução neste artigo ajuda os leitores a entender como avaliar, criticamente, a informação encontrada na _web_. +- `Security` + - : Este artigo provê informação de como manter sistemas, identidades e conteúdo seguros. +- `Composing` + - : Este artigo explica como criar e selecionar conteúdo para a _web_. +- `Remixing` + - : Este artigo ensina como modificar recursos já existentes na _web_ para criar algo novo. +- `Design` + - : Documentação sobre como aprimorar a estética visual e a experiência dos utilizadores. +- `Accessibility` + - : Documentos que descrevem como desenvolver conteúdo com acessibilidade, o que significa permitir que o máximo possível de pessoas possa acessá-lo, ainda que as suas habilidades sejam limitadas de alguma forma. +- `CodingScripting` + - : Como programar e/ou criar experiências interativas na _web_. +- `infrastructure` + - : Este documento explica as partes técnicas da internete. +- `Sharing` + - : O conteúdo deste artigo fala sobre as várias maneiras de criar recursos com outras pessoas. +- `Collaborating` + - : Este artigo provê informação de como trabalhar em conjunto com outras pessoas. +- `Community` + - : Este artigo detalha como se envolver com as comunidades da _Web_ e entender como elas funcionam. +- `Privacy` + - : Este material ajuda a examinar as consequências de compatilhar dados _online._ +- `OpenPractices` + - : Este artigo demonstra como manter a _Web_ acessível a todas as pessoas. + +## Colocando tudo junto + +Para cada página você aplica vários tipos de etiquetas, por exemplo: + +- Um tutorial sobre WebGL para iniciantes + - : `WebGL`, Gráficos, `Graphics`, Guia, `Guide`, Iniciante, `Beginner` +- Referência para elementos {{HTMLElement("canvas")}} + - : `Canvas`, Tela, `HTML`, `Element`, Elementos, `Graphics` `Reference`, Referencial Gráfico +- Uma página de entrada para as ferramentas de desenvolvedores voltados ao Firefox OS + - : `Tools`, Ferramentas, `Firefox OS`, `Landing`, Destino + +## Etiquetas e filtros de busca + +Filtros de busca não vão funcionar apropriadamente, a não ser que marquemos as páginas da MDN corretamente. Aqui está uma tabela dos filtros de pesquisa e sua busca correspondente. + +> **Nota:** **Observação:** Se várias etiquetas estiverem listadas abaixo de "Nome da etiqueta", isso significa que, pelo menos, uma delas precisa estar presente para o artigo estar propriamente marcado. + +| Grupo do filtro | Nome do filtro de pesquisa | Nome da _etiqueta_ | +| ------------------- | -------------------------- | ---------------------------------------------------------------------------------------------------- | +| Tópico | Open Web Apps | `Apps` | +| | HTML | `HTML` | +| | CSS | `CSS` | +| | JavaScript | `JavaScript` | +| | APIs e DOM | `API` | +| | Telas | `Canvas` | +| | SVG | `SVG` | +| | MathML | `MathML` | +| | WebGL | `WebGL` | +| | XUL | `XUL` | +| | Marketplace | `Marketplace` | +| | Firefox | `Firefox` | +| | Firefox para Android | `Firefox Mobile` | +| | Firefox para Computadores | `Firefox Desktop` | +| | Firefox OS | `Firefox OS` | +| | Dispositivos Móveis | `Mobile` | +| | Desenvolvimento _Web_ | `Web Development` | +| | Complementos & Extensões | `Add-ons `\|\| `Extensions` \|\| `Plugins` \|\| `Themes` | +| | Jogos | `Games` | +| Nível de habilidade | Sou Especialista | `Advanced` | +| | Nível Intermediário | `Intermediate` | +| | Estou Começando | `Beginner` | +| Tipo de documento | Documentos | _Esta vai restringir a busca ao teor dos documentos, deixando de fora Hacks e outros conteúdos MDN._ | +| | Demos | _Isto vai incluir as demonstrações (Demo Studio) nos resultados da busca._ | +| | Ferramentas | `Tools` | +| | Exemplos de Códigos | `Example` | +| | Guia & Tutorial | `Guide` | +| | Perfis de desenvolvedores | _Esta inclui os perfis de desenvolvedores da comunidade MDN nos resultados da busca._ | +| | Recursos Externos | _Isto é alguma coisa que a equipe de desenvolvimento vai ter que solucionar._ | + +## Problemas de etiquetas que você pode consertar + +Há vários tipos de problemas de rotulagem que você pode ajudar a resolver: + +- Sem etiquetas + - : Geralmente os artigos devem ter, _no minimo_, as etiquetas de "[categória](/pt-BR/docs/MDN/Contribute/guia/Como-marcar-as-paginas-corretamente#Categória)" e "[tópico](/pt-BR/docs/MDN/Contribute/guia/Como-marcar-as-paginas-corretamente#Tópico)". Comumente outras etiquetas podem ser adicionadas mas, se você ajudar a garantir que o requesito minimo delas esteja presente, você já terá uma documentação maravilhosa! +- Etiquetas que não seguem nossos padrões + - : Por favor, conserte qualquer documento cujas etiquetas não sigam as normas estabelecidas nesta página. Leve em consideração que, devido a um [erro no _Kuma_](https://bugzilla.mozilla.org/show_bug.cgi?id=776048), algumas etiquetas traduzidas (como `Référence`) podem aparecer em algumas páginas em inglês. Há uma chance bem grande destas etiquetas voltarem após serem deletadas, então, não se acanhe em consertá-las, até o erro ser corrigiido. +- Etiquetas incorretas + - : Se você estiver lendo um artigo sobre HTML e este estiver marcado com "JavaScript", provavelmente há algo errado! Da mesma forma, se um artigo discutir os detalhes internos da Mozilla mas exibir uma etiqueta "_Web_", provavelmente existe algo errado aí, também. Remova essas tetiquetas e adicione as corretas, se elas ainda não estiverem lá. Por favor, também corrija etiquetas escritas incorretamente (p.ex. "javascript" não está de todo errada, uma vez que etiquetas não consideram maiúsculas, ou minúsculas, mas vamos ter capricho!: ) +- Carência de Etiquetas + - : Se um artigo tem algumas, mas não todas as etiquetas de que precisa, sinta-se à vontade para adicionar mais. Por exemplo: se uma página de referência de JavaScript estiver (corretamente) marcada com "JavaScript" e nada mais além disso, agradecemos se você inserir a etiqueta "Referência/Reference" lá, também! +- Etiquetas indesejáveis (_spam_) + - : Esta besta asquerosa é o mais revoltante dos problemas de etiquetas: Algum verme da _Web_ depositou suas excreções nas etiquetass de uma página (como "Programa Grátis!" ou "Ei, eu estava navegando pela sua página e queria perguntar se você me ajudaria a resolver esse problema que estou tendo com o _Flash_ travando o tempo todo"). Temos que remover estas "etiquetas" assim que possível! Elas são horrendas, difíceis de manejar se esperarmos demais, e atrapalham muito a {{Glossary("SEO")}}. + +Se você vir um (ou mais) destes problemas, por favor, registre-se, ou entre na MDN e clique no botão "EDITAR", no canto superior direito da página. Quando o editor carregar, role até o pé da página e você verá as etiquetas. Para mais detalhes da interface de marcação, leia a seção "[As caixas de etiquetas](/pt-BR/docs/MDN/Contribute/Editor/Basics#The_tags_box)" do [Guia do editor da MDN](/pt-BR/docs/MDN/Contribute/Editor). diff --git a/files/pt-br/mdn/writing_guidelines/index.html b/files/pt-br/mdn/writing_guidelines/index.html deleted file mode 100644 index bd0b614b4d6dbe..00000000000000 --- a/files/pt-br/mdn/writing_guidelines/index.html +++ /dev/null @@ -1,119 +0,0 @@ ---- -title: Sobre o MDN -slug: MDN/Writing_guidelines -tags: - - Colaboração - - Comunidade - - Guia(2) - - Licenças - - MDN Meta -translation_of: MDN/About -original_slug: MDN/About ---- -
    {{MDNSidebar}}
    - -
    {{IncludeSubNav("/pt-BR/docs/MDN")}}
    - -

    A Rede de Desenvolvedores da Mozilla (MDN) é uma plataforma de aprendizagem em evolução para tecnologias da Web e o software que alimenta a Web, incluindo:

    - - - -

    Nossa missão

    - -

    A missão da MDN é simples: prover uma completa, exata e útil documentação para tudo sobre a open Web, sendo ele construído, suportado ou não pela Mozilla. Se é uma tecnologia aberta e Web, queremos documentá-lo.

    - -

    Além disso, podemos fornecer a documentação sobre como desenvolver e contribuir com os projetos da Mozilla, Firefox OS e desenvolvimento de Web app.

    - -

    Se você não tem certeza se um tópico específico deve ser abordado no MDN leia: Isso pertence ao MDN?

    - -

    Como você pode ajudar

    - -

    Você não precisa ser capaz de programar - or escrever - para poder ajudar a MDN! Nós temos muitos caminhos por onde você pode ajudar, de uma revisão de artigos para ter certeza que fazem sentido, até contribuindo com texto, adicionando códigos de exemplo. Na verdade existem tantas formas de ajudar que nós temos uma ferramenta para ajudá-lo a escolher tarefas para ajudar, baseada em seus interesses e na sua quantidade de tempo livre.

    - -

    A comunidade MDN

    - -

    Nossa comunidade é global! Nós temos contribuidores incríveis ao redor do mundo todo, em muitos idiomas. Se você gostaria de descobrir mais sobre nós, ou se precisa de qualquer tipo de ajuda com a MDN, fique livre para checar nosso fórum de discussões ou canal IRC!

    - -

    Licenças e cópias de direito

    - -

    Os documentos wiki da MDN foram preparados com as contribuições de muitos autores, de dentro e de fora da Mozilla Foundation. A menos que seja indicado, o conteúdo está disponível sob os termos da Creative Commons Attribution-ShareAlike license (CC-BY-SA), v2.5 ou qualquer versão mais recente. Por favor, atribua "Mozilla Contributors" e inclua um hyperlink (online) ou URL (impresso) para a página da wiki específica do conteúdo referenciado. Por exemplo, para atribuir a este artigo, você pode escrever:

    - -
    About MDN por Mozilla Contributors está licenciado sob CC-BY-SA 2.5.
    - -

    Note que nesse exemplo, "Mozilla Contributors" leva para a história da página citada. Veja Best practices for attribution para explicações mais detalhadas.

    - -
    -

    Nota: Veja MDN content on WebPlatform.org para informações sobre como reutilizar e atribuir conteúdo da MDN naquele site.

    -
    - -

    Amostras de código adicionadas a esta wiki antes de 20 de agosto de 2010 estão disponíveis sob a MIT license; você deveria inserir a seguinte informação de atribuição no template MIT: "© <data da última revisão da página da wiki> <nome da pessoa que a inseriu na wiki>".

    - -

    Amostras de código adicionadas no dia 20 de agosto de 2010 ou depois estão no public domain. Não é necessário um aviso de licença, mas se você precisa de um, você pode utilizar: "Qualquer direito de cópia é dedicado ao Domínio Público. http://creativecommons.org/publicdomain/zero/1.0/".

    - -

    Se você deseja contribuir para esta wiki, você deve tornar sua documentação disponível pela licença Attribution-ShareAlike (ou ocasionalmente uma licença alternativa já especificada pela página que você está editando), e suas amostras de código disponívels sob a Creative Commons CC-0 (uma dedicação de Domínio Público). Acrescentar a esta wiki significa que você concorda que suas contribuições serão feitas sob estas licenças.

    - -

    Alguns conteúdos mais antigos foram disponibilizados sob uma licença diferente das citadas acima; estas são indicadas no final de cada página em um Alternate License Block.

    - -
    -

    Importante: Nenhuma nova página deve ser criada usando licenças alternativas.

    -
    - -

    Os direitos de cópia para materiais de contribuição permanecem com o(a) autor(a), a menos que ele(a) os atribua a outra pessoa.

    - -

    Se você tem perguntas ou dúvidas sobre algo exposto aqui, por favor contate Eric Shepherd.

    - -
    -

    Os direitos das marcas, logos, marcas de serviço da Mozilla Foundation, bem como o visual e estrutura deste site, não estão licenciados pela Creative Commons, e enquanto são trabalhos autorais (como logos e design gráfico), eles não estão inclusos no trabalho que está licenciado nesses termos. Se você utilizar o texto de documentos, e quiser também usar qualquer um destes direitos, ou se tem outras perguntas sobre cumprir com nossos termos de licença para esta coleção, você deve contatar a Mozilla Foundation aqui: licensing@mozilla.org.

    - -

    Baixar conteúdo

    - -

    Você pode baixar o conteúdo de uma página individual na MDN adicionando document parameters à URL para especificar qual formato deseja.

    - -

    Se você quiser baixar um dump SQL completo e anonimizado da base de dados da MDN -- isto é, uma cópia da base de dados com todas as informações privadas de usuários removidas, nós também fornecemos isso. Esse dump é atualizado no primeiro dia de todo mês.

    - -

    Existem três arquivos que compreendem o dump mensal anonimizado da MDN:

    - -
    -
    <date>.sanitized.devmo_sanitize.sql.gz
    -
    O dump de banco de dados MySQL sanitizado de todo o conteúdo da MDN, registros de datas, e assim por diante. Inclui todo o conteúdo de artigos, registros de histórico, e assim por diante. Todas as informações pessoais de usuários são retiradas (como endereços de email).
    -
    attachments-<date>.tar.gz
    -
    Esse arquivo contém todos os uploads de arquivos anexos feitos para a wiki.
    -
    uploads-<date>.tar.gz
    -
    Esse arquivo (muito grande!) contém os uploads de arquivos para o Demo Studio. Se você tem interesse apenas no conteúdo da wiki, você não precisa baixar isso.
    -
    - -

    Visite o aterro da MDN para baixar esses arquivos.

    - -

    Ferramentas de terceiros

    - -

    Você também pode visualizar o conteúdo da MDN via ferramentas de terceiros como o Dash (para Mac OS) e Zeal (para Linux e Windows).

    - -

    Informando problemas com a MDN

    - -

    De vez em quando, você pode encontrar problemas usando a MDN. Seja um problema com a infraestrutura do site ou um erro no conteúdo da documentação, você pode tentar consertar sozinho ou reportar o problema. Enquanto a primeira opção é preferida, a última é às vezes o melhor que você consegue fazer, e tudo bem com isso também.

    - -

    Erros na documentação

    - -

    Obviamente, já que a MDN é uma wiki, a melhor coisa que você pode fazer é consertar problemas que você encontrar sozinho. Mas talvez você não saiba a resposta, ou esteja no meio de uma correria para o hospital ou algo assim, e precise anotar o problema pra que alguém possa olhar depois.

    - -

    Como tudo o que é Mozilla, você pode reportar um problema na documentação registrando um bug. É aí que entra o registro de um documentation request bug. Nosso útil formulário de solicitação de documentação reunirá as informações necessárias para que possamos começar a consertar o problema.

    - -

    Naturalmente, nossa comunidade de escrita é atarefada, então às vezes a forma mais rápida de ver um problema de documentação resolvido é consertá-lo você mesmo. Veja Criando e editando páginas para detalhes.

    - -

    Bugs do site ou solicitar recursos

    - -

    Kuma, a plataforma desenvolvida pela Mozilla usada para o web site da MDN, está em um constante estado de desenvolvimento. Nossos desenvolvedores—assim como vários contribuidores voluntários—estão constantemente fazendo melhorias. Se você encontrar um bug, ou tiver um problema com o site, ou ainda tiver uma sugestão para algo que poderia tornar o software mais incrível, você pode usar o Kuma bug form para preencher um relatório.

    - -

    História da MDN

    - -

    O projeto Mozilla Developer Network (a.k.a. Mozilla Developer Center (MDC), a.k.a. Devmo) começou no início de 2005, quando a Mozilla Foundation obteve uma licença da AOL para utilizar o conteúdo original DevEdge. Os materiais ainda úteis foram extraídos do conteúdo DevEdge, e então migrados por voluntários para essa wiki, pra que a manutenção e atualização fossem mais fáceis.

    - -

    Desde então, o projeto continuou a crescer e agora forma um nexo central para toda a documentação para desenvolvedores relacionada ao Mozilla Project e tecnologias abertas da web. Em 2010, o nome mudou para Mozilla Developer Network; 2011 viu a adição do Demo Studio para desenvolvedores web compartilharem e exibirem seu código, e páginas Learning para fornecer links de tutoriais. (O nome MDC ainda vive como "MDN Doc Center" para a seção de documentação.) A tempo, espera-se que a Mozilla Developer Network se torne um recurso que web designers, desenvolvedores de aplicações, e escritores de extensões e temas visitam regularmente.

    - -

    Sobre a Mozilla

    - -

    Se você quer saber mais sobre quem somos, como fazer parte da Mozilla ou apenas onde nos encontrar, você veio ao lugar certo. Para descobrir o que nos impulsiona e nos torna diferentes, visite nossa página de missão.

    diff --git a/files/pt-br/mdn/writing_guidelines/index.md b/files/pt-br/mdn/writing_guidelines/index.md new file mode 100644 index 00000000000000..5a4a993b387036 --- /dev/null +++ b/files/pt-br/mdn/writing_guidelines/index.md @@ -0,0 +1,110 @@ +--- +title: Sobre o MDN +slug: MDN/Writing_guidelines +tags: + - Colaboração + - Comunidade + - Guia(2) + - Licenças + - MDN Meta +translation_of: MDN/About +original_slug: MDN/About +--- +{{MDNSidebar}}{{IncludeSubNav("/pt-BR/docs/MDN")}} + +A Rede de Desenvolvedores da Mozilla (MDN) é uma plataforma de aprendizagem em evolução para tecnologias da Web e o software que alimenta a Web, incluindo: + +- Padrões web como [CSS](/pt-BR/docs/CSS), [HTML](/pt-BR/docs/HTML), e [JavaScript](/pt-BR/docs/JavaScript) +- [Open Web app development](/pt-BR/docs/Apps) +- [Firefox add-on development](/pt-BR/docs/Add-ons) + +## Nossa missão + +A missão da MDN é simples: prover uma completa, exata e útil documentação para tudo sobre a open Web, sendo ele construído, suportado ou não pela Mozilla. Se é uma tecnologia aberta e Web, queremos documentá-lo. + +Além disso, podemos fornecer a documentação sobre como [desenvolver e contribuir com os projetos da Mozilla](/pt-BR/docs/Mozilla), [Firefox OS](/en-US/Firefox_OS) e [desenvolvimento de Web app](/en-US/Apps). + +Se você não tem certeza se um tópico específico deve ser abordado no MDN leia: [Isso pertence ao MDN?](/pt-BR/docs/Project:MDN/Contributing/Does_this_belong) + +## Como você pode ajudar + +Você não precisa ser capaz de programar - or escrever - para poder ajudar a MDN! Nós temos muitos caminhos por onde você pode ajudar, de uma revisão de artigos para ter certeza que fazem sentido, até contribuindo com texto, adicionando códigos de exemplo. Na verdade existem tantas formas de ajudar que nós temos uma [ferramenta para ajudá-lo a escolher tarefas para ajudar](/pt-BR/docs/MDN/Quick_start), baseada em seus interesses e na sua quantidade de tempo livre. + +## A comunidade MDN + +Nossa comunidade é global! Nós temos contribuidores incríveis ao redor do mundo todo, em muitos idiomas. Se você gostaria de descobrir mais sobre nós, ou se precisa de qualquer tipo de ajuda com a MDN, fique livre para checar nosso fórum de discussões ou canal IRC! + +## Licenças e cópias de direito + +Os documentos wiki da MDN foram preparados com as contribuições de muitos autores, de dentro e de fora da Mozilla Foundation. A menos que seja indicado, o conteúdo está disponível sob os termos da [Creative Commons Attribution-ShareAlike license](http://creativecommons.org/licenses/by-sa/2.5/) (CC-BY-SA), v2.5 ou qualquer versão mais recente. Por favor, atribua "Mozilla Contributors" e inclua um hyperlink (online) ou URL (impresso) para a página da wiki específica do conteúdo referenciado. Por exemplo, para atribuir a este artigo, você pode escrever: + +> [About MDN](/pt-BR/docs/MDN/About) por [Mozilla Contributors](/pt-BR/docs/MDN/About$history) está licenciado sob [CC-BY-SA 2.5](http://creativecommons.org/licenses/by-sa/2.5/). + +Note que nesse exemplo, "Mozilla Contributors" leva para a história da página citada. Veja [Best practices for attribution](http://wiki.creativecommons.org/Marking/Users) para explicações mais detalhadas. + +> **Nota:** Veja [MDN content on WebPlatform.org](/pt-BR/docs/MDN_content_on_WebPlatform.org) para informações sobre como reutilizar e atribuir conteúdo da MDN naquele site. + +Amostras de código adicionadas a esta wiki antes de 20 de agosto de 2010 estão disponíveis sob a [MIT license](http://www.opensource.org/licenses/mit-license.php); você deveria inserir a seguinte informação de atribuição no template MIT: "© \ \". + +Amostras de código adicionadas no dia 20 de agosto de 2010 ou depois estão no [public domain](http://creativecommons.org/publicdomain/zero/1.0/). Não é necessário um aviso de licença, mas se você precisa de um, você pode utilizar: "Qualquer direito de cópia é dedicado ao Domínio Público. http\://creativecommons.org/publicdomain/zero/1.0/". + +Se você deseja contribuir para esta wiki, você deve tornar sua documentação disponível pela licença Attribution-ShareAlike (ou ocasionalmente uma licença alternativa já especificada pela página que você está editando), e suas amostras de código disponívels sob a [Creative Commons CC-0](http://creativecommons.org/publicdomain/zero/1.0/) (uma dedicação de Domínio Público). Acrescentar a esta wiki significa que você concorda que suas contribuições serão feitas sob estas licenças. + +Alguns conteúdos mais antigos foram disponibilizados sob uma licença diferente das citadas acima; estas são indicadas no final de cada página em um [Alternate License Block](/Project:en/Examples/Alternate_License_Block "Project:En/Examples/Alternate License Block"). + +> **Aviso:** **Importante:** Nenhuma nova página deve ser criada usando licenças alternativas. + +Os direitos de cópia para materiais de contribuição permanecem com o(a) autor(a), a menos que ele(a) os atribua a outra pessoa. + +Se você tem perguntas ou dúvidas sobre algo exposto aqui, por favor contate [Eric Shepherd](mailto:eshepherd@mozilla.com). + +--- + +Os direitos das marcas, logos, marcas de serviço da Mozilla Foundation, bem como o visual e estrutura deste site, não estão licenciados pela Creative Commons, e enquanto são trabalhos autorais (como logos e design gráfico), eles não estão inclusos no trabalho que está licenciado nesses termos. Se você utilizar o texto de documentos, e quiser também usar qualquer um destes direitos, ou se tem outras perguntas sobre cumprir com nossos termos de licença para esta coleção, você deve contatar a Mozilla Foundation aqui: . + +## Baixar conteúdo + +Você pode baixar o conteúdo de uma página individual na MDN adicionando [document parameters](/pt-BR/docs/Project:MDN/Kuma/API#Document_parameters) à URL para especificar qual formato deseja. + +Se você quiser baixar um dump SQL completo e anonimizado da base de dados da MDN -- isto é, uma cópia da base de dados com todas as informações privadas de usuários removidas, nós também fornecemos isso. Esse dump é atualizado no primeiro dia de todo mês. + +Existem três arquivos que compreendem o dump mensal anonimizado da MDN: + +- `.sanitized.devmo_sanitize.sql.gz` + - : O dump de banco de dados MySQL sanitizado de todo o conteúdo da MDN, registros de datas, e assim por diante. Inclui todo o conteúdo de artigos, registros de histórico, e assim por diante. Todas as informações pessoais de usuários são retiradas (como endereços de email). +- `attachments-.tar.gz` + - : Esse arquivo contém todos os uploads de arquivos anexos feitos para a wiki. +- `uploads-.tar.gz` + - : Esse arquivo (muito grande!) contém os uploads de arquivos para o Demo Studio. Se você tem interesse apenas no conteúdo da wiki, você não precisa baixar isso. + +[Visite o aterro da MDN](https://developer.allizom.org/landfill/) para baixar esses arquivos. + +### Ferramentas de terceiros + +Você também pode visualizar o conteúdo da MDN via ferramentas de terceiros como o [Dash](http://kapeli.com/dash) (para Mac OS) e [Zeal](http://zealdocs.org/) (para Linux e Windows). + +## Informando problemas com a MDN + +De vez em quando, você pode encontrar problemas usando a MDN. Seja um problema com a infraestrutura do site ou um erro no conteúdo da documentação, você pode tentar consertar sozinho ou reportar o problema. Enquanto a primeira opção é preferida, a última é às vezes o melhor que você consegue fazer, e tudo bem com isso também. + +### Erros na documentação + +Obviamente, já que a MDN é uma wiki, a melhor coisa que você pode fazer é consertar problemas que você encontrar sozinho. Mas talvez você não saiba a resposta, ou esteja no meio de uma correria para o hospital ou algo assim, e precise anotar o problema pra que alguém possa olhar depois. + +Como tudo o que é Mozilla, você pode reportar um problema na documentação registrando um bug. É aí que entra o registro de um [documentation request bug](https://bugzilla.mozilla.org/form.doc). Nosso útil formulário de solicitação de documentação reunirá as informações necessárias para que possamos começar a consertar o problema. + +Naturalmente, nossa comunidade de escrita é atarefada, então às vezes a forma mais rápida de ver um problema de documentação resolvido é consertá-lo você mesmo. Veja [Criando e editando páginas](/pt-BR/docs/MDN/Contribute/Creating_and_editing_pages "/en-US/docs/Project:MDN/Contributing/Creating_and_editing_pages") para detalhes. + +### Bugs do site ou solicitar recursos + +[Kuma](/pt-BR/docs/Project:MDN/Kuma), a plataforma desenvolvida pela Mozilla usada para o web site da MDN, está em um constante estado de desenvolvimento. Nossos desenvolvedores—assim como vários contribuidores voluntários—estão constantemente fazendo melhorias. Se você encontrar um bug, ou tiver um problema com o site, ou ainda tiver uma sugestão para algo que poderia tornar o software mais incrível, você pode usar o [Kuma bug form](https://bugzilla.mozilla.org/form.mdn) para preencher um relatório. + +## História da MDN + +O projeto Mozilla Developer Network (a.k.a. Mozilla Developer Center (MDC), a.k.a. _Devmo_) começou no início de 2005, quando a [Mozilla Foundation](http://www.mozillafoundation.org) obteve uma licença da AOL para utilizar o conteúdo original [DevEdge](/Project:en/DevEdge "Project:en/DevEdge"). Os materiais ainda úteis foram extraídos do conteúdo DevEdge, e então migrados por voluntários para essa wiki, pra que a manutenção e atualização fossem mais fáceis. + +Desde então, o projeto continuou a crescer e agora forma um nexo central para toda a documentação para desenvolvedores relacionada ao Mozilla Project e tecnologias abertas da web. Em 2010, o nome mudou para Mozilla Developer Network; 2011 viu a adição do [Demo Studio](http://developer.mozilla.org/en-US/demos) para desenvolvedores web compartilharem e exibirem seu código, e páginas [Learning](http://developer.mozilla.org/en-US/learn) para fornecer links de tutoriais. (O nome MDC ainda vive como "MDN Doc Center" para a seção de documentação.) A tempo, espera-se que a Mozilla Developer Network se torne um recurso que web designers, desenvolvedores de aplicações, e escritores de extensões e temas visitam regularmente. + +## Sobre a Mozilla + +Se você quer saber mais sobre quem somos, como fazer parte da Mozilla ou apenas onde nos encontrar, você veio ao lugar certo. Para descobrir o que nos impulsiona e nos torna diferentes, visite nossa página de [missão](http://www.mozilla.org/en-US/mission/). diff --git a/files/pt-br/mdn/writing_guidelines/page_structures/index.html b/files/pt-br/mdn/writing_guidelines/page_structures/index.html deleted file mode 100644 index a345e9497d6e4d..00000000000000 --- a/files/pt-br/mdn/writing_guidelines/page_structures/index.html +++ /dev/null @@ -1,473 +0,0 @@ ---- -title: Tabelas de compatibilidade -slug: MDN/Writing_guidelines/Page_structures -translation_of: MDN/Structures/Compatibility_tables -original_slug: MDN/Structures/Compatibility_tables ---- -
    {{MDNSidebar}}
    - -

    A MDN possui um formato padrão para tabelas de compatibilidade para nossa documentação da Web aberta; isto é, documentação de tecnologias como DOM, HTML, CSS, JavaScript, SVG etc., compartilhadas em todos os navegadores. Este artigo é um guia de "introdução" sobre como adicionar, manter o banco de dados a partir do qual as tabelas de compatibilidade são geradas e como integrar as tabelas em artigos.

    - -

    Para obter uma documentação mais avançada, bem como as alterações mais recentes nos processos e esquemas JSON usados ​​para representar os dados, consulte o guia do colaborador do repositório de dados e o guia de diretrizes de dados.

    - -

    Se você tiver dúvidas ou descobrir problemas, compartilhe conosco no fórum de discussão da MDN.

    - -

    Como acessar o repositório de dados

    - -

    Os dados são armazenados em um repositório do GitHub — consulte https://github.com/mdn/browser-compat-data. Para acessá-lo, você precisa obter uma conta do GitHub, bifurcar (fork) o repositório de dados compatível com o navegador em sua própria conta e, em seguida, clonar seu fork na sua máquina local.

    - -

    Preparando para adicionar os dados

    - -

    Antes de adicionar dados novos, verifique que o fork criado tenha o mesmo conteúdo que o repositório principal. Após isso, crie uma nova branch, dentro do fork criado, para conter as mudanças e adições a serem realizadas, em seguida, faça um pull dessa branch no clone local, para então começar a contribuir com o projeto.

    - -

    Uma forma simples para ter certeza que o seu fork tem o mesmo conteúdo, e está tão atualizado quanto o repositório principal, é descrita abaixo:

    - -

    Adicionando o repositório principal browser-compat-data como um controle remoto

    - -

    Vá para o clone local do seu fork no seu terminal/linha de comando e adicione um controle remoto apontando para o repositório principal (upstream) assim (você só precisa fazer isso uma vez):

    - -
    git remote add upstream https://github.com/mdn/browser-compat-data.git
    - -

    Se não tiver certeza se fez isso, verifique os controles remotos que seu repositório está usando

    - -
    git remote -v
    - -

    Atualizando seu fork com o conteúdo do controle remoto

    - -

    Agora, sempre que você quiser atualizar seu fork, você pode fazer isso:

    - -
      -
    1. -

      Certificando-se de que você está no branch master:

      - -
      git checkout master
      -
    2. -
    3. -

      buscando o conteúdo atualizado do repositório usando:

      - -
      git fetch upstream
      -
    4. -
    5. -

      faça o rebase do seu conteúdo master com o conteúdo do repositório principal:

      - -
      git rebase upstream/master
      -
    6. -
    7. -

      faça o push dessas atualizações de volta ao seu fork remoto usando:

      - -
      git push -f
      -
    8. -
    - -

    Criando um novo branch (ramo) para fazer o seu trabalho

    - -

    Em seguida, vá à sua bifurcação remota (será em https://github.com/seu-nome-de-usuario/browser-compat-data) e crie um novo ramo para guardar suas mudanças de adição de conteúdo. Isso pode ser feito em:

    - -
      -
    1. Clicando no botão "Branch: Master".
    2. -
    3. Colocando um novo nome de ramo dentro do campo de texto de "Encontre ou crie seu ramo...".
    4. -
    5. Clicando no botão "Criar ramo nome-do-ramo a partir de Master".
    6. -
    - -

    Por exemplo, se você quisesse adicionar informações sobre WebVR API, você criaria um ramno chamado algo como "webvr".

    - -

    Mudando para o novo branch (ramo)

    - -

    Agora,volte para o seu terminal/linha de comando, e atualize seu clone local da sua bifurcação para incluir o seu novo ramo usando o seguinte comando:

    - -
    git pull
    - -

    Agora troque para o seu ramo usando:

    - -
    git checkout name-of-branch
    - -

    Agora você deveria estar pronto para adicionar seu conteúdo!

    - -

    Adicionando os dados

    - -

    To add the data, you need to create a new file or files to store your compat data in. The files you need to create differ, depending on what technology you are working on:

    - -
      -
    • HTML: One file per HTML element, contained in browser-compat-data/html/elements. The file should be called the name of the element, all in lower case, e.g. div.json.
    • -
    • CSS: One file per CSS property or selector, contained in the appropriate directory (see browser-compat-data/css). The file should be called the name of the feature, all in lower case, e.g. background-color.json, or hover.json.
    • -
    • JS: One file per JS object, contained in browser-compat-data/javascript/builtins. The file should be called the exact name of the object, with the casing preserved, e.g. Date.json or InternalError.json.
    • -
    • APIs: One file per interface contained in the API, put in browser-compat-data/api. Each file should be called the exact name of the interface, with the casing preserved, e.g. The WebVR API has VRDisplay.json, VRDisplayCapabilities.json, etc.
    • -
    - -
    -

    Note: You'll notice that the repo also contains data for Browser Extensions and HTTP. These data sets are basically finished as they stand, but more features may need to be added in the future.

    -
    - -

    Each file you create has to follow the pattern defined in the schema contained within our repo; you can see the detailed schema description here.

    - -

    Estrutura de dados de compatibilidade básica

    - -

    Let's look at an example. CSS property JSON files for example need the following basic structure:

    - -
    {
    -  "css": {
    -    "properties": {
    -      "border-width": {
    -        "__compat": {
    -          ...
    -        }
    -      }
    -    }
    -  }
    -}
    - -

    You have the css object, inside of which is a properties object. Inside the properties object, you need one member for each of the specific features you want to define the compat data for. Each of these members has a __compat member, inside of which the actual data goes.

    - -

    The above data is found in the border-width.json file — compare this to the rendered border-width support table on MDN.

    - -

    Other types of features work in the same way, but with different object names:

    - -
      -
    • CSS selectors work in basically the same way as CSS properties, except that the top-level object structure is css.selectors instead of css.properties. See cue.json for an example.
    • -
    • HTML data works in basically the same way, except that the top-level object structure is html.elements. See article.json for an example.
    • -
    • The top level object structure for JS built-in objects is javascript.builtins; see Array.json for an example.
    • -
    - -
    -

    In HTML, CSS, and JS pages, you'll normally only need one feature. API interfaces work slightly differently — they always have multiple sub-features (see Sub-features, below).

    - -

    Estrutura básica dentro de um recurso

    - -

    Inside a feature __compat member, you need to include the following members:

    - -
      -
    • mdn_url: Contains the URL of the reference page for this feature on MDN. Note that this needs to be written without the locale directory inside, e.g. /docs/... not /docs/en-US/... (or whatever). This is added in by the macro when the data is put on the page, for localization purposes.
    • -
    • support: Contains members representing the browser support information for this feature in all the different browsers we want to report.
    • -
    • status: Contains members reporting the standards track status of this feature.
    • -
    - -

    The names of the browser members are defined in the schema (see Browser identifiers). You should use the full list of currently defined identifiers. If you wish to add another browser, talk to us first, as this could have a wide-ranging impact and should not be done without careful thought.

    - -

    In a basic browser compat data file, you'll only need to include "version_added" inside the browser identifier members (we'll cover Advanced cases later on). The different values you might want to include are as follows:

    - -
      -
    • A version number: If you know the exact version in which a browser started to support your feature, use a string representing the number, e.g. "47".
    • -
    • true: If a browser supports a feature but you don't know the exact version number, use the value true. This equivalent to the \{{CompatVersionUnknown}} macro call in the old manual tables.
    • -
    • false: If a browser does not support a feature, use the value false. This is equivalent to the the \{{CompatNo}} macro call in the old manual tables.
    • -
    • null: If you don't know whether a browser supports a feature or not, use the value null. This is equivalent to the \{{CompatUnknown}} macro call in the old manual tables.
    • -
    - -

    Inside the status member, you'll include three submembers:

    - -
      -
    • "experimental": This should be set to true if the feature is experimental, or false otherwise.
    • -
    • "standard_track": This should be set to true if a feature is on some kind of standards track (most commonly W3C/WHATWG, but there are also other standards efforts such as Khronos, TC39, etc.) or false otherwise.
    • -
    • "deprecated": This should be set to true if the feature is deprecated, or false otherwise.
    • -
    - -

    The feature data for border-width (also see border-width.json) is shown below as an example:

    - -
    "__compat": {
    -  "mdn_url": "https://developer.mozilla.org/docs/Web/CSS/border-width",
    -  "support": {
    -    "chrome": {
    -      "version_added": "1"
    -    },
    -    "webview_android": {
    -      "version_added": "2"
    -    },
    -    "edge": {
    -      "version_added": true
    -    },
    -    "edge_mobile": {
    -      "version_added": true
    -    },
    -    "firefox": {
    -      "version_added": "1"
    -    },
    -    "firefox_android": {
    -      "version_added": "1"
    -    },
    -    "ie": {
    -      "version_added": "4"
    -    },
    -    "ie_mobile": {
    -      "version_added": "6"
    -    },
    -    "opera": {
    -      "version_added": "3.5"
    -    },
    -    "opera_android": {
    -      "version_added": "11"
    -    },
    -    "safari": {
    -      "version_added": "1"
    -    },
    -    "safari_ios": {
    -      "version_added": "3"
    -    }
    -  },
    -  "status": {
    -    "experimental": false,
    -    "standard_track": true,
    -    "deprecated": false
    -  }
    -}
    - -

    Adicionando uma descrição

    - -

    There is a fourth, optional, member that can go inside the __compat member — description. This can be used to include a human-readable description of the feature. You should only include this if it is hard to see what the feature is from glancing at the data. For example, it might not be that obvious what a constructor is from looking at the data structure, so you can include a description like so:

    - -
    {
    -  "api": {
    -    "AbortController": {
    -      "__compat": {
    -        ...
    -      },
    -      "AbortController": {
    -        "__compat": {
    -          "mdn_url": "https://developer.mozilla.org/docs/Web/API/AbortController/AbortController",
    -          "description": "<code>AbortController()</code> constructor",
    -          "support": {
    -            ...
    -          }
    -        }
    -      }
    -
    -      ... etc.
    -    }
    -  }
    -}
    - -

    Sub-recursos

    - -

    In a page where the compat table has more than one row, you'll need multiple subfeatures inside each feature to define the information for each row. This can happen, for example, when you've got the basic support for a feature stored in one row, but then the feature also has a new property or value type that was addded much later in the specification's life and is only supported in a couple of browsers.

    - -

    As an example, see the compat data and corresponding MDN page for the background-color property. The basic support exists inside the __compat object as explained above, then you have an additional row for browsers' support for "alpha channel for hex values", which contains its own __compat object.

    - -
    {
    -  "css": {
    -    "properties": {
    -      "background-color": {
    -        "__compat": {
    -          ...
    -        },
    -        "alpha_ch_for_hex": {
    -          "__compat": {
    -            ...
    -          },
    -        }
    -      }
    -    }
    -  }
    -}
    - -

    For an API, you've got the top two levels defined as api.name-of-the-interface, then a top-level __compat section to define the overall browser compatibility of the interface, then a sub-feature for each of the methods, properties, and constructors contained inside the interface. The basic structure looks like this:

    - -
    {
    -  "api": {
    -    "VRDisplay": {
    -      "__compat": {
    -        ...
    -      },
    -      "cancelAnimationFrame": {
    -        "__compat": {
    -          ...
    -        }
    -      },
    -      "capabilities": {
    -        "__compat": {
    -          ...
    -        }
    -      },
    -
    -      ... etc.
    -
    -    }
    -  }
    -}
    - -

    See VRDisplay.json for a full example.

    -
    - -

    Adicionando dados: Casos avançados

    - -

    There are some advanced features that you'll want to include in browser compat data. The aim of this section is to list the most common ones, providing an example of each to show how you can implement them in your own compat data.

    - -

    Incluindo uma nota de rodapé

    - -

    Often compat tables will include footnotes related to certain entries that explain useful details or strange behavior that developers will find useful. As an example, the Chrome Android entry for {{domxref("VRDisplay.capabilities")}} (see also VRDisplay.json) (at the time of writing) had a footnote "Currently supported only by Google Daydream." To include this in the capabilities data, we added a "notes" submember inside the relevant "chrome_android" submember; it would look like this:

    - -
    "chrome_android": {
    -  "version_added": true,
    -  "notes": "Currently supported only by Google Daydream."
    -}
    - -

    Incluindo um prefixo de fornecedor

    - -

    If a feature is supported behind a vendor prefix in one or more browsers, you'll want to make that clear in the browser compat data. imagine you had a feature that was supported with a -moz- prefix in Firefox. To specify this in the compat data, you'd need to add a "prefix" submember inside the relevant "firefox" submember. It would look something like this:

    - -
    "firefox": {
    -  "version_added": true,
    -  "prefix": "-moz-"
    -}
    - -

    Incluindo preferências ou sinalizadores do navegador

    - -

    Some features may be supported in a browser, but they are experimental and turned off by default. If a user wants to play with this feature they need to turn it on using a preference/flag.

    - -

    To represent this in the compat data, you need to add the "flags" submember inside the relevant browser identifier submember. The value of "flags" is an array of objects each of which contains of three members:

    - -
      -
    • "type": The type of flag or pref this is. The most common value is "preference", which is set inside the browser (for example, using about:config in Firefox, or chrome://flags in Chrome), but you might also sometimes use a value of "compile_flag", which is a preference set when the browser build is compiled.
    • -
    • "name": This is a string representing the name of the preference that needs to have a value set on it. For example, "Enable Experimental Web Platform Features" is a preference that exists in Chrome, found in chrome://flags.
    • -
    • "value_to_set": This is a string representing the value that needs to be set on the preference, for example "true".
    • -
    - -

    So to add a preference/flag to the Chrome support for a feature, you'd do something like this:

    - -
    "chrome": {
    -  "version_added": "50",
    -  "flags": [
    -    {
    -      "type": "preference",
    -      "name": "Enable Experimental Web Platform Features",
    -      "value_to_set": "true"
    -    }
    -  ]
    -},
    - -

    If a feature is behind two or more flags, you can add additional objects to the "flags" array, like in this case, for example:

    - -
    "firefox": {
    -  "version_added": "57",
    -  "flags": [
    -    {
    -      "type": "preference",
    -      "name": "dom.streams.enabled",
    -      "value_to_set": "true"
    -    },
    -    {
    -      "type": "preference",
    -      "name": "javascript.options.streams",
    -      "value_to_set": "true"
    -    }
    -  ]
    -},
    - -

    Incluindo uma versão em que o suporte foi removido

    - -

    Sometimes a feature will be added in a certain browser version, but then removed again as the feature is deprecated. This can be easily represented using the "version_removed" submember, which takes as its value a string representing the version number it was removed on. For example:

    - -
    "firefox": {
    -  "version_added": "35",
    -  "version_removed": "47",
    -},
    - -

    Incluindo vários pontos de suporte para a mesma entrada do navegador

    - -

    Sometimes you'll want to add multiple support data points for the same browser inside the same feature.

    - -

    As an example, the {{cssxref("text-align-last")}} property (see also text-align-last.json) was added to Chrome in version 35, supported behind a pref.

    - -

    The support mentioned above was then removed in version 47; also in version 47, support was added for text-align-last enabled by default.

    - -

    To include both of these data points, you can make the value of the "chrome" submember an array containing two support information objects, rather than just a single support information object:

    - -
    "chrome": [
    -  {
    -    "version_added": "47"
    -  },
    -  {
    -    "version_added": "35",
    -    "version_removed": "47",
    -    "flags": [
    -      {
    -        "type": "preference",
    -        "name": "Enable Experimental Web Platform Features",
    -        "value_to_set": "true"
    -      }
    -    ]
    -  }
    -],
    - -
    -

    Note: You should put the most current or important support point first in the array — this makes the data easier to read for people who just want to scan it for the latest info.

    -
    - -

    Incluindo um nome alternativo

    - -

    Occasionally browsers will support a feature under a different name to the name defined in its specification. This might be for example because a browser added experimental support for a feature early, and then the name changed before the spec stabilized.

    - -

    To include such a case in the browser compat data, you can include a support information point that specifies the alternative name inside an "alternative_name" member.

    - -
    -

    Note: The alternative name might not be an exact alias — it might have differing behaviour to the standard version.

    -
    - -

    Let's look at an example. The {{cssxref("border-top-right-radius")}} property (see also border-top-right-radius.json) was supported in Firefox:

    - -
      -
    • From version 4 onwards with the standard name border-top-right-radius.
    • -
    • From version 49 onwards with a -webkit- prefix, for browser compatibility purposes.
    • -
    • From version 1 onwards with the alternative name -moz-border-radius-topright. Support for this alias was removed in version 12.
    • -
    - -

    To represent this in the data, we used the following JSON:

    - -
    "firefox": [
    -  {
    -    "version_added": "4",
    -    "notes": "Prior to Firefox 50.0, border styles of rounded corners were always rendered as if <code>border-style</code> was solid. This has been fixed in Firefox 50.0."
    -  },
    -  {
    -    "prefix": "-webkit-",
    -    "version_added": "49",
    -    "notes": "From Firefox 44 to 48, the <code>-webkit-</code> prefix was available with the <code>layout.css.prefixes.webkit</code> preference. Starting with Firefox 49, the preference defaults to <code>true</code>."
    -  },
    -  {
    -    "alternative_name": "-moz-border-radius-topright",
    -    "version_added": "1",
    -    "version_removed": "12"
    -  }
    -],
    - -

    Empurrando uma mudança de volta para o repositório principal

    - -

    Once you are finished with adding your compat data, you should first test it using the following commands:

    - -
      -
    • npm run lint — tests all the compat data to make sure the JSON is valid, and is written in the correct style, for example correct indentation, no missing commas, etc. It will print out a long list of file names and test results; if an error is found, the linter will throw an error on the file it is found in, giving you useful debugging info like line number, error message, etc.
    • -
    • npm run show-errors — validates the JSON against the data schema, and highlights errors such as invalid browser version numbers being used.
    • -
    • npm run render dotted.path.to.feature — allows you to preview the markup for the compat table for a data file in the repo. As an example, npm run render css.properties.background shows the table markup for the {{cssxref("background")}} property.
    • -
    - -

    If it is looking OK, you then need to commit it and push it back up to your remote fork on GitHub. You can do this easily with terminal commands like this:

    - -
    git add .
    -git commit -m 'adding compat data for name-of-feature'
    -git push
    - -

    Now go to your remote fork (i.e. https://github.com/your-username/browser-compat-data) and you should see information about your push at the top of the files list (under "Your recently pushed branches"). You can create a pull request (starting the process of pushing this to the main repo) by pressing the "Compare & pull request" button, then following the simple prompts on the subsequent screen.

    - -

    At this point, you just need to wait. A reviewer will review your pull request, and merge it with the main repo, OR request that you make changes. If changes are needed, make the changes and submit again until the PR is accepted.

    - -

    Inserindo os dados em páginas MDN

    - -

    Once your new data has been included in the main repo, you can start dynamically generating browser compat tables based on that data on MDN pages using the \{{Compat}} macro. This takes a single parameter, the dot notation required to walk down the JSON data and find the object representing the feature you want to generate the compat table for.

    - -

    Above the macro call, to help other contributors finding their way, you should add a hidden text that is only visible in MDN contributors in edit mode:

    - -
    <div class="hidden">
    -<p>The compatibility table on this page is generated from structured data.
    -If you'd like to contribute to the data, please check out
    -<a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a>
    -and send us a pull request.</p>
    -</div>
    - -

    As an example, on the {{httpheader("Accept-Charset")}} HTTP header page, the macro call looks like this: \{{Compat("http.headers.Accept-Charset")}}. If you look at the accept-charset.json file in the repo, you'll see how this is reflected in the JSON data.

    - -

    As another example, The compat table for the {{domxref("VRDisplay.capabilities")}} property is generated using \{{Compat("api.VRDisplay.capabilities")}}. The macro call generates the following table (and corresponding set of notes):

    - -
    - -

    {{Compat("api.VRDisplay.capabilities")}}

    - -
    -

    Note: The filenames often match the labels given to the interfaces inside the JSON structures, but it is not always the case. When the macro calls generate the tables, they walk through all the files until they find the relevant JSON to use, so the filenames are not critical. Saying that, you should always name them as intuitively as possible.

    -
    diff --git a/files/pt-br/mdn/writing_guidelines/page_structures/index.md b/files/pt-br/mdn/writing_guidelines/page_structures/index.md new file mode 100644 index 00000000000000..252aea389d17a8 --- /dev/null +++ b/files/pt-br/mdn/writing_guidelines/page_structures/index.md @@ -0,0 +1,482 @@ +--- +title: Tabelas de compatibilidade +slug: MDN/Writing_guidelines/Page_structures +translation_of: MDN/Structures/Compatibility_tables +original_slug: MDN/Structures/Compatibility_tables +--- +{{MDNSidebar}} + +A MDN possui um formato padrão para tabelas de compatibilidade para nossa documentação da Web aberta; isto é, documentação de tecnologias como DOM, HTML, CSS, JavaScript, SVG etc., compartilhadas em todos os navegadores. Este artigo é um guia de "introdução" sobre como adicionar, manter o banco de dados a partir do qual as tabelas de compatibilidade são geradas e como integrar as tabelas em artigos. + +Para obter uma documentação mais avançada, bem como as alterações mais recentes nos processos e esquemas JSON usados ​​para representar os dados, consulte o [guia do colaborador](https://github.com/mdn/browser-compat-data/blob/master/docs/contributing.md) do repositório de dados e o [guia de diretrizes de dados](https://github.com/mdn/browser-compat-data/blob/master/docs/data-guidelines.md). + +Se você tiver dúvidas ou descobrir problemas, compartilhe conosco no [fórum de discussão da MDN](https://discourse.mozilla-community.org/c/mdn). + +## Como acessar o repositório de dados + +Os dados são armazenados em um repositório do GitHub — consulte . Para acessá-lo, você precisa obter uma conta do GitHub, bifurcar (fork) o repositório de dados compatível com o navegador em sua própria conta e, em seguida, clonar seu fork na sua máquina local. + +## Preparando para adicionar os dados + +Antes de adicionar dados novos, verifique que o _fork_ criado tenha o mesmo conteúdo que o repositório principal. Após isso, crie uma nova _branch,_ dentro do _fork_ criado, para conter as mudanças e adições a serem realizadas, em seguida, faça um _pull_ dessa branch no clone local, para então começar a contribuir com o projeto. + +Uma forma simples para ter certeza que o seu _fork_ tem o mesmo conteúdo, e está tão atualizado quanto o repositório principal, é descrita abaixo: + +### Adicionando o repositório principal browser-compat-data como um controle remoto + +Vá para o clone local do seu fork no seu terminal/linha de comando e adicione um controle remoto apontando para o repositório principal (upstream) assim (você só precisa fazer isso uma vez): + +```bash +git remote add upstream https://github.com/mdn/browser-compat-data.git +``` + +Se não tiver certeza se fez isso, verifique os controles remotos que seu repositório está usando + +```bash +git remote -v +``` + +### Atualizando seu fork com o conteúdo do controle remoto + +Agora, sempre que você quiser atualizar seu fork, você pode fazer isso: + +1. Certificando-se de que você está no branch master: + + ```bash + git checkout master + ``` + +2. buscando o conteúdo atualizado do repositório usando: + + ```bash + git fetch upstream + ``` + +3. faça o rebase do seu conteúdo master com o conteúdo do repositório principal: + + ```bash + git rebase upstream/master + ``` + +4. faça o push dessas atualizações de volta ao seu fork remoto usando: + + ```bash + git push -f + ``` + +### Criando um novo branch (ramo) para fazer o seu trabalho + +Em seguida, vá à sua bifurcação remota (será em `https://github.com/seu-nome-de-usuario/browser-compat-data`) e crie um novo ramo para guardar suas mudanças de adição de conteúdo. Isso pode ser feito em: + +1. Clicando no botão "Branch: Master". +2. Colocando um novo nome de ramo dentro do campo de texto de "Encontre ou crie seu ramo...". +3. Clicando no botão "Criar ramo _nome-do-ramo_ a partir de Master". + +Por exemplo, se você quisesse adicionar informações sobre WebVR API, você criaria um ramno chamado algo como "webvr". + +### Mudando para o novo branch (ramo) + +Agora,volte para o seu terminal/linha de comando, e atualize seu clone local da sua bifurcação para incluir o seu novo ramo usando o seguinte comando: + +```bash +git pull +``` + +Agora troque para o seu ramo usando: + +```bash +git checkout name-of-branch +``` + +Agora você deveria estar pronto para adicionar seu conteúdo! + +## Adicionando os dados + +To add the data, you need to create a new file or files to store your compat data in. The files you need to create differ, depending on what technology you are working on: + +- HTML: One file per HTML element, contained in [browser-compat-data/html/elements](https://github.com/mdn/browser-compat-data/tree/master/html/elements). The file should be called the name of the element, all in lower case, e.g. `div.json`. +- CSS: One file per CSS property or selector, contained in the appropriate directory (see [browser-compat-data/css](https://github.com/mdn/browser-compat-data/tree/master/css)). The file should be called the name of the feature, all in lower case, e.g. `background-color.json`, or `hover.json`. +- JS: One file per JS object, contained in [browser-compat-data/javascript/builtins](https://github.com/mdn/browser-compat-data/tree/master/javascript/builtins). The file should be called the exact name of the object, with the casing preserved, e.g. `Date.json` or `InternalError.json`. +- APIs: One file per interface contained in the API, put in [browser-compat-data/api](https://github.com/mdn/browser-compat-data/tree/master/api). Each file should be called the exact name of the interface, with the casing preserved, e.g. The WebVR API has `VRDisplay.json`, `VRDisplayCapabilities.json`, etc. + +> **Nota:** You'll notice that the repo also contains data for [Browser Extensions](/en-US/Add-ons/WebExtensions) and [HTTP](/pt-BR/docs/Web/HTTP). These data sets are basically finished as they stand, but more features may need to be added in the future. + +Each file you create has to follow the pattern defined in the schema contained within our repo; you can see the [detailed schema description here](https://github.com/mdn/browser-compat-data/blob/master/schemas/compat-data-schema.md). + +### Estrutura de dados de compatibilidade básica + +Let's look at an example. CSS property JSON files for example need the following basic structure: + +```json +{ + "css": { + "properties": { + "border-width": { + "__compat": { + ... + } + } + } + } +} +``` + +You have the `css` object, inside of which is a `properties` object. Inside the `properties` object, you need one member for each of the specific features you want to define the compat data for. Each of these members has a `__compat` member, inside of which the actual data goes. + +The above data is found in the [border-width.json](https://github.com/mdn/browser-compat-data/blob/master/css/properties/border-width.json) file — compare this to the [rendered border-width support table on MDN](/pt-BR/docs/Web/CSS/border-width#Browser_compatibility). + +Other types of features work in the same way, but with different object names: + +- CSS selectors work in basically the same way as CSS properties, except that the top-level object structure is `css.selectors` instead of `css.properties`. See [cue.json](https://github.com/mdn/browser-compat-data/blob/master/css/selectors/cue.json) for an example. +- HTML data works in basically the same way, except that the top-level object structure is `html.elements`. See `article.json` for an example. +- The top level object structure for JS built-in objects is `javascript.builtins`; see [Array.json](https://github.com/mdn/browser-compat-data/blob/master/javascript/builtins/Array.json) for an example. + +In HTML, CSS, and JS pages, you'll normally only need one feature. API interfaces work slightly differently — they always have multiple sub-features (see [Sub-features](#sub-features), below). + +### Estrutura básica dentro de um recurso + +Inside a feature `__compat` member, you need to include the following members: + +- `mdn_url`: Contains the URL of the reference page for this feature on MDN. Note that this needs to be written without the locale directory inside, e.g. `/docs/...` not `/docs/en-US/...` (or whatever). This is added in by the macro when the data is put on the page, for localization purposes. +- `support`: Contains members representing the browser support information for this feature in all the different browsers we want to report. +- `status`: Contains members reporting the standards track status of this feature. + +The names of the browser members are defined in the schema (see [Browser identifiers](https://github.com/mdn/browser-compat-data/blob/master/schemas/compat-data-schema.md#browser-identifiers)). You should use the full list of currently defined identifiers. If you wish to add another browser, talk to us first, as this could have a wide-ranging impact and should not be done without careful thought. + +In a basic browser compat data file, you'll only need to include "version_added" inside the browser identifier members (we'll cover [Advanced cases](#advanced_cases) later on). The different values you might want to include are as follows: + +- A version number: If you know the exact version in which a browser started to support your feature, use a string representing the number, e.g. "47". +- `true`: If a browser supports a feature but you don't know the exact version number, use the value `true`. This equivalent to the `\{{CompatVersionUnknown}}` macro call in the old manual tables. +- `false`: If a browser does not support a feature, use the value `false`. This is equivalent to the the `\{{CompatNo}}` macro call in the old manual tables. +- `null`: If you don't know whether a browser supports a feature or not, use the value `null`. This is equivalent to the `\{{CompatUnknown}}` macro call in the old manual tables. + +Inside the `status` member, you'll include three submembers: + +- "experimental": This should be set to `true` if the feature is [experimental](/pt-BR/docs/MDN/Contribute/Guidelines/Conventions_definitions#Experimental), or `false` otherwise. +- "standard_track": This should be set to `true` if a feature is on some kind of standards track (most commonly W3C/WHATWG, but there are also other standards efforts such as Khronos, TC39, etc.) or `false` otherwise. +- "deprecated": This should be set to `true` if the feature is [deprecated](/pt-BR/docs/MDN/Contribute/Guidelines/Conventions_definitions#Deprecated_and_obsolete), or `false` otherwise. + +The feature data for [border-width](/pt-BR/docs/Web/CSS/border-width#Browser_compatibility) (also see [border-width.json](https://github.com/mdn/browser-compat-data/blob/master/css/properties/border-width.json)) is shown below as an example: + +```json +"__compat": { + "mdn_url": "https://developer.mozilla.org/docs/Web/CSS/border-width", + "support": { + "chrome": { + "version_added": "1" + }, + "webview_android": { + "version_added": "2" + }, + "edge": { + "version_added": true + }, + "edge_mobile": { + "version_added": true + }, + "firefox": { + "version_added": "1" + }, + "firefox_android": { + "version_added": "1" + }, + "ie": { + "version_added": "4" + }, + "ie_mobile": { + "version_added": "6" + }, + "opera": { + "version_added": "3.5" + }, + "opera_android": { + "version_added": "11" + }, + "safari": { + "version_added": "1" + }, + "safari_ios": { + "version_added": "3" + } + }, + "status": { + "experimental": false, + "standard_track": true, + "deprecated": false + } +} +``` + +#### Adicionando uma descrição + +There is a fourth, optional, member that can go inside the \_\_compat member — `description`. This can be used to include a human-readable description of the feature. You should only include this if it is hard to see what the feature is from glancing at the data. For example, it might not be that obvious what a constructor is from looking at the data structure, so you can include a description like so: + +```json +{ + "api": { + "AbortController": { + "__compat": { + ... + }, + "AbortController": { + "__compat": { + "mdn_url": "https://developer.mozilla.org/docs/Web/API/AbortController/AbortController", + "description": "AbortController() constructor", + "support": { + ... + } + } + } + + ... etc. + } + } +} +``` + +### Sub-recursos + +In a page where the compat table has more than one row, you'll need multiple subfeatures inside each feature to define the information for each row. This can happen, for example, when you've got the basic support for a feature stored in one row, but then the feature also has a new property or value type that was addded much later in the specification's life and is only supported in a couple of browsers. + +As an example, see the [compat data](https://github.com/mdn/browser-compat-data/blob/master/css/properties/background-color.json) and [corresponding MDN page](/pt-BR/docs/Web/CSS/background-color) for the `background-color` property. The basic support exists inside the `__compat` object as explained above, then you have an additional row for browsers' support for "alpha channel for hex values", which contains its own `__compat` object. + +```json +{ + "css": { + "properties": { + "background-color": { + "__compat": { + ... + }, + "alpha_ch_for_hex": { + "__compat": { + ... + }, + } + } + } + } +} +``` + +For an API, you've got the top two levels defined as `api.name-of-the-interface`, then a top-level `__compat` section to define the overall browser compatibility of the interface, then a sub-feature for each of the methods, properties, and constructors contained inside the interface. The basic structure looks like this: + +```json +{ + "api": { + "VRDisplay": { + "__compat": { + ... + }, + "cancelAnimationFrame": { + "__compat": { + ... + } + }, + "capabilities": { + "__compat": { + ... + } + }, + + ... etc. + + } + } +} +``` + +See [VRDisplay.json](https://github.com/mdn/browser-compat-data/blob/master/api/VRDisplay.json) for a full example. + +## Adicionando dados: Casos avançados + +There are some advanced features that you'll want to include in browser compat data. The aim of this section is to list the most common ones, providing an example of each to show how you can implement them in your own compat data. + +### Incluindo uma nota de rodapé + +Often compat tables will include footnotes related to certain entries that explain useful details or strange behavior that developers will find useful. As an example, the Chrome Android entry for {{domxref("VRDisplay.capabilities")}} (see also [VRDisplay.json](https://github.com/mdn/browser-compat-data/blob/master/api/VRDisplay.json)) (at the time of writing) had a footnote "Currently supported only by Google Daydream." To include this in the capabilities data, we added a "notes" submember inside the relevant "chrome_android" submember; it would look like this: + +```json +"chrome_android": { + "version_added": true, + "notes": "Currently supported only by Google Daydream." +} +``` + +### Incluindo um prefixo de fornecedor + +If a feature is supported behind a vendor prefix in one or more browsers, you'll want to make that clear in the browser compat data. imagine you had a feature that was supported with a `-moz-` prefix in Firefox. To specify this in the compat data, you'd need to add a "prefix" submember inside the relevant "firefox" submember. It would look something like this: + +```json +"firefox": { + "version_added": true, + "prefix": "-moz-" +} +``` + +### Incluindo preferências ou sinalizadores do navegador + +Some features may be supported in a browser, but they are experimental and turned off by default. If a user wants to play with this feature they need to turn it on using a preference/flag. + +To represent this in the compat data, you need to add the "flags" submember inside the relevant browser identifier submember. The value of "flags" is an array of objects each of which contains of three members: + +- "type": The type of flag or pref this is. The most common value is "preference", which is set inside the browser (for example, using `about:config` in Firefox, or `chrome://flags` in Chrome), but you might also sometimes use a value of "compile_flag", which is a preference set when the browser build is compiled. +- "name": This is a string representing the name of the preference that needs to have a value set on it. For example, "Enable Experimental Web Platform Features" is a preference that exists in Chrome, found in `chrome://flags`. +- "value_to_set": This is a string representing the value that needs to be set on the preference, for example "true". + +So to add a preference/flag to the Chrome support for a feature, you'd do something like this: + +```json +"chrome": { + "version_added": "50", + "flags": [ + { + "type": "preference", + "name": "Enable Experimental Web Platform Features", + "value_to_set": "true" + } + ] +}, +``` + +If a feature is behind two or more flags, you can add additional objects to the "flags" array, like in this case, for example: + +```json +"firefox": { + "version_added": "57", + "flags": [ + { + "type": "preference", + "name": "dom.streams.enabled", + "value_to_set": "true" + }, + { + "type": "preference", + "name": "javascript.options.streams", + "value_to_set": "true" + } + ] +}, +``` + +### Incluindo uma versão em que o suporte foi removido + +Sometimes a feature will be added in a certain browser version, but then removed again as the feature is deprecated. This can be easily represented using the "version_removed" submember, which takes as its value a string representing the version number it was removed on. For example: + +```json +"firefox": { + "version_added": "35", + "version_removed": "47", +}, +``` + +### Incluindo vários pontos de suporte para a mesma entrada do navegador + +Sometimes you'll want to add multiple support data points for the same browser inside the same feature. + +As an example, the {{cssxref("text-align-last")}} property (see also [text-align-last.json](https://github.com/mdn/browser-compat-data/blob/master/css/properties/text-align-last.json)) was added to Chrome in version 35, supported behind a pref. + +The support mentioned above was then removed in version 47; also in version 47, support was added for `text-align-last` enabled by default. + +To include both of these data points, you can make the value of the "chrome" submember an array containing two support information objects, rather than just a single support information object: + +```json +"chrome": [ + { + "version_added": "47" + }, + { + "version_added": "35", + "version_removed": "47", + "flags": [ + { + "type": "preference", + "name": "Enable Experimental Web Platform Features", + "value_to_set": "true" + } + ] + } +], +``` + +> **Nota:** You should put the most current or important support point first in the array — this makes the data easier to read for people who just want to scan it for the latest info. + +### Incluindo um nome alternativo + +Occasionally browsers will support a feature under a different name to the name defined in its specification. This might be for example because a browser added experimental support for a feature early, and then the name changed before the spec stabilized. + +To include such a case in the browser compat data, you can include a support information point that specifies the alternative name inside an "alternative_name" member. + +> **Nota:** The alternative name might not be an exact alias — it might have differing behaviour to the standard version. + +Let's look at an example. The {{cssxref("border-top-right-radius")}} property (see also [border-top-right-radius.json](https://github.com/mdn/browser-compat-data/blob/2a0cc3f6bb17aa4345441bed47a059dffd847793/css/properties/border-top-right-radius.json)) was supported in Firefox: + +- From version 4 onwards with the standard name `border-top-right-radius`. +- From version 49 onwards with a `-webkit-` prefix, for browser compatibility purposes. +- From version 1 onwards with the alternative name `-moz-border-radius-topright`. Support for this alias was removed in version 12. + +To represent this in the data, we used the following JSON: + +```json +"firefox": [ + { + "version_added": "4", + "notes": "Prior to Firefox 50.0, border styles of rounded corners were always rendered as if border-style was solid. This has been fixed in Firefox 50.0." + }, + { + "prefix": "-webkit-", + "version_added": "49", + "notes": "From Firefox 44 to 48, the -webkit- prefix was available with the layout.css.prefixes.webkit preference. Starting with Firefox 49, the preference defaults to true." + }, + { + "alternative_name": "-moz-border-radius-topright", + "version_added": "1", + "version_removed": "12" + } +], +``` + +## Empurrando uma mudança de volta para o repositório principal + +Once you are finished with adding your compat data, you should first test it using the following commands: + +- `npm run lint` — tests all the compat data to make sure the JSON is valid, and is written in the correct style, for example correct indentation, no missing commas, etc. It will print out a long list of file names and test results; if an error is found, the linter will throw an error on the file it is found in, giving you useful debugging info like line number, error message, etc. +- `npm run show-errors` — validates the JSON against the data schema, and highlights errors such as invalid browser version numbers being used. +- `npm run render dotted.path.to.feature` — allows you to preview the markup for the compat table for a data file in the repo. As an example, `npm run render css.properties.background` shows the table markup for the {{cssxref("background")}} property. + +If it is looking OK, you then need to commit it and push it back up to your remote fork on GitHub. You can do this easily with terminal commands like this: + +```bash +git add . +git commit -m 'adding compat data for name-of-feature' +git push +``` + +Now go to your remote fork (i.e. `https://github.com/your-username/browser-compat-data`) and you should see information about your push at the top of the files list (under "Your recently pushed branches"). You can create a pull request (starting the process of pushing this to the main repo) by pressing the "Compare & pull request" button, then following the simple prompts on the subsequent screen. + +At this point, you just need to wait. A reviewer will review your pull request, and merge it with the main repo, OR request that you make changes. If changes are needed, make the changes and submit again until the PR is accepted. + +## Inserindo os dados em páginas MDN + +Once your new data has been included in the main repo, you can start dynamically generating browser compat tables based on that data on MDN pages using the \\{{Compat}} macro. This takes a single parameter, the dot notation required to walk down the JSON data and find the object representing the feature you want to generate the compat table for. + +Above the macro call, to help other contributors finding their way, you should add a hidden text that is only visible in MDN contributors in edit mode: + +```html + +``` + +As an example, on the {{httpheader("Accept-Charset")}} HTTP header page, the macro call looks like this: \\{{Compat("http.headers.Accept-Charset")}}. If you look at the [accept-charset.json](https://github.com/mdn/browser-compat-data/blob/master/http/headers/accept-charset.json) file in the repo, you'll see how this is reflected in the JSON data. + +As another example, The compat table for the {{domxref("VRDisplay.capabilities")}} property is generated using \\{{Compat("api.VRDisplay.capabilities")}}. The macro call generates the following table (and corresponding set of notes): + +--- + +{{Compat("api.VRDisplay.capabilities")}} + +> **Nota:** The filenames often match the labels given to the interfaces inside the JSON structures, but it is not always the case. When the macro calls generate the tables, they walk through all the files until they find the relevant JSON to use, so the filenames are not critical. Saying that, you should always name them as intuitively as possible. diff --git a/files/pt-br/mdn/writing_guidelines/page_structures/live_samples/index.html b/files/pt-br/mdn/writing_guidelines/page_structures/live_samples/index.html deleted file mode 100644 index 9601d6d71d0733..00000000000000 --- a/files/pt-br/mdn/writing_guidelines/page_structures/live_samples/index.html +++ /dev/null @@ -1,44 +0,0 @@ ---- -title: Como converter exemplos de codigos para funcionar "ao vivo" -slug: MDN/Writing_guidelines/Page_structures/Live_samples -tags: - - Começando - - Como - - Contribuindo - - Documentação -translation_of: MDN/Contribute/Howto/Convert_code_samples_to_be_live -original_slug: MDN/Contribute/Howto/Convert_code_samples_to_be_live ---- -
    {{MDNSidebar}}

    A MDN agora possui um sistema de "exemplos ao vivo", onde a amostra de código e exibida em uma página que é diretamente utilizado para exibir a saída dessa amostra. No entanto, muitos artigos existentes possuem exemplos de código que ainda não utilizam este sistema, e precisam ser convertidos.

    - - - - - - - - - - - - - - - - -
    Onde isso precisa ser feito?Artigos tagueados com NeedsLiveSample
    O que você precisa saber para fazer a tarefa? -
      -
    • Conhecimento de HTML, CSS e/ou JavaScript, dependendo da amostra de código.
    • -
    • Capacidade de usar macros KumaScript dentro dos artigos da MDN.
    • -
    -
    Quais são os passos para fazer a tarefa? -

    Para uma descrição completa do sistema de exemplos ao vivo, incluindo como criar exemplos ao vivo ,veja Using the live sample system.

    - -
      -
    1. Escolha um artigo da lista lista de artigos que estao tagueados com NeedsLiveSample, em que o exemplo de codigo seja uma feature que seja familiar.
    2. -
    3. Converta o codigo de exemplo para "ao vivo".
    4. -
    5. Apague qualquer codigo ou imagem usada previamente para exibir uma saida de exemplo.
    6. -
    -
    - -

    diff --git a/files/pt-br/mdn/writing_guidelines/page_structures/live_samples/index.md b/files/pt-br/mdn/writing_guidelines/page_structures/live_samples/index.md new file mode 100644 index 00000000000000..c43c139b92aaeb --- /dev/null +++ b/files/pt-br/mdn/writing_guidelines/page_structures/live_samples/index.md @@ -0,0 +1,69 @@ +--- +title: Como converter exemplos de codigos para funcionar "ao vivo" +slug: MDN/Writing_guidelines/Page_structures/Live_samples +tags: + - Começando + - Como + - Contribuindo + - Documentação +translation_of: MDN/Contribute/Howto/Convert_code_samples_to_be_live +original_slug: MDN/Contribute/Howto/Convert_code_samples_to_be_live +--- +{{MDNSidebar}} + +A MDN agora possui um sistema de "exemplos ao vivo", onde a amostra de código e exibida em uma página que é diretamente utilizado para exibir a saída dessa amostra. No entanto, muitos artigos existentes possuem exemplos de código que ainda não utilizam este sistema, e precisam ser convertidos. + + + + + + + + + + + + + + + + +
    Onde isso precisa ser feito? + Artigos tagueados com + NeedsLiveSample +
    O que você precisa saber para fazer a tarefa? +
      +
    • + Conhecimento de HTML, CSS e/ou JavaScript, dependendo da amostra de + código. +
    • +
    • + Capacidade de usar macros + KumaScript + dentro dos artigos da MDN. +
    • +
    +
    Quais são os passos para fazer a tarefa? +

    + Para uma descrição completa do sistema de exemplos ao vivo, incluindo + como criar exemplos ao vivo ,veja + Using the live sample system. +

    +
      +
    1. + Escolha um artigo da lista lista de artigos que estao tagueados com + NeedsLiveSample, em + que o exemplo de codigo seja uma feature que seja familiar. +
    2. +
    3. Converta o codigo de exemplo para "ao vivo".
    4. +
    5. + Apague qualquer codigo ou imagem usada previamente para exibir uma + saida de exemplo. +
    6. +
    +
    diff --git a/files/pt-br/mdn/writing_guidelines/writing_style_guide/index.html b/files/pt-br/mdn/writing_guidelines/writing_style_guide/index.html deleted file mode 100644 index 083ca8af17ac43..00000000000000 --- a/files/pt-br/mdn/writing_guidelines/writing_style_guide/index.html +++ /dev/null @@ -1,566 +0,0 @@ ---- -title: Guia de estilo de escrita -slug: MDN/Writing_guidelines/Writing_style_guide -translation_of: MDN/Guidelines/Writing_style_guide -original_slug: MDN/Guidelines/Writing_style_guide ---- -
    {{MDNSidebar}}
    - -

    Em um esforço para apresentar a documentação de maneira organizada, padronizada e fácil de ler a guia de estilo MDN Web Docs descreve como o texto deve ser organizado, escrito, formatado, e assim por diante. Estas sao orientações mais do que regras estritas. Nos estamos mais interessados em conteúdo do que em formatação, então não se sinta obrigado a aprender a guia de estilo antes de contribuir. Não fique chateado/a ou surpreso/a caso algum/a voluntário/a trabalhador/a edite o seu trabalho de acordo com esta guia.

    - -

    Se você esta procurando por coisas específicas sobre como determinado tipo de página deve ser estruturado, veja a página sobre guia de layout MDN.

    - -

    Os aspetos relacionado a linguagem desta guia aplicam-se principalmente a documentação em Inglês. Outras idiomas devem ter (e são bem-vindos a criar) seu próprio guia de estilo. Estes devem ser publicados como sub-páginas da página do time de localização.

    - -

    Para os estilos padrão que se aplicam ao conteúdo escrito por outros sites que não sejam a MDN, referir-se a guia de estilo Única Mozilla.

    - -

    Básico

    - -

    O melhor lugar para começar em qualquer publicação extensa sobre guia de estilo é com padrões de texto muito simples para ajudar a manter a consistência da documentação. As seguintes seções esboçam alguns destes padrões básicos para ajudar você.

    - -

    Título das Páginas

    - -

    Títulos de páginas são usados em resultados de pesquisa e também usados para estruturar a hierarquia da página na lista de breadcrumb(literalmente migalhas de pão) na parte superior da página. O título da página (que é exibido na parte superior da página e nos resultados de pesquisa) pode ser diferente da página "slug", que é a parte do URL da página que segue "<local>/docs/".

    - -

    Maisuculização de títulos e cabeçalhos

    - -

    Títulos de páginas e seções de cabeçalho devem usar letras maiúsculas no estilo da frase (Maiúsculas so na primeira palavra e nomes próprios) em vez de letras maiúsculas no estilo de título:

    - -
      -
    • Correto: "Um novo método para criar sobreposições Javascript"
    • -
    • Incorreto: "Um Novo Método para Criar Sobreposições Javascript"
    • -
    - -

    Nós temos muitas páginas antigas que foram escritas antes que essa regra de estilo fosse estabelecida. Sinta-se livre para atualizá-las se achar necessário. Estamos atualizando-as gradualmente.

    - -

    Escolhendo títulos e slugs

    - -

    Slugs de página devem ser mantidas curtas; quando criar um novo nível de hierarquia, o componente do novo nível no slug, geralmente, deve ser só uma ou duas palavras.

    - -

    Títulos de páginas, por outro lado, podem ser grandes o quanto quiser, sendo razoável, e devem ser descritivos.

    - -

    Criando novas subárvores

    - -

    Quando você precisar adicionar vários artigos sobre um tópico ou um assunto do tópico, você normalmente fará isso criando uma página de destino e adicionando subpáginas para cada um dos artigos individuais. A página de destino deve abrir com um ou dois parágrafos descrevendo o tópico ou a técnologia e, em seguida, fornecer uma lista de subpáginas com descrições de cada página. Você pode automatizar a inserção de páginas na lista usando algumas macros que criamos.

    - -

    Por exemplo, considere a guia JavaScript, que é estruturada da seguinte forma:

    - - - -

    Tente evitar colocar seu artigo no topo da hierarquia, o que torna lento o site e menos eficiente a pesquisa e a navegação.

    - -

    Orientações gerais do conteúdo do artigo

    - -

    Quando estiver escrevendo qualquer documento é importante conhecer o quanto falar. Se ficar divagando muito o artigo fica tedioso de ler e ninguém ira usa-lo. Escolher a quantidade certa a falar sobre o assunto é muito importante por diversas razões. Entre essas razões: assegurar que o leitor encontre a informação que eles precisam, prover suficiente material de qualidade para os engines de pesquisa poderem analizar e classificar o artigo de maneira adequada. Iremos discutir ao respeito disso aqui. Para aprender um pouco mais sobre como fazer as páginas são classificadas pelos engines de pesquisa, vejam o artigo Como escrever SEO para MDN.

    - -

    Seções, parágrafos e novas linhas

    - -

    Use os níveis de cabeçalho em ordem decrescente na hierarquia: {{HTMLElement("h2")}} depois {{HTMLElement("h3")}} depois {{HTMLElement("h4")}}, sem pular níveis. {{HTMLElement("h2")}} é o maior nível permitido, pois {{HTMLElement("h1")}} está reservado para o título da página. Se perceber que precisará de mais de 3 ou 4 níveis de cabeçalho, considere fragmentar seu artigo em artigos menores, ou colocando uma landing page, linkando estes com o {{TemplateLink("Next")}}, {{TemplateLink("Previous")}}, e {{TemplateLink("PreviousNext")}} macros.

    - -

    O Enter (ou Return) do seu teclado inicia um novo parágrafo. Para inserir uma nova linha sem espaço, faça Shift + Enter.

    - -

    Algumas regras

    - -
      -
    • Não crie listas com apenas um item. Não divida um tópico em um. No mínimo dois, ou nenhum.
    • -
    • Não crie cabeçalhos em sequência. É visualmente feio, e é importante para os leitores apresentar algum texto antes de iniciar outras seções.
    • -
    • Evite usar macros de cabeçalhos, com exceção de algumas macros específicas para tal.
    • -
    • Não use estilos e classes nos cabeçalhos; especificamente falando do elemento <code>. Portanto, não faça um cabeçalho "Usando a interface SuperAmazingThing". Em vez disso, escreva "Usando a interface SuperAmazingThing".
    • -
    - -

    Text formatting and styles

    - -

    Use the "Formatting Styles" drop-down list to apply predefined styles to selected content.

    - -
    Note: The "Note" style is used to call out important notes, like this one.
    - -
    Warning: Similarly, the "Warning" style creates warning boxes like this.
    - -

    Unless specifically instructed to do so, do not use the HTML style attribute to manually style content. If you can't do it using a predefined class, drop into Matrix and ask for help.

    - -

    Code sample style and formatting

    - -

    Tabs and line breaks

    - -

    Use two spaces per tab in all code samples. Code should be indented cleanly, with open-brace ("{") characters on the same line as the statement that opens the block. For example:

    - -
    if (condition) {
    -  /* handle the condition */
    -} else {
    -  /* handle the "else" case */
    -}
    -
    - -

    Long lines shouldn't be allowed to stretch off horizontally to the extent that they require horizontal scrolling to read. Instead, break at natural breaking points. Some examples follow:

    - -
    if (class.CONDITION || class.OTHER_CONDITION || class.SOME_OTHER_CONDITION
    -       || class.YET_ANOTHER_CONDITION ) {
    -  /* something */
    -}
    -
    -var toolkitProfileService = Components.classes["@mozilla.org/toolkit/profile-service;1"]
    -                           .createInstance(Components.interfaces.nsIToolkitProfileService);
    -
    - -

    Inline code formatting

    - -

    Use the "Code" button (labeled with two angle brackets "<>") to apply inline code-style formatting to function names, variable names, and method names (this uses the {{HTMLElement("code")}} element). For example, "the frenchText() function".

    - -

    Method names should be followed by a pair of parentheses: doSomethingUseful(). This helps to differentiate methods from other code terms.

    - -

    Syntax highlighting

    - -

    Screenshot of the "syntax highlighting" menu.Entire lines (or multiple lines) of code should be formatted using syntax highlighting rather than the {{HTMLElement("code")}} element. Click the "pre" button in the toolbar to create the preformatted content box in which you'll then write your code. Then, with the text entry cursor inside the code box, select the appropriate language from the language list button to the right of the "pre" button, as seen in the screenshot to the right. The following example shows text with JavaScript formatting:

    - -
    for (var i = 0, j = 9; i <= 9; i++, j--)
    -  document.writeln("a[" + i + "][" + j + "]= " + a[i][j]);
    - -

    If no appropriate transformation is available, use the pre tag without specifying a language ("No Highlight" in the language menu).

    - -
    x = 42;
    - -

    Styling HTML element references

    - -

    There are various specific rules to follow when writing about HTML elements, in order to consistently describe the various components of elements, and to ensure that they're properly linked to detailed documentation.

    - -
    -
    Element names
    -
    Use the {{TemplateLink("HTMLElement")}} macro, which creates a link to the page for that element. For example, writing \{{HTMLElement("title")}} produces "{{HTMLElement("title")}}". If you don't want to create a link, enclose the name in angle brackets and use "Code (inline)" style (e.g., <title>).
    -
    Attribute names
    -
    Use bold face.
    -
    Attribute definitions
    -
    Use the {{TemplateLink("htmlattrdef")}} macro (e.g., \{{htmlattrdef("type")}}) for the definition term, so that it can be linked to from other pages, then use the {{TemplateLink("htmlattrxref")}} macro (e.g., \{{htmlattrxref("attr","element")}}) to reference attribute definitions.
    -
    Attribute values
    -
    Use "Code (inline)" style, and do not use quotation marks around strings, unless needed by the syntax of a code sample. E.g.: When the type attribute of an <input> element is set to email or tel ...
    -
    Labeling attributes
    -
    Use labels like {{HTMLVersionInline(5)}} thoughtfully. For example, use them next to the bold attribute name but not for every occurrence in your body text.
    -
    - -

    Latin abbreviations

    - -

    In notes and parentheses

    - -
      -
    • Common Latin abbreviations (etc., i.e., e.g.) may be used in parenthetical expressions and in notes. Use periods in these abbreviations. -
        -
      • Correct: Web browsers (e.g. Firefox) can be used ...
      • -
      • Incorrect: Web browsers e.g. Firefox can be used ...
      • -
      • Incorrect: Web browsers, e.g. Firefox, can be used ...
      • -
      • Incorrect: Web browsers, (eg: Firefox) can be used ...
      • -
      -
    • -
    - -

    In running text

    - -
      -
    • In regular text (i.e. text outside of notes or parentheses), use the English equivalent of the abbreviation. -
        -
      • Correct: ... web browsers, and so on.
      • -
      • Incorrect: ... web browsers, etc.
      • -
      • Correct: Web browsers such as Firefox can be used ...
      • -
      • Incorrect: Web browsers e.g. Firefox can be used ...
      • -
      -
    • -
    - -

    Meanings and English equivalents of Latin abbreviations

    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    AbbrevLatinEnglish
    cf.confercompare
    e.g.exempli gratiafor example
    et al.et aliiand others
    etc.et ceteraand so forth, and so on
    i.e.id estthat is, in other words
    N.B.nota benenote well
    P.S.post scriptumpostscript
    - -
    -

    Note: Always consider whether it's truly beneficial to use a Latin abbreviation. Some of these are used so rarely that many readers won't understand the meaning, and others are often confused with one another. And be sure that you use them correctly, if you choose to do so. For example, be careful not to confuse "e.g." with "i.e.", which is a common error.

    -
    - -

    Acronyms and abbreviations

    - -

    Capitalization and periods

    - -

    Use full capitals and delete periods in all acronyms and abbreviations, including organizations such as "US" and "UN".

    - -
      -
    • Correct: XUL
    • -
    • Incorrect: X.U.L.; Xul
    • -
    - -

    Expansion

    - -

    On the first mention of a term on a page, expand acronyms likely to be unfamiliar to users. When in doubt, expand it, or, better, link it to the article or glossary entry describing the technology.

    - -
      -
    • Correct: "XUL (XML User Interface Language) is Mozilla's XML-based language..."
    • -
    • Incorrect: "XUL is Mozilla's XML-based language..."
    • -
    - -

    Plurals of acronyms and abbreviations

    - -

    For plurals of acronyms or abbreviations, add s. Don't use an apostrophe. Ever. Please.

    - -
      -
    • Correct: CD-ROMs
    • -
    • Incorrect: CD-ROM's
    • -
    - -

    Capitalization

    - -

    Use standard English capitalization rules in body text, and capitalize "World Wide Web" and "Web".

    - -

    Keyboard keys should use sentence-style capitalization, not all-caps capitalization. For example, "Enter" not "ENTER."

    - -

    Contractions

    - -

    Use contractions (e.g. "don't", "can't", "shouldn't") if you prefer. We're not that formal!

    - -

    Pluralization

    - -

    Use English-style plurals, not the Latin- or Greek-influenced forms.

    - -
      -
    • Correct: syllabuses, octopuses
    • -
    • Incorrect: syllabi, octopi
    • -
    - -

    Hyphenation

    - -

    Hyphenate compounds when the last letter of the prefix is a vowel and is the same as the first letter of the root.

    - -
      -
    • Correct: email, re-elect, co-op
    • -
    • Incorrect: e-mail, reelect, coop
    • -
    - -

    Gender-neutral language

    - -

    It is a good idea to use gender-neutral language in any kind of writing where gender is irrelevant to the subject matter, to make the text as inclusive as possible. So for example, if you are talking about the actions of a specific man, usage of he/his would be fine, but if the subject is a person of either gender, he/his isn't really appropriate.
    -
    - Let's take the following example:

    - -
    -

    A confirmation dialog appears, asking the user if he allows the web page to make use of his web cam.

    -
    - -
    -

    A confirmation dialog appears, asking the user if she allows the web page to make use of her web cam.

    -
    - -

    Both versions in this case are gender-specific. This could be fixed by using gender-neutral pronouns:

    - -
    -

    A confirmation dialog appears, asking the user if they allow the web page to make use of their web cam.

    -
    - -
    -

    Note: MDN allows the use of this very common syntax (which is controversial among usage authorities), in order to make up for the lack of a neutral gender in English. The use of the third-person plural as a neutral gender pronoun (that is, using "they," them", "their," and "theirs") is an accepted practice, commonly known as "singular 'they.'"

    -
    - -

    You can use both genders:

    - -
    -

    A confirmation dialog appears, asking the user if he or she allows the web page to make use of his/her web cam.

    -
    - -

    making the users plural:

    - -
    -

    A confirmation dialog appears, asking the users if they allow the web page to make use of their web cams.

    -
    - -

    The best solution, of course, is to rewrite and eliminate the pronouns completely:

    - -
    -

    A confirmation dialog appears, requesting the user's permission for web cam access.

    -
    - -
    -

    A confirmation dialog box appears, which asks the user for permission to use the web cam.

    -
    - -

    The last way of dealing with the problem is arguably better, as it is not only grammatically more correct but removes some of the complexity associated with dealing with genders across different languages that may have wildly varying gender rules. This can make translation easier, both for readers reading English, then translating it into their own language as they read, and for localizers translating articles into their own language.

    - -

    Numbers and numerals

    - -

    Dates

    - -

    For dates (not including dates in code samples) use the format "January 1, 1990".

    - -
      -
    • Correct: February 24, 2006
    • -
    • Incorrect: February 24th, 2006; 24 February, 2006; 24/02/2006
    • -
    - -

    Alternately, you can use the YYYY/MM/DD format.

    - -
      -
    • Correct: 2006/02/24
    • -
    • Incorrect: 02/24/2006; 24/02/2006; 02/24/06
    • -
    - -

    Decades

    - -

    For decades, use the format "1990s". Don't use an apostrophe.

    - -
      -
    • Correct: 1990s
    • -
    • Incorrect: 1990's
    • -
    - -

    Plurals of numerals

    - -

    For plurals of numerals add "s". Don't use an apostrophe.

    - -
      -
    • Correct: 486s
    • -
    • Incorrect: 486's
    • -
    - -

    Commas

    - -

    In running text, use commas only in five-digit and larger numbers.

    - -
      -
    • Correct: 4000; 54,000
    • -
    • Incorrect: 4,000; 54000
    • -
    - -

    Punctuation

    - -

    Serial comma

    - -

    Use the serial comma. The serial (also known as "Oxford") comma is the comma that appears before the conjunction in a series of three or more items.

    - -
      -
    • Correct: I will travel on trains, planes, and automobiles.
    • -
    • Incorrect: I will travel on trains, planes and automobiles.
    • -
    - -
    -

    Note: This is in contrast to the One Mozilla style guide, which specifies that the serial comma is not to be used. MDN is an exception to this rule.

    -
    - -

    Spelling

    - -

    For words with variant spellings, always use the first entry at Answers.com. Do not use variant spellings.

    - -
      -
    • Correct: localize, honor
    • -
    • Incorrect: localise, honour
    • -
    - -

    Terminology

    - -

    Obsolete vs. deprecated

    - -

    It's important to be clear on the difference between the terms obsolete and deprecated.

    - -
    -
    Obsolete:
    -
    On MDN, the term obsolete marks an API or technology that is not only no longer recommended, but also no longer implemented in the browser. For Mozilla-specific technologies, the API is no longer implemented in Mozilla code; for Web standard technology, the API or feature is no longer supported by current, commonly-used browsers.
    -
    Deprecated:
    -
    On MDN, the term deprecated marks an API or technology that is no longer recommended, but is still implemented and may still work. These technologies will in theory eventually become obsolete and be removed, so you should stop using them. For Mozilla-specific technologies, the API is still supported in Mozilla code; for Web standard technology, the API or feature has been removed or replaced in a recent version of the defining standard.
    -
    - -

    HTML elements

    - -

    Use "elements" to refer to HTML and XML elements, rather than "tags". In addition, they should almost always be wrapped in "<>", and should be in the {{HTMLElement("code")}} style. Also, at least the first time you reference a given element in a section should use the {{TemplateLink("HTMLElement")}} macro, to create a link to the documentation for the element (unless you're writing within that element's reference document page).

    - -
      -
    • Correct: the {{HTMLElement("span")}} element
    • -
    • Incorrect: the span tag
    • -
    - -

    User interface actions

    - -

    In task sequences, describe user interface actions using the imperative mood. Identify the user interface element by its label and type.

    - -
      -
    • Correct: Click the Edit button.
    • -
    • Incorrect: Click Edit.
    • -
    - -

    Voice

    - -

    While the active voice is generally preferred, the passive voice is also acceptable, given the informal feel of our content. Try to be consistent, though.

    - -

    Wiki markup and usage

    - - - -

    To automatically create a link to a Bugzilla bug, use this template:

    - -
    \{{Bug(322603)}}
    -
    - -

    This results in:

    - -

    {{Bug(322603)}}

    - -

    For WebKit bugs, you can use this template:

    - -
    \{{Webkitbug("322603")}}
    -
    - -

    This results in:

    - -

    {{Webkitbug("322603")}}

    - -

    Page tags

    - -

    Tags provide meta information about a page and/or indicate that a page has specific improvements needed to its content. Every page in the wiki should have tags. You can find details on tagging in our How to properly tag pages guide.

    - -

    The tagging interface lives at the bottom of a page while you're in edit mode, and looks something like this:

    - -

    Screenshot of the UX for adding and removing tags on MDN

    - -

    To add a tag, click in the edit box at the end of the tag list and type the tag name you wish to add. Tags will autocomplete as you type. Press enter (or return) to submit the new tag. Each article may have as many tags as needed. For example, an article about using JavaScript in AJAX programming might have both "JavaScript" and "AJAX" as tags.

    - -

    To remove a tag, simply click the little "X" icon in the tag.

    - -

    Tagging pages that need work

    - -

    In addition to using tags to track information about the documentation's quality and content, we also use them to mark articles as needing specific types of work.

    - -

    Tagging obsolete pages

    - -

    Use the following tags for pages that are not current:

    - -
      -
    • Junk: Use for spam, pages created by mistake, or content that is so bad that it should be deleted. Pages with this tag are deleted from time to time.
    • -
    • Obsolete: Use for content that is technically superceded, but still valid in context. For example an HTML element that is obsolete in HTML5 is still valid in HTML 4.01. You can also use the {{TemplateLink("obsolete_header")}} macro to put a prominent banner on the topic.
    • -
    • Archive: Use for content that is technically superceded and no longer useful. If possible, add a note to the topic referring readers to a more current topic. For example, a page that describes how to use the Mozilla CVS repository should refer readers to a current topic on using Mercurial repos. (If no corresponding current topic exists, use the NeedsUpdate tag, and add an explanation on the Talk page.) Pages with the Archive tag are eventually moved from the main content of MDN to the Archive section.
    • -
    - -

    SEO summary

    - -

    The SEO summary is a very short summary of the page. It will be reported as a summary of the article to robots crawling the site, and will then appear in search results for the page. It is also used by macros that automate the construction of landing pages inside MDN itself.

    - -

    By default, the first pagragraph of the page is used as the SEO summary. However you can override this behavior by marking a section with the "SEO summary" style in the WYSIWYG editor.

    - -

    Landing pages

    - -

    Landing pages are pages at the root of a topic area of the site, such as the main CSS or HTML pages. They have a standard format that consists of three areas:

    - -
      -
    1. A brief (typically one paragraph) overview of what the technology is and what it's used for. See Writing a landing page overview for tips.
    2. -
    3. A two-column list of links with appropriate headings. See Creating a page link list for guidelines.
    4. -
    5. An optional "Browser compatibility" section at the bottom of the page.
    6. -
    - - - -

    The link list section of an MDN landing page consists of two columns. These are created using the following HTML:

    - -
    <div class="row topicpage-table">
    -  <div class="section">
    -    ... left column contents ...
    -  </div>
    -  <div class="section">
    -    ... right column contents ...
    -  </div>
    -</div>
    - -

    The left column should be a list of articles, with an <h2> header at the top of the left column explaining that it's a list of articles about the topic (for example "Documentation and tutorials about foo"); this header should use the CSS class "Documentation". Below that is a <dl> list of articles with each article's link in a <dt> block and a brief one-or-two sentence summary of the article in the corresponding <dd> block.

    - -

    The right column should contain one or more of the following sections, in order:

    - -
    -
    Getting help from the community
    -
    This should provide information on Matrix rooms and mailing lists available about the topic. The heading should use the class "Community".
    -
    Tools
    -
    A list of tools the user can look at to help with the use of the technology described in this section of MDN. The heading should use the class "Tools".
    -
    Related topics
    -
    A list of links to landing pages for other, related, technologies of relevance. The heading should use the class "Related_Topics".
    -
    - -

    <<<finish this once we finalize the landing page standards>>>

    - -

    Using, inserting images

    - -

    It's sometimes helpful to provide an image in an article you create or modify, especially if the article is very technical. To include an image:

    - -
      -
    1. Attach the desired image file to the article (at the bottom of every article in edit mode)
    2. -
    3. Create an image in the WYSIWYG editor
    4. -
    5. In the WYSIWYG editor in the drop-down list listing attachments, select the newly created attachment which is your image
    6. -
    7. Press OK.
    8. -
    - -

    Other References

    - -

    Preferred style guides

    - -

    If you have questions about usage and style not covered here, we recommend referring to the Economist style guide or, failing that, the Chicago Manual of Style.

    - -

    Preferred dictionary

    - -

    For questions of spelling, please refer to Answers.com. The spell-checker for this site uses American English. Please do not use variant spellings (e.g., use honor rather than honour).

    - -

    We will be expanding the guide over time, so if you have specific questions that aren't covered in this document, please send them to the MDC mailing list or project lead so we know what should be added.

    - -

    MDN-specific

    - - - -

    Language, grammar, spelling

    - -

    If you're interested in improving your writing and editing skills, you may find the following resources to be helpful.

    - - diff --git a/files/pt-br/mdn/writing_guidelines/writing_style_guide/index.md b/files/pt-br/mdn/writing_guidelines/writing_style_guide/index.md new file mode 100644 index 00000000000000..96ffb7f5235bdb --- /dev/null +++ b/files/pt-br/mdn/writing_guidelines/writing_style_guide/index.md @@ -0,0 +1,463 @@ +--- +title: Guia de estilo de escrita +slug: MDN/Writing_guidelines/Writing_style_guide +translation_of: MDN/Guidelines/Writing_style_guide +original_slug: MDN/Guidelines/Writing_style_guide +--- +{{MDNSidebar}} + +Em um esforço para apresentar a documentação de maneira organizada, padronizada e fácil de ler a guia de estilo MDN Web Docs descreve como o texto deve ser organizado, escrito, formatado, e assim por diante. Estas sao orientações mais do que regras estritas. Nos estamos mais interessados em conteúdo do que em formatação, então não se sinta obrigado a aprender a guia de estilo antes de contribuir. Não fique chateado/a ou surpreso/a caso algum/a voluntário/a trabalhador/a edite o seu trabalho de acordo com esta guia. + +Se você esta procurando por coisas específicas sobre como determinado tipo de página deve ser estruturado, veja a [página sobre guia de layout MDN](/pt-BR/docs/MDN/Contribute/Content/Layout). + +Os aspetos relacionado a linguagem desta guia aplicam-se principalmente a documentação em Inglês. Outras idiomas devem ter (e são bem-vindos a criar) seu próprio guia de estilo. Estes devem ser publicados como sub-páginas da página do time de localização. + +Para os estilos padrão que se aplicam ao conteúdo escrito por outros sites que não sejam a MDN, referir-se a [guia de estilo Única Mozilla](http://www.mozilla.org/en-US/styleguide/). + +## Básico + +O melhor lugar para começar em qualquer publicação extensa sobre guia de estilo é com padrões de texto muito simples para ajudar a manter a consistência da documentação. As seguintes seções esboçam alguns destes padrões básicos para ajudar você. + +### Título das Páginas + +Títulos de páginas são usados em resultados de pesquisa e também usados para estruturar a hierarquia da página na lista de breadcrumb(literalmente migalhas de pão) na parte superior da página. O título da página (que é exibido na parte superior da página e nos resultados de pesquisa) pode ser diferente da página "slug", que é a parte do URL da página que segue _"\/docs/"._ + +#### Maisuculização de títulos e cabeçalhos + +Títulos de páginas e seções de cabeçalho devem usar letras maiúsculas no estilo da frase (Maiúsculas so na primeira palavra e nomes próprios) em vez de letras maiúsculas no estilo de título: + +- **Correto**: "Um novo método para criar sobreposições Javascript" +- **Incorreto**: "Um Novo Método para Criar Sobreposições Javascript" + +Nós temos muitas páginas antigas que foram escritas antes que essa regra de estilo fosse estabelecida. Sinta-se livre para atualizá-las se achar necessário. Estamos atualizando-as gradualmente. + +#### Escolhendo títulos e slugs + +Slugs de página devem ser mantidas curtas; quando criar um novo nível de hierarquia, o componente do novo nível no slug, geralmente, deve ser só uma ou duas palavras. + +Títulos de páginas, por outro lado, podem ser grandes o quanto quiser, sendo razoável, e devem ser descritivos. + +#### Criando novas subárvores + +Quando você precisar adicionar vários artigos sobre um tópico ou um assunto do tópico, você normalmente fará isso criando uma página de destino e adicionando subpáginas para cada um dos artigos individuais. A página de destino deve abrir com um ou dois parágrafos descrevendo o tópico ou a técnologia e, em seguida, fornecer uma lista de subpáginas com descrições de cada página. Você pode automatizar a inserção de páginas na lista usando algumas macros que criamos. + +Por exemplo, considere a guia [JavaScript](/pt-BR/docs/Web/JavaScript), que é estruturada da seguinte forma: + +- [JavaScript/Guide](/pt-BR/docs/Web/JavaScript/Guide "JavaScript/Guide") - Página principal do sumário. +- [JavaScript/Guide/JavaScript Overview](/pt-BR/docs/Web/JavaScript/Guide/JavaScript_Overview "JavaScript/Guide/JavaScript_Overview") +- [JavaScript/Guide/Functions](/pt-BR/docs/JavaScript/Guide/Functions "JavaScript/Guide/Functions") +- [JavaScript/Guide/Details of the Object Model](/pt-BR/docs/JavaScript/Guide/Details_of_the_Object_Model "JavaScript/Guide/Details_of_the_Object_Model") + +Tente evitar colocar seu artigo no topo da hierarquia, o que torna lento o site e menos eficiente a pesquisa e a navegação. + +### Orientações gerais do conteúdo do artigo + +Quando estiver escrevendo qualquer documento é importante conhecer o quanto falar. Se ficar divagando muito o artigo fica tedioso de ler e ninguém ira usa-lo. Escolher a quantidade certa a falar sobre o assunto é muito importante por diversas razões. Entre essas razões: assegurar que o leitor encontre a informação que eles precisam, prover suficiente material de qualidade para os engines de pesquisa poderem analizar e classificar o artigo de maneira adequada. Iremos discutir ao respeito disso aqui. Para aprender um pouco mais sobre como fazer as páginas são classificadas pelos engines de pesquisa, vejam o artigo [Como escrever SEO para MDN](/pt-BR/docs/MDN/Contribute/Howto/Write_for_SEO). + +### Seções, parágrafos e novas linhas + +Use os níveis de cabeçalho em ordem decrescente na hierarquia: {{HTMLElement("h2")}} depois {{HTMLElement("h3")}} depois {{HTMLElement("h4")}}, sem pular níveis. {{HTMLElement("h2")}} é o maior nível permitido, pois {{HTMLElement("h1")}} está reservado para o título da página. Se perceber que precisará de mais de 3 ou 4 níveis de cabeçalho, considere fragmentar seu artigo em artigos menores, ou colocando uma landing page, linkando estes com o {{TemplateLink("Next")}}, {{TemplateLink("Previous")}}, e {{TemplateLink("PreviousNext")}} macros. + +O Enter (ou Return) do seu teclado inicia um novo parágrafo. Para inserir uma nova linha sem espaço, faça Shift + Enter. + +#### Algumas regras + +- Não crie listas com apenas um item. Não divida um tópico em um. No mínimo dois, ou nenhum. +- Não crie cabeçalhos em sequência. É visualmente feio, e é importante para os leitores apresentar algum texto antes de iniciar outras seções. +- Evite usar macros de cabeçalhos, com exceção de algumas macros específicas para tal. +- Não use estilos e classes nos cabeçalhos; especificamente falando do elemento \. Portanto, não faça um cabeçalho "Usando a interface `SuperAmazingThing`". Em vez disso, escreva "Usando a interface SuperAmazingThing". + +### Text formatting and styles + +Use the "Formatting Styles" drop-down list to apply predefined styles to selected content. + +> **Nota:**The "Note" style is used to call out important notes, like this one. + +> **Aviso:** Similarly, the "Warning" style creates warning boxes like this. + +Unless specifically instructed to do so, **do not** use the HTML `style` attribute to manually style content. If you can't do it using a predefined class, drop into [Matrix](https://chat.mozilla.org/#/room/#mdn:mozilla.org) and ask for help. + +### Code sample style and formatting + +#### Tabs and line breaks + +Use two spaces per tab in all code samples. Code should be indented cleanly, with open-brace ("{") characters on the same line as the statement that opens the block. For example: + +```js +if (condition) { + /* handle the condition */ +} else { + /* handle the "else" case */ +} +``` + +Long lines shouldn't be allowed to stretch off horizontally to the extent that they require horizontal scrolling to read. Instead, break at natural breaking points. Some examples follow: + +```js +if (class.CONDITION || class.OTHER_CONDITION || class.SOME_OTHER_CONDITION + || class.YET_ANOTHER_CONDITION ) { + /* something */ +} + +var toolkitProfileService = Components.classes["@mozilla.org/toolkit/profile-service;1"] + .createInstance(Components.interfaces.nsIToolkitProfileService); +``` + +#### Inline code formatting + +Use the "Code" button (labeled with two angle brackets "<>") to apply inline code-style formatting to function names, variable names, and method names (this uses the {{HTMLElement("code")}} element). For example, "the `frenchText()` function". + +Method names should be followed by a pair of parentheses: `doSomethingUseful()`. This helps to differentiate methods from other code terms. + +#### Syntax highlighting + +![Screenshot of the "syntax highlighting" menu.](https://mdn.mozillademos.org/files/7857/syntax-highlighting-menu.png)Entire lines (or multiple lines) of code should be formatted using syntax highlighting rather than the {{HTMLElement("code")}} element. Click the "pre" button in the toolbar to create the preformatted content box in which you'll then write your code. Then, with the text entry cursor inside the code box, select the appropriate language from the language list button to the right of the "pre" button, as seen in the screenshot to the right. The following example shows text with JavaScript formatting: + +```js +for (var i = 0, j = 9; i <= 9; i++, j--) + document.writeln("a[" + i + "][" + j + "]= " + a[i][j]); +``` + +If no appropriate transformation is available, use the `pre` tag without specifying a language ("No Highlight" in the language menu). + +``` +x = 42; +``` + +#### Styling HTML element references + +There are various specific rules to follow when writing about HTML elements, in order to consistently describe the various components of elements, and to ensure that they're properly linked to detailed documentation. + +- Element names + - : Use the {{TemplateLink("HTMLElement")}} macro, which creates a link to the page for that element. For example, writing \\{{HTMLElement("title")}} produces "{{HTMLElement("title")}}". If you don't want to create a link, **enclose the name in angle brackets** and use "Code (inline)" style (e.g., ``). +- Attribute names + - : Use **bold face**. +- Attribute definitions + - : Use the {{TemplateLink("htmlattrdef")}} macro (e.g., \\{{htmlattrdef("type")}}) for the definition term, so that it can be linked to from other pages, then use the {{TemplateLink("htmlattrxref")}} macro (e.g., \\{{htmlattrxref("attr","element")}}) to reference attribute definitions. +- Attribute values + - : Use "Code (inline)" style, and do not use quotation marks around strings, unless needed by the syntax of a code sample. E.g.: When the **type** attribute of an `<input>` element is set to `email` or `tel` ... +- Labeling attributes + - : Use labels like {{HTMLVersionInline(5)}} thoughtfully. For example, use them next to the bold attribute name but not for every occurrence in your body text. + +### Latin abbreviations + +#### In notes and parentheses + +- Common Latin abbreviations (etc., i.e., e.g.) may be used in parenthetical expressions and in notes. Use periods in these abbreviations. + + - **Correct**: Web browsers (e.g. Firefox) can be used ... + - **Incorrect**: Web browsers e.g. Firefox can be used ... + - **Incorrect**: Web browsers, e.g. Firefox, can be used ... + - **Incorrect**: Web browsers, (eg: Firefox) can be used ... + +#### In running text + +- In regular text (i.e. text outside of notes or parentheses), use the English equivalent of the abbreviation. + + - **Correct**: ... web browsers, and so on. + - **Incorrect**: ... web browsers, etc. + - **Correct**: Web browsers such as Firefox can be used ... + - **Incorrect**: Web browsers e.g. Firefox can be used ... + +#### Meanings and English equivalents of Latin abbreviations + +| Abbrev | Latin | English | +| ------ | ---------------- | ----------------------- | +| cf. | _confer_ | compare | +| e.g. | _exempli gratia_ | for example | +| et al. | _et alii_ | and others | +| etc. | _et cetera_ | and so forth, and so on | +| i.e. | _id est_ | that is, in other words | +| N.B. | _nota bene_ | note well | +| P.S. | _post scriptum_ | postscript | + +> **Nota:** Always consider whether it's truly beneficial to use a Latin abbreviation. Some of these are used so rarely that many readers won't understand the meaning, and others are often confused with one another. And be sure that **you** use them correctly, if you choose to do so. For example, be careful not to confuse "e.g." with "i.e.", which is a common error. + +### Acronyms and abbreviations + +#### Capitalization and periods + +Use full capitals and delete periods in all acronyms and abbreviations, including organizations such as "US" and "UN". + +- **Correct**: XUL +- **Incorrect**: X.U.L.; Xul + +#### Expansion + +On the first mention of a term on a page, expand acronyms likely to be unfamiliar to users. When in doubt, expand it, or, better, link it to the article or [glossary](/pt-BR/docs/Glossary) entry describing the technology. + +- **Correct**: "XUL (XML User Interface Language) is Mozilla's XML-based language..." +- **Incorrect**: "XUL is Mozilla's XML-based language..." + +#### Plurals of acronyms and abbreviations + +For plurals of acronyms or abbreviations, add _s_. Don't use an apostrophe. Ever. Please. + +- **Correct**: CD-ROMs +- **Incorrect**: CD-ROM's + +### Capitalization + +Use standard English capitalization rules in body text, and capitalize "World Wide Web" and "Web". + +Keyboard keys should use sentence-style capitalization, not all-caps capitalization. For example, "Enter" not "ENTER." + +### Contractions + +Use contractions (e.g. "don't", "can't", "shouldn't") if you prefer. We're not that formal! + +### Pluralization + +Use English-style plurals, not the Latin- or Greek-influenced forms. + +- **Correct**: syllabuses, octopuses +- **Incorrect**: syllabi, octopi + +### Hyphenation + +Hyphenate compounds when the last letter of the prefix is a vowel and is the same as the first letter of the root. + +- **Correct**: email, re-elect, co-op +- **Incorrect**: e-mail, reelect, coop + +### Gender-neutral language + +It is a good idea to use gender-neutral language in any kind of writing where gender is irrelevant to the subject matter, to make the text as inclusive as possible. So for example, if you are talking about the actions of a specific man, usage of he/his would be fine, but if the subject is a person of either gender, he/his isn't really appropriate. + +Let's take the following example: + +> A confirmation dialog appears, asking the user if he allows the web page to make use of his web cam. + +> A confirmation dialog appears, asking the user if she allows the web page to make use of her web cam. + +Both versions in this case are gender-specific. This could be fixed by using gender-neutral pronouns: + +> A confirmation dialog appears, asking the user if they allow the web page to make use of their web cam. + +> **Nota:** MDN allows the use of this very common syntax (which is controversial among usage authorities), in order to make up for the lack of a neutral gender in English. The use of the third-person plural as a neutral gender pronoun (that is, using "they," them", "their," and "theirs") is an accepted practice, commonly known as "[singular 'they.'](http://en.wikipedia.org/wiki/Singular_they)" + +You can use both genders: + +> A confirmation dialog appears, asking the user if he or she allows the web page to make use of his/her web cam. + +making the users plural: + +> A confirmation dialog appears, asking the users if they allow the web page to make use of their web cams. + +The best solution, of course, is to rewrite and eliminate the pronouns completely: + +> A confirmation dialog appears, requesting the user's permission for web cam access. + +> A confirmation dialog box appears, which asks the user for permission to use the web cam. + +The last way of dealing with the problem is arguably better, as it is not only grammatically more correct but removes some of the complexity associated with dealing with genders across different languages that may have wildly varying gender rules. This can make translation easier, both for readers reading English, then translating it into their own language as they read, and for localizers translating articles into their own language. + +### Numbers and numerals + +#### Dates + +For dates (not including dates in code samples) use the format "January 1, 1990". + +- **Correct**: February 24, 2006 +- **Incorrect**: February 24th, 2006; 24 February, 2006; 24/02/2006 + +Alternately, you can use the YYYY/MM/DD format. + +- **Correct**: 2006/02/24 +- **Incorrect**: 02/24/2006; 24/02/2006; 02/24/06 + +#### Decades + +For decades, use the format "1990s". Don't use an apostrophe. + +- **Correct**: 1990s +- **Incorrect**: 1990's + +#### Plurals of numerals + +For plurals of numerals add "s". Don't use an apostrophe. + +- **Correct**: 486s +- **Incorrect**: 486's + +#### Commas + +In running text, use commas only in five-digit and larger numbers. + +- **Correct**: 4000; 54,000 +- **Incorrect**: 4,000; 54000 + +### Punctuation + +#### Serial comma + +**Use the serial comma**. The serial (also known as "Oxford") comma is the comma that appears before the conjunction in a series of three or more items. + +- **Correct**: I will travel on trains, planes, and automobiles. +- **Incorrect**: I will travel on trains, planes and automobiles. + +> **Nota:** This is in contrast to the [One Mozilla style guide](http://www.mozilla.org/en-US/styleguide/), which specifies that the serial comma is not to be used. MDN is an exception to this rule. + +### Spelling + +For words with variant spellings, always use the first entry at [Answers.com](http://www.answers.com/library/Dictionary). Do not use variant spellings. + +- **Correct**: localize, honor +- **Incorrect**: localise, honour + +### Terminology + +#### Obsolete vs. deprecated + +It's important to be clear on the difference between the terms **obsolete** and **deprecated**. + +- Obsolete: + - : On MDN, the term **obsolete** marks an API or technology that is not only no longer recommended, but also no longer implemented in the browser. For Mozilla-specific technologies, the API is no longer implemented in Mozilla code; for Web standard technology, the API or feature is no longer supported by current, commonly-used browsers. +- Deprecated: + - : On MDN, the term **deprecated** marks an API or technology that is no longer recommended, but is still implemented and may still work. These technologies will in theory eventually become _obsolete_ and be removed, so you should stop using them. For Mozilla-specific technologies, the API is still supported in Mozilla code; for Web standard technology, the API or feature has been removed or replaced in a recent version of the defining standard. + +#### HTML elements + +Use "elements" to refer to HTML and XML elements, rather than "tags". In addition, they should almost always be wrapped in "<>", and should be in the {{HTMLElement("code")}} style. Also, at least the first time you reference a given element in a section should use the {{TemplateLink("HTMLElement")}} macro, to create a link to the documentation for the element (unless you're writing within that element's reference document page). + +- **Correct**: the {{HTMLElement("span")}} element +- **Incorrect**: the span tag + +#### User interface actions + +In task sequences, describe user interface actions using the imperative mood. Identify the user interface element by its label and type. + +- **Correct**: Click the Edit button. +- **Incorrect**: Click Edit. + +### Voice + +While the active voice is generally preferred, the passive voice is also acceptable, given the informal feel of our content. Try to be consistent, though. + +## Wiki markup and usage + +### External links + +To automatically create a link to a Bugzilla bug, use this template: + +``` +\{{Bug(322603)}} +``` + +This results in: + +{{Bug(322603)}} + +For WebKit bugs, you can use this template: + +``` +\{{Webkitbug("322603")}} +``` + +This results in: + +{{Webkitbug("322603")}} + +### Page tags + +Tags provide meta information about a page and/or indicate that a page has specific improvements needed to its content. Every page in the wiki should have tags. You can find details on tagging in our [How to properly tag pages](/pt-BR/docs/MDN/Contribute/Howto/Tag) guide. + +The tagging interface lives at the bottom of a page while you're in edit mode, and looks something like this: + +![Screenshot of the UX for adding and removing tags on MDN](https://mdn.mozillademos.org/files/7859/tag-interface.png) + +To add a tag, click in the edit box at the end of the tag list and type the tag name you wish to add. Tags will autocomplete as you type. Press enter (or return) to submit the new tag. Each article may have as many tags as needed. For example, an article about using JavaScript in AJAX programming might have both "JavaScript" and "AJAX" as tags. + +To remove a tag, simply click the little "X" icon in the tag. + +#### Tagging pages that need work + +In addition to using tags to track information about the documentation's quality and content, we also use them to mark articles as needing specific types of work. + +#### Tagging obsolete pages + +Use the following tags for pages that are not current: + +- _Junk_: Use for spam, pages created by mistake, or content that is so bad that it should be deleted. Pages with this tag are deleted from time to time. +- _Obsolete_: Use for content that is technically superceded, but still valid in context. For example an HTML element that is obsolete in HTML5 is still valid in HTML 4.01. You can also use the {{TemplateLink("obsolete_header")}} macro to put a prominent banner on the topic. +- _Archive_: Use for content that is technically superceded and no longer useful. If possible, add a note to the topic referring readers to a more current topic. For example, a page that describes how to use the Mozilla CVS repository should refer readers to a current topic on using Mercurial repos. (If no corresponding current topic exists, use the _NeedsUpdate_ tag, and add an explanation on the Talk page.) Pages with the Archive tag are eventually moved from the main content of MDN to the [Archive](/pt-BR/docs/Archive) section. + +### SEO summary + +The SEO summary is a very short summary of the page. It will be reported as a summary of the article to robots crawling the site, and will then appear in search results for the page. It is also used by macros that automate the construction of landing pages inside MDN itself. + +By default, the first pagragraph of the page is used as the SEO summary. However you can override this behavior by marking a section with the ["SEO summary" style in the WYSIWYG editor](/pt-BR/docs/Project:MDN/Contributing/Editor_guide/Editing#Formatting_styles). + +### Landing pages + +**Landing pages** are pages at the root of a topic area of the site, such as the main [CSS](/pt-BR/docs/CSS "CSS") or [HTML](/pt-BR/docs/HTML "HTML") pages. They have a standard format that consists of three areas: + +1. A brief (typically one paragraph) overview of what the technology is and what it's used for. See [Writing a landing page overview](#writing_a_landing_page_overview) for tips. +2. A two-column list of links with appropriate headings. See [Creating a page link list](#creating_a_page_link_list) for guidelines. +3. An **optional** "Browser compatibility" section at the bottom of the page. + +#### Creating a page link list + +The link list section of an MDN landing page consists of two columns. These are created using the following HTML: + +```html +<div class="row topicpage-table"> + <div class="section"> + ... left column contents ... + </div> + <div class="section"> + ... right column contents ... + </div> +</div> +``` + +The left column should be a list of articles, with an `<h2>` header at the top of the left column explaining that it's a list of articles about the topic (for example "Documentation and tutorials about foo"); this header should use the CSS class "Documentation". Below that is a `<dl>` list of articles with each article's link in a `<dt>` block and a brief one-or-two sentence summary of the article in the corresponding `<dd>` block. + +The right column should contain one or more of the following sections, in order: + +- Getting help from the community + - : This should provide information on Matrix rooms and mailing lists available about the topic. The heading should use the class "Community". +- Tools + - : A list of tools the user can look at to help with the use of the technology described in this section of MDN. The heading should use the class "Tools". +- Related topics + - : A list of links to landing pages for other, related, technologies of relevance. The heading should use the class "Related_Topics". + +**<<\<finish this once we finalize the landing page standards>>>** + +## Using, inserting images + +It's sometimes helpful to provide an image in an article you create or modify, especially if the article is very technical. To include an image: + +1. Attach the desired image file to the article (at the bottom of every article in edit mode) +2. Create an image in the WYSIWYG editor +3. In the WYSIWYG editor in the drop-down list listing attachments, select the newly created attachment which is your image +4. Press OK. + +## Other References + +### Preferred style guides + +If you have questions about usage and style not covered here, we recommend referring to the [Economist style guide](http://www.economist.com/research/StyleGuide/) or, failing that, the [Chicago Manual of Style](http://www.amazon.com/gp/product/0226104036/). + +### Preferred dictionary + +For questions of spelling, please refer to [Answers.com](http://www.answers.com/library/Dictionary). The spell-checker for this site uses American English. Please do not use variant spellings (e.g., use _honor_ rather than _honour_). + +We will be expanding the guide over time, so if you have specific questions that aren't covered in this document, please send them to the [MDC mailing list](/pt-BR/docs/Project:Community "Project:en/Community") or [project lead](/User:Sheppy "User:Sheppy") so we know what should be added. + +### MDN-specific + +- [Custom CSS classes](/pt-BR/docs/Project:Custom_CSS_Classes "Project:en/Custom_CSS_Classes") defined for all MDC pages. +- [Custom templates](/pt-BR/docs/Project:Custom_Templates "Project:en/Custom_Templates") created for use on MDC, with explanations. + +### Language, grammar, spelling + +If you're interested in improving your writing and editing skills, you may find the following resources to be helpful. + +- [On Writing Well](http://www.amazon.com/Writing-Well-30th-Anniversary-Nonfiction/dp/0060891548), by William Zinsser (Amazon link) +- [Style: The Basics of Clarity and Grace](http://www.amazon.com/Style-Basics-Clarity-Grace-4th/dp/0205830765/), by Joseph Williams and Gregory Colomb (Amazon link) +- [American Heritage Book of English Usage](http://www.bartleby.com/64/) +- [Common Errors in English](http://www.wsu.edu/~brians/errors/) +- [English Grammar FAQ](http://www-personal.umich.edu/~jlawler/aue.html) (alt.usage.english) +- [Bob's quick guide to the apostrophe, you idiots](http://www.angryflower.com/bobsqu.gif) (funny) +- [Merriam-Webster's Concise Dictionary of English Usage](http://www.amazon.com/Merriam-Websters-Concise-Dictionary-English-Usage/dp/B004L2KNI2) (Amazon link): Scholarly but user-friendly, evidence-based advice; very good for non-native speakers, especially for preposition usage. diff --git a/files/pt-br/mdn/yari/index.html b/files/pt-br/mdn/yari/index.html deleted file mode 100644 index 48ecba9528838b..00000000000000 --- a/files/pt-br/mdn/yari/index.html +++ /dev/null @@ -1,54 +0,0 @@ ---- -title: 'Kuma: MDN''s wiki platform' -slug: MDN/Yari -tags: - - projeto kuma -translation_of: MDN/Kuma -original_slug: MDN/Kuma ---- -<div>{{MDNSidebar}}</div> - -<p>Kuma é a plataforma wiki que auxilia o Mozilla Developer Network. É uma plataforma open source escrita em <a href="http://www.python.org/">Python</a> utilizando o framework <a href="https://www.djangoproject.com/">Django</a>.</p> - -<h2>Documentação do Kuma</h2> - -<dl> - <dt><a href="/en-US/docs/Project:MDN/Kuma/API" title="/en-US/docs/Project:About">A API Kuma</a></dt> - <dd>Kuma provê de uma simples API que lhe permite acessar informações através das páginas, e até enviar novas páginas de conteúdo.</dd> - <dt><a href="/en-US/docs/Project:Introduction_to_KumaScript" title="/en-US/docs/Project:Introduction_to_KumaScript">Introdução ao KumaScript</a>:</dt> - <dd>...o modelo de linguagem Kuma.</dd> - <dt><a href="/en-US/docs/Project:MDN/Kuma/KumaScript_guide" title="/en-US/docs/Project:MDN/Kuma/KumaScript_guide">Usando KumaScript e modelos</a></dt> - <dd>Um guia de como usar modelos KumaScript em um artigo de conteúdo.</dd> - <dt><a href="/en-US/docs/Project:MDN/Kuma/KumaScript_reference" title="/en-US/docs/Project:MDN/Kuma/KumaScript_reference">Referência do KumaScript</a></dt> - <dd>Uma referência para o KumaScript.</dd> - <dt><a href="/en-US/docs/MDN/Kuma/PUT_API">O Kuma PUT API</a></dt> - <dd>O PUT API <strong>experimental</strong> torna possível a criação e atualização de artigos no MDN remotamente. Também é possível, por instância, escrever scripts que automaticamente geram e enviam artigos baseados na IDL ou nos conteúdos dos arquivos de cabeçalho.</dd> - <dt><a href="/en-US/docs/Project:MDN/Kuma/Contributing" title="/en-US/docs/Project:MDN/Kuma/Contributing">Contribuindo para o Kuma</a></dt> - <dd>Um guia de como fazer um fork do Kuma e contribuir para o projeto.</dd> -</dl> - -<p>Classificação de arquivos mais antigos:</p> - -<ul> - <li><a href="/en-US/docs/Project:Getting_started_with_Kuma" title="/en-US/docs/Project:Getting_started_with_Kuma">Começando com o Kuma</a>: informação sobre a plataforma; diferenças entre a plataforma Kuma e a Mindtouch Deki platform</li> - <li><a href="/en-US/docs/Project:MDC_editor_guide" title="/en-US/docs/Project:MDC_editor_guide">A interface de edição MDN</a>: atalhos do teclado; descrição dos componentes de interface e funções</li> -</ul> - -<h2 id="Ferramentas_e_tarefas">Ferramentas e tarefas</h2> - -<dl> - <dt><a href="/en-US/docs/MDN/Kuma/Server_charts">Gráficos do Servidor</a></dt> - <dd>Alguns dos nossos gráficos New Relic</dd> - <dt><a href="https://bugzilla.mozilla.org/buglist.cgi?cmdtype=dorem&remaction=run&namedcmd=mdn-backlog&sharer_id=416309&list_id=6206936" title="https://bugzilla.mozilla.org/buglist.cgi?cmdtype=dorem&remaction=run&namedcmd=mdn-backlog&sharer_id=416309&list_id=6206936">Bugs</a></dt> - <dd>Uma lista dos bugs do Kuma. Sinta-se livre para olha-los e encontrar algo que você gostaria de corrigir. <em>Esse link requer que você logue no Bugzilla.</em></dd> - <dt><a href="/en-US/docs/MDN/Kuma/Tools">Ferrmentas e Links</a></dt> - <dd>Esta página tem uma lista detalhada de várias ferramentas utéis e páginas de documentção. Encontre páginas que nossos desenvolvedores usam todos os dias!</dd> - <dt><a href="https://bugzilla.mozilla.org/enter_bug.cgi?product=Mozilla%20Developer%20Network">Informar um bug</a></dt> - <dd>Se você teve algum problema com o Kuma, ou possui uma ideia para o torna-lo melhor, você pode arquivar um bug!</dd> - <dt><a href="/en-US/docs/Project:MDN/Kuma/Changelog" title="/en-US/docs/Project:MDN/Kuma/Changelog">Log de mudanças</a></dt> - <dd>Uma lista das últimas mundaças enviadas; um ótimo lugar para visualizar o que aconteceu recentemente.</dd> - <dt><a href="http://mzl.la/deployed-mdn">O que é implantado?</a></dt> - <dd>Um quadro de status que mostra o que foi implantado ao server de produção.</dd> - <dt><a href="https://trello.com/b/SyPJAeST/engineering-roadmap">Roteiro de Engenhria</a></dt> - <dd>Quadro do Trello usado para gerenciamento do trabalho regular no projeto do Kuma.</dd> -</dl> diff --git a/files/pt-br/mdn/yari/index.md b/files/pt-br/mdn/yari/index.md new file mode 100644 index 00000000000000..67f24fa6a0f90a --- /dev/null +++ b/files/pt-br/mdn/yari/index.md @@ -0,0 +1,48 @@ +--- +title: 'Kuma: MDN''s wiki platform' +slug: MDN/Yari +tags: + - projeto kuma +translation_of: MDN/Kuma +original_slug: MDN/Kuma +--- +{{MDNSidebar}} + +Kuma é a plataforma wiki que auxilia o Mozilla Developer Network. É uma plataforma open source escrita em [Python](http://www.python.org/) utilizando o framework [Django](https://www.djangoproject.com/). + +## Documentação do Kuma + +- [A API Kuma](/pt-BR/docs/Project:MDN/Kuma/API "/en-US/docs/Project:About") + - : Kuma provê de uma simples API que lhe permite acessar informações através das páginas, e até enviar novas páginas de conteúdo. +- [Introdução ao KumaScript](/pt-BR/docs/Project:Introduction_to_KumaScript): + - : ...o modelo de linguagem Kuma. +- [Usando KumaScript e modelos](/pt-BR/docs/Project:MDN/Kuma/KumaScript_guide) + - : Um guia de como usar modelos KumaScript em um artigo de conteúdo. +- [Referência do KumaScript](/pt-BR/docs/Project:MDN/Kuma/KumaScript_reference) + - : Uma referência para o KumaScript. +- [O Kuma PUT API](/pt-BR/docs/MDN/Kuma/PUT_API) + - : O PUT API **experimental** torna possível a criação e atualização de artigos no MDN remotamente. Também é possível, por instância, escrever scripts que automaticamente geram e enviam artigos baseados na IDL ou nos conteúdos dos arquivos de cabeçalho. +- [Contribuindo para o Kuma](/pt-BR/docs/Project:MDN/Kuma/Contributing) + - : Um guia de como fazer um fork do Kuma e contribuir para o projeto. + +Classificação de arquivos mais antigos: + +- [Começando com o Kuma](/pt-BR/docs/Project:Getting_started_with_Kuma): informação sobre a plataforma; diferenças entre a plataforma Kuma e a Mindtouch Deki platform +- [A interface de edição MDN](/pt-BR/docs/Project:MDC_editor_guide): atalhos do teclado; descrição dos componentes de interface e funções + +## Ferramentas e tarefas + +- [Gráficos do Servidor](/pt-BR/docs/MDN/Kuma/Server_charts) + - : Alguns dos nossos gráficos New Relic +- [Bugs](https://bugzilla.mozilla.org/buglist.cgi?cmdtype=dorem&remaction=run&namedcmd=mdn-backlog&sharer_id=416309&list_id=6206936) + - : Uma lista dos bugs do Kuma. Sinta-se livre para olha-los e encontrar algo que você gostaria de corrigir. _Esse link requer que você logue no Bugzilla._ +- [Ferrmentas e Links](/pt-BR/docs/MDN/Kuma/Tools) + - : Esta página tem uma lista detalhada de várias ferramentas utéis e páginas de documentção. Encontre páginas que nossos desenvolvedores usam todos os dias! +- [Informar um bug](https://bugzilla.mozilla.org/enter_bug.cgi?product=Mozilla%20Developer%20Network) + - : Se você teve algum problema com o Kuma, ou possui uma ideia para o torna-lo melhor, você pode arquivar um bug! +- [Log de mudanças](/pt-BR/docs/Project:MDN/Kuma/Changelog) + - : Uma lista das últimas mundaças enviadas; um ótimo lugar para visualizar o que aconteceu recentemente. +- [O que é implantado?](http://mzl.la/deployed-mdn) + - : Um quadro de status que mostra o que foi implantado ao server de produção. +- [Roteiro de Engenhria](https://trello.com/b/SyPJAeST/engineering-roadmap) + - : Quadro do Trello usado para gerenciamento do trabalho regular no projeto do Kuma.