npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

langs-page

v1.4.5

Published

Tradutor de páginas da web usando a API do Google Translate

Downloads

12

Readme

Logo

Langs Page

Pacote JavaScript para integração com a API de tradução do Google. Suporta tradução automática entre vários idiomas.

Instalação

Instale o pacote usando npm ou yarn:

npm

  npm install langs-page

yarn

  yarn add langs-page

Ou caso prefira pode usar CDN:

CDN

<script src="https://unpkg.com/[email protected]" defer></script>

Exemplos

Você pode usar as funções com Service Worker para melhorar a performance e UX:

  • Crie o arquivo translateService.js no seu projeto. Este arquivo irá conter a lógica para configurar o Service Worker e traduzir os textos na página.
import { configure, translateText, langs } from "langs-page";

let config = {};
let serviceWorkerInitialized = false;
let serviceWorkerRegistration = null;

// Configuração inicial do pacote
export function setupTranslation(defaultLang, targetLangs) {
  try {
    config = configure(defaultLang, targetLangs);
  } catch (error) {
    console.error("Erro na configuração de idioma:", error.message);
  }
}

// Função para traduzir um texto diretamente
export async function translateTextDirect(text, toLang) {
  try {
    const translation = await translateText(text, config.defaultLang, toLang);
    return translation;
  } catch (error) {
    console.error("Erro na tradução:", error.message);
    return text; // Retorna o texto original em caso de erro
  }
}

// Função para traduzir um texto usando Service Worker
export async function translateTextUsingServiceWorker(text, toLang) {
  if (!serviceWorkerInitialized) {
    await initializeServiceWorker();
  }

  return new Promise((resolve, reject) => {
    const messageChannel = new MessageChannel();
    messageChannel.port1.onmessage = (event) => {
      if (event.data.translated) {
        resolve(event.data.translated);
      } else {
        reject(new Error("Tradução falhou no Service Worker"));
      }
    };

    navigator.serviceWorker.controller.postMessage(
      {
        type: "TRANSLATE_TEXT",
        text,
        toLang,
        defaultLang: config.defaultLang,
      },
      [messageChannel.port2]
    );
  });
}

// Retorna a lista de idiomas suportados
export function getSupportedLanguages() {
  return Object.keys(langs).map((key) => ({ code: key, name: langs[key] }));
}

// Função para inicializar o Service Worker
async function initializeServiceWorker() {
  if ("serviceWorker" in navigator) {
    try {
      const registration = await navigator.serviceWorker.register(
        "/translateService.js"
      );
      serviceWorkerRegistration = registration;
      serviceWorkerInitialized = true;
    } catch (error) {
      console.error("Falha ao registrar o Service Worker:", error.message);
    }
  } else {
    console.error("Service Worker não é suportado neste navegador.");
  }
}

// Listener para mensagens do Service Worker
if ("serviceWorker" in navigator) {
  navigator.serviceWorker.addEventListener("message", async (event) => {
    const { type, text, toLang, defaultLang } = event.data;

    if (type === "TRANSLATE_TEXT") {
      try {
        const translation = await translateTextDirect(
          text,
          defaultLang,
          toLang
        );
        event.ports[0].postMessage({ translated: translation });
      } catch (error) {
        console.error(
          "Erro ao traduzir texto no Service Worker:",
          error.message
        );
        event.ports[0].postMessage({ translated: text }); // Retorna o texto original em caso de erro
      }
    }
  });
}
  • Agora, integre o serviço de tradução no seu componente principal React incluindo um dropdown de idiomas para seleção e a tradução dos textos da página.
import React, { useState, useEffect } from "react";
import {
  setupTranslation,
  translateTextUsingServiceWorker,
  getSupportedLanguages,
} from "./translateService";

export default function App() {
  // Configurando idiomas padrão e de destino
  const { defaultLang, targetLangs } = setupTranslation("pt", ["en", "es"]);

  const [currentLang, setCurrentLang] = useState(defaultLang);
  const [translatedText, setTranslatedText] = useState("");

  // Lista de idiomas suportados para dropdown
  const supportedLanguages = getSupportedLanguages();

  // Função para traduzir o texto
  const translatePage = async () => {
    const textToTranslate = document.body.innerText;

    try {
      const translated = await translateTextUsingServiceWorker(
        textToTranslate,
        currentLang
      );
      setTranslatedText(translated);
    } catch (error) {
      console.error("Erro ao traduzir:", error.message);
    }
  };

  useEffect(() => {
    translatePage(); // Traduz a página ao carregar
  }, [currentLang]);

  const handleLangChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    setCurrentLang(e.target.value);
  };

  return (
    <div>
      <select value={currentLang} onChange={handleLangChange}>
        {supportedLanguages.map((lang) => (
          <option key={lang.code} value={lang.code}>
            {lang.code.toUpperCase()} - {lang.name}
          </option>
        ))}
      </select>

      <div dangerouslySetInnerHTML={{ __html: translatedText }} />
    </div>
  );
}

Licença

MIT

Autores