mirror of
https://github.com/microsoft/Web-Dev-For-Beginners.git
synced 2025-09-03 03:32:55 +02:00
Initial commit
This commit is contained in:
28
5-browser-extension/solution/README.md
Normal file
28
5-browser-extension/solution/README.md
Normal file
@@ -0,0 +1,28 @@
|
||||
# Carbon Trigger Browser Extension: Completed Code
|
||||
|
||||
Using tmrow's C02 Signal API to track electricity usage, build a browser extension so that you can have a reminder right in your browser about how heavy your region's electricity usage is. Using this extension ad hoc will help you to make judgement calls on your activities based on this information.
|
||||
|
||||

|
||||
|
||||
## Getting Started
|
||||
|
||||
You will need to have [npm](https://npmjs.com) installed. Download a copy of this code to a folder on your computer.
|
||||
|
||||
Install all the required packages:
|
||||
|
||||
```
|
||||
npm install
|
||||
```
|
||||
|
||||
Build the extension from webpack
|
||||
|
||||
```
|
||||
npm run build
|
||||
```
|
||||
|
||||
To install on Edge, use the 'three dot' menu on the top right corner of the browser to find the Extensions panel. From there, select 'Load Unpacked' to load a new extension. Open the 'dist' folder at the prompt and the extension will load. To use it, you will need an API key for CO2 Signal's API ([get one here via email](https://www.co2signal.com/) - enter your email in the box on this page) and the [code for your region](http://api.electricitymap.org/v3/zones) corresponding to the [Electricity Map](https://www.electricitymap.org/map) (in Boston, for example, I use 'US-NEISO').
|
||||
|
||||

|
||||
|
||||
Once the API key and region is input into the extension interface, the colored dot in the browser extension bar should change to reflect your region's energy usage and give you a pointer on what energy-heavy activities would be appropriate for you to perform. The concept behind this 'dot' system was given to me by the [Energy Lollipop extension](https://energylollipop.com/) for California emissions.
|
||||
|
1403
5-browser-extension/solution/package-lock.json
generated
Normal file
1403
5-browser-extension/solution/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
29
5-browser-extension/solution/package.json
Normal file
29
5-browser-extension/solution/package.json
Normal file
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"name": "carbon-trigger-extension",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "index.js",
|
||||
"engines": {
|
||||
"npm": ">=9.0.0",
|
||||
"node": ">=18.0.0"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1",
|
||||
"watch": "webpack --watch",
|
||||
"build": "webpack"
|
||||
},
|
||||
"keywords": [
|
||||
"chrome extension",
|
||||
"edge extension",
|
||||
"carbon usage tracker"
|
||||
],
|
||||
"author": "Microsoft Cloud Advocacy Team",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"webpack": "^5.94.0",
|
||||
"webpack-cli": "^5.1.4"
|
||||
},
|
||||
"dependencies": {
|
||||
"axios": "^1.7.4"
|
||||
}
|
||||
}
|
127
5-browser-extension/solution/src/index.js
Normal file
127
5-browser-extension/solution/src/index.js
Normal file
@@ -0,0 +1,127 @@
|
||||
import axios from 'axios';
|
||||
|
||||
// form fields
|
||||
const form = document.querySelector('.form-data');
|
||||
const region = document.querySelector('.region-name');
|
||||
const apiKey = document.querySelector('.api-key');
|
||||
|
||||
// results
|
||||
const errors = document.querySelector('.errors');
|
||||
const loading = document.querySelector('.loading');
|
||||
const results = document.querySelector('.result-container');
|
||||
const usage = document.querySelector('.carbon-usage');
|
||||
const fossilfuel = document.querySelector('.fossil-fuel');
|
||||
const myregion = document.querySelector('.my-region');
|
||||
const clearBtn = document.querySelector('.clear-btn');
|
||||
|
||||
calculateColor = async (value) => {
|
||||
let co2Scale = [0, 150, 600, 750, 800];
|
||||
let colors = ['#2AA364', '#F5EB4D', '#9E4229', '#381D02', '#381D02'];
|
||||
|
||||
let closestNum = co2Scale.sort((a, b) => {
|
||||
return Math.abs(a - value) - Math.abs(b - value);
|
||||
})[0];
|
||||
//console.log(value + ' is closest to ' + closestNum);
|
||||
let num = (element) => element > closestNum;
|
||||
let scaleIndex = co2Scale.findIndex(num);
|
||||
|
||||
let closestColor = colors[scaleIndex];
|
||||
//console.log(scaleIndex, closestColor);
|
||||
|
||||
chrome.runtime.sendMessage({ action: 'updateIcon', value: { color: closestColor } });
|
||||
};
|
||||
|
||||
const displayCarbonUsage = async (apiKey, region) => {
|
||||
try {
|
||||
await axios
|
||||
.get('https://api.co2signal.com/v1/latest', {
|
||||
params: {
|
||||
countryCode: region,
|
||||
},
|
||||
headers: {
|
||||
//please get your own token from CO2Signal https://www.co2signal.com/
|
||||
'auth-token': apiKey,
|
||||
},
|
||||
})
|
||||
.then((response) => {
|
||||
let CO2 = Math.floor(response.data.data.carbonIntensity);
|
||||
|
||||
calculateColor(CO2);
|
||||
|
||||
loading.style.display = 'none';
|
||||
form.style.display = 'none';
|
||||
myregion.textContent = region;
|
||||
usage.textContent =
|
||||
Math.round(response.data.data.carbonIntensity) + ' grams (grams C02 emitted per kilowatt hour)';
|
||||
fossilfuel.textContent =
|
||||
response.data.data.fossilFuelPercentage.toFixed(2) +
|
||||
'% (percentage of fossil fuels used to generate electricity)';
|
||||
results.style.display = 'block';
|
||||
});
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
loading.style.display = 'none';
|
||||
results.style.display = 'none';
|
||||
errors.textContent = 'Sorry, we have no data for the region you have requested.';
|
||||
}
|
||||
};
|
||||
|
||||
// set up api key and region
|
||||
const setUpUser = async (apiKey, region) => {
|
||||
localStorage.setItem('apiKey', apiKey);
|
||||
localStorage.setItem('region', region);
|
||||
loading.style.display = 'block';
|
||||
errors.textContent = '';
|
||||
clearBtn.style.display = 'block';
|
||||
//make initial call
|
||||
displayCarbonUsage(apiKey, region);
|
||||
};
|
||||
|
||||
// handle form submission
|
||||
const handleSubmit = async (e) => {
|
||||
e.preventDefault();
|
||||
setUpUser(apiKey.value, region.value);
|
||||
};
|
||||
|
||||
//initial checks
|
||||
const init = async () => {
|
||||
//if anything is in localStorage, pick it up
|
||||
const storedApiKey = localStorage.getItem('apiKey');
|
||||
const storedRegion = localStorage.getItem('region');
|
||||
|
||||
//set icon to be generic green
|
||||
chrome.runtime.sendMessage({
|
||||
action: 'updateIcon',
|
||||
value: {
|
||||
color: 'green',
|
||||
},
|
||||
});
|
||||
|
||||
if (storedApiKey === null || storedRegion === null) {
|
||||
//if we don't have the keys, show the form
|
||||
form.style.display = 'block';
|
||||
results.style.display = 'none';
|
||||
loading.style.display = 'none';
|
||||
clearBtn.style.display = 'none';
|
||||
errors.textContent = '';
|
||||
} else {
|
||||
//if we have saved keys/regions in localStorage, show results when they load
|
||||
results.style.display = 'none';
|
||||
form.style.display = 'none';
|
||||
displayCarbonUsage(storedApiKey, storedRegion);
|
||||
clearBtn.style.display = 'block';
|
||||
}
|
||||
};
|
||||
|
||||
const reset = async (e) => {
|
||||
e.preventDefault();
|
||||
//clear local storage for region only
|
||||
localStorage.removeItem('region');
|
||||
init();
|
||||
};
|
||||
|
||||
form.addEventListener('submit', (e) => handleSubmit(e));
|
||||
clearBtn.addEventListener('click', (e) => reset(e));
|
||||
|
||||
//start app
|
||||
init();
|
28
5-browser-extension/solution/translation/README.es.md
Normal file
28
5-browser-extension/solution/translation/README.es.md
Normal file
@@ -0,0 +1,28 @@
|
||||
# Extensión del navegador Carbon Trigger: Código completo
|
||||
|
||||
Usando la API de señal C02 de tmrow para rastrear el uso de electricidad, cree una extensión de navegador para que pueda tener un recordatorio directamente en su navegador sobre el consumo de electricidad de su región. El uso de esta extensión ad hoc le ayudará a tomar decisiones sobre sus actividades basándose en esta información.
|
||||
|
||||

|
||||
|
||||
## Empezando
|
||||
|
||||
Deberá tener [npm](https://npmjs.com) instalado. Descargue una copia de este código en una carpeta de su computadora.
|
||||
|
||||
Instale todos los paquetes necesarios:
|
||||
|
||||
```
|
||||
npm install
|
||||
```
|
||||
|
||||
Construye la extensión desde webpack:
|
||||
|
||||
```
|
||||
npm run build
|
||||
```
|
||||
|
||||
Para instalar en Edge, use el menú de 'tres puntos' en la esquina superior derecha del navegador para encontrar el panel Extensiones. Desde allí, seleccione 'Cargar desempaquetado' para cargar una nueva extensión. Abra la carpeta 'dist' cuando se le solicite y se cargará la extensión. Para usarlo, necesitará una clave API para la API de CO2 Signal ([obtenga una aquí por correo electrónico](https://www.co2signal.com/) - ingrese su correo electrónico en el cuadro de esta página) y el [código para su región](http://api.electricitymap.org/v3/zones) correspondiente al [Mapa de electricidad](https://www.electricitymap.org/map) (en Boston, por ejemplo, utilizo 'US- NEISO').
|
||||
|
||||

|
||||
|
||||
Una vez que se ingresa la clave API y la región en la interfaz de extensión, el punto de color en la barra de extensión del navegador debe cambiar para reflejar el uso de energía de su región y darle un indicador sobre las actividades de alto consumo de energía que serían apropiadas para usted. El concepto detrás de este sistema de "puntos" me lo dio la [extensión Energy Lollipop](https://energylollipop.com/) para las emisiones de California.
|
||||
|
28
5-browser-extension/solution/translation/README.fr.md
Normal file
28
5-browser-extension/solution/translation/README.fr.md
Normal file
@@ -0,0 +1,28 @@
|
||||
# Extension de navigateur Carbon Trigger: Completed Code
|
||||
|
||||
En utilisant l'API C02 Signal de tmrow pour suivre la consommation d'électricité, créez une extension de navigateur afin que vous puissiez avoir un rappel directement dans votre navigateur sur la consommation d'électricité de votre région. L'utilisation de cette extension ad hoc vous aidera à porter un jugement sur vos activités sur la base de ces informations.
|
||||
|
||||

|
||||
|
||||
## Débuter
|
||||
|
||||
Vous devrez avoir [npm](https://npmjs.com) installé. Téléchargez une copie de ce code dans un dossier de votre ordinateur.
|
||||
|
||||
Installez tous les packages requis :
|
||||
|
||||
```
|
||||
npm install
|
||||
```
|
||||
|
||||
Build the extension from webpack
|
||||
|
||||
```
|
||||
npm run build
|
||||
```
|
||||
|
||||
Pour installer sur Edge, utilisez le menu 'trois points' dans le coin supérieur droit du navigateur pour trouver le panneau Extensions. À partir de là, sélectionnez 'Charger l'extension décompressée' pour charger une nouvelle extension. Ouvrez le dossier 'dist' à l'invite et l'extension se chargera. Pour l'utiliser, vous aurez besoin d'une clé API pour l'API de CO2 Signal ([obtenez-en une ici par e-mail](https://www.co2signal.com/) - entrez votre e-mail dans la case sur cette page) et le [code pour votre région](http://api.electricitymap.org/v3/zones) correspondant à la [Carte de l'électricité](https://www.electricitymap.org/map) (à Boston, par exemple, j'utilise 'US- NEISO').
|
||||
|
||||

|
||||
|
||||
Une fois que la clé API et la région sont entrées dans l'interface d'extension, le point coloré dans la barre d'extension du navigateur doit changer pour refléter la consommation d'énergie de votre région et vous donner un indicateur sur les activités énergivores qu'il vous serait approprié d'effectuer. Le concept derrière ce système de 'points' m'a été donné par l'[extension Energy Lollipop](https://energylollipop.com/) pour les émissions californiennes.
|
||||
|
27
5-browser-extension/solution/translation/README.hi.md
Normal file
27
5-browser-extension/solution/translation/README.hi.md
Normal file
@@ -0,0 +1,27 @@
|
||||
# कार्बन ट्रिगर ब्राउज़र एक्सटेंशन: पूरा किया हुआ कोड
|
||||
|
||||
बिजली के उपयोग को ट्रैक करने के लिए tmrow के C02 सिग्नल एपीआई का उपयोग करना, एक ब्राउज़र एक्सटेंशन का निर्माण करना ताकि आपके ब्राउज़र में आपके क्षेत्र की बिजली का उपयोग कितना भारी हो, इस बारे में आपको एक रिमाइंडर मिल सके. इस एक्सटेंशन तदर्थ का उपयोग करने से आपको इस जानकारी के आधार पर अपनी गतिविधियों पर निर्णय लेने में मदद मिलेगी.
|
||||
|
||||

|
||||
|
||||
## शुरू करना
|
||||
|
||||
आपको [npm](https://npmjs.com) इंस्टॉल करना होगा । अपने कंप्यूटर पर एक फ़ोल्डर में इस कोड की एक प्रति डाउनलोड करें।
|
||||
|
||||
सभी आवश्यक पैकेज स्थापित करें:
|
||||
|
||||
```
|
||||
npm install
|
||||
```
|
||||
|
||||
वेबपैक से एक्सटेंशन बनाएं
|
||||
|
||||
```
|
||||
npm run build
|
||||
```
|
||||
|
||||
एज पर स्थापित करने के लिए, एक्सटेंशन पैनल को खोजने के लिए ब्राउज़र के ऊपरी दाएं कोने पर 'तीन डॉट' मेनू का उपयोग करें. वहां से, एक नया एक्सटेंशन लोड करने के लिए 'लोड अनपैक्ड' चुनें. प्रॉम्प्ट पर 'dist' फ़ोल्डर खोलें और एक्सटेंशन लोड होगा. इसका उपयोग करने के लिए, आपको CO2 सिग्नल की एपीआई ([ईमेल के माध्यम से यहां प्राप्त करें](https://www.co2snal.com/) के लिए एक एपीआई कुंजी की आवश्यकता होगी - इस पृष्ठ पर बॉक्स में अपना ईमेल दर्ज करें) और [अपने क्षेत्र के लिए कोड](http://api.electricitymap.org/v3/zones) [विद्युत मानचित्र](https://www.electricitymap.org/map) (उदाहरण के लिए, बोस्टन में, मैं 'US-NEISO' का उपयोग करता हूं).
|
||||
|
||||

|
||||
|
||||
एक बार एपीआई कुंजी और क्षेत्र एक्सटेंशन इंटरफ़ेस में इनपुट हो जाने के बाद, ब्राउज़र एक्सटेंशन बार में रंगीन डॉट को आपके क्षेत्र की ऊर्जा के उपयोग को प्रतिबिंबित करने के लिए बदलना चाहिए और आपको एक संकेतक देना चाहिए कि ऊर्जा-भारी गतिविधियां आपके प्रदर्शन के लिए क्या उपयुक्त होंगी।. इस 'डॉट' प्रणाली के पीछे की अवधारणा मुझे कैलिफ़ोर्निया उत्सर्जन के लिए [एनर्जी लॉलीपॉप एक्सटेंशन](https://energylollipop.com/) द्वारा दी गई थी।
|
27
5-browser-extension/solution/translation/README.it.md
Normal file
27
5-browser-extension/solution/translation/README.it.md
Normal file
@@ -0,0 +1,27 @@
|
||||
# Estensione del browser Carbon Trigger: codice per partire
|
||||
|
||||
Si utilizzerà l'API Signal C02 di tmrow per monitorare l'utilizzo dell'elettricità per creare un'estensione per il browser in modo da poter avere un promemoria direttamente nel proprio browser su quanto sia pesante l'utilizzo di elettricità nella propria regione. L'utilizzo di questa estensione ad hoc aiuterà a valutare le proprie attività in base a queste informazioni.
|
||||
|
||||

|
||||
|
||||
## Per Iniziare
|
||||
|
||||
E' necessario che [npm](https://npmjs.com) sia installato. Scaricare una copia di questo codice in una cartella del proprio computer.
|
||||
|
||||
Installare tutti i pacchetti richiesti:
|
||||
|
||||
```
|
||||
npm install
|
||||
```
|
||||
|
||||
Creare l'estensione da webpack
|
||||
|
||||
```
|
||||
npm run build
|
||||
```
|
||||
|
||||
Per installare su Edge, utilizzare il menu "tre punti" nell'angolo in alto a destra del browser per trovare il pannello Estensioni. Se non già attiva, attivare la Modalità sviluppatore (in basso a sinistra). Selezionare "Carica decompressa" per caricare una nuova estensione. Aprire la cartella "dist" al prompt e l'estensione verrà caricata. Per usarla, si avrà bisogno di una chiave API per l'API di CO2 Signal (si può[ ottenere qui via e-mail](https://www.co2signal.com/) - inserire la propria e-mail nella casella in questa pagina) e il [codice per la propria regione](http://api.electricitymap.org/v3/zones) corrispondente alla [mappa elettrica](https://www.electricitymap.org/map) (a Boston, ad esempio, "US-NEISO").
|
||||
|
||||

|
||||
|
||||
Una volta che la chiave API e la regione sono state inserite nell'interfaccia dell'estensione, il punto colorato nella barra dell'estensione del browser dovrebbe cambiare per riflettere l'utilizzo di energia della regione e fornire un puntatore su quali attività ad alto consumo energetico sarebbero appropriate da eseguire. Il concetto alla base di questo sistema a "punti" è stato fornito dall' [estensione Energy Lollipop](https://energylollipop.com/) per le emissioni della California.
|
28
5-browser-extension/solution/translation/README.ja.md
Normal file
28
5-browser-extension/solution/translation/README.ja.md
Normal file
@@ -0,0 +1,28 @@
|
||||
# カーボントリガーブラウザ拡張機能: 完成したコード
|
||||
|
||||
tmrow の C02 シグナル API を使用して電力使用量を追跡するために、あなたの地域の電力使用量がどれだけ多いかをブラウザ上でリマインダーとして表示できるようにブラウザ拡張機能を構築します。この拡張機能をアドホックに使用することで、この情報に基づいてあなたの活動を判断することができます。
|
||||
|
||||

|
||||
|
||||
## はじめに
|
||||
|
||||
[npm](https://npmjs.com) がインストールされている必要があります。このコードのコピーをコンピュータ上のフォルダにダウンロードしてください。
|
||||
|
||||
必要なパッケージをすべてインストールします。
|
||||
|
||||
```
|
||||
npm install
|
||||
```
|
||||
|
||||
webpack から拡張機能をビルドします。
|
||||
|
||||
```
|
||||
npm run build
|
||||
```
|
||||
|
||||
Edge にインストールするには、ブラウザの右上にある「3つのドット」メニューから「拡張機能」パネルを見つけます。そこから「Load Unpacked」を選択して、新しい拡張機能をロードします。プロンプトで「dist」フォルダを開くと、拡張機能が読み込まれます。使用するには、CO2 シグナル API の API キー ([get one here via email](https://www.co2signal.com/) - このページのボックスにメールを入力してください) と、[Electricity Map](https://www.electricitymap.org/map) に対応する [code for your region](http://api.electricitymap.org/v3/zones) が必要です (ボストンでは、例えば、'US-NEISO' を使用しています)。
|
||||
|
||||

|
||||
|
||||
API キーと地域を拡張インターフェイスに入力すると、ブラウザの拡張バーに表示される色付きのドットが変化し、あなたの地域のエネルギー使用量を反映して、どのようなエネルギーを必要とする活動を行うのが適切なのかを示してくれます。この「ドット」システムのコンセプトは、カリフォルニア州の排出量のための [Energy Lollipop extension](https://energylollipop.com/) が私に与えてくれたものです。
|
||||
|
27
5-browser-extension/solution/translation/README.ms.md
Normal file
27
5-browser-extension/solution/translation/README.ms.md
Normal file
@@ -0,0 +1,27 @@
|
||||
# Sambungan Penyemak Imbas Carbon Trigger: Kod Lengkap
|
||||
|
||||
Menggunakan API Isyarat C02 tmrow untuk mengesan penggunaan elektrik, bina pelanjutan penyemak imbas sehingga anda dapat memperoleh peringatan di penyemak imbas anda tentang betapa berat penggunaan elektrik wilayah anda. Menggunakan pelanjutan ini secara khusus akan membantu anda membuat pertimbangan mengenai aktiviti anda berdasarkan maklumat ini.
|
||||
|
||||

|
||||
|
||||
## Bermula Dari Sini
|
||||
|
||||
Anda perlu memasang [npm] (https://npmjs.com). Muat turun salinan kod ini ke folder di komputer anda.
|
||||
|
||||
Pasang semua pakej yang diperlukan:
|
||||
|
||||
```
|
||||
npm install
|
||||
```
|
||||
|
||||
Bina pelanjutan dari webpack
|
||||
|
||||
```
|
||||
npm run build
|
||||
```
|
||||
|
||||
Untuk memasang di Edge, gunakan menu 'tiga titik' di sudut kanan atas penyemak imbas untuk mencari panel Sambungan. Dari sana, pilih 'Load Unpacked' untuk memuat sambungan baru. Buka folder 'dist' pada permintaan dan pelanjutan akan dimuat. Untuk menggunakannya, anda memerlukan kunci API untuk API Isyarat CO2 ([dapatkan satu di sini melalui e-mel](https://www.co2signal.com/) - masukkan e-mel anda di dalam kotak di halaman ini) dan [kod untuk wilayah anda](http://api.electricitymap.org/v3/zones) yang sesuai dengan [Peta Elektrik](https://www.electricitymap.org/map) (di Boston, misalnya, saya menggunakan 'US- NEISO').
|
||||
|
||||

|
||||
|
||||
Setelah kunci API dan wilayah dimasukkan ke antara muka peluasan, titik berwarna di bar pelanjutan penyemak imbas akan berubah untuk mencerminkan penggunaan tenaga wilayah anda dan memberi anda petunjuk mengenai aktiviti berat yang sesuai untuk anda lakukan. Konsep di sebalik sistem 'dot' ini diberikan kepada saya oleh [pelanjutan penyemak imbas Lollipop Tenaga](https://energylollipop.com/) untuk pelepasan California.
|
Reference in New Issue
Block a user