Skip to content

Commit

Permalink
Add translation instructions (#185)
Browse files Browse the repository at this point in the history
  • Loading branch information
melloware authored Aug 1, 2024
1 parent 6b429a6 commit f3f9b03
Show file tree
Hide file tree
Showing 4 changed files with 101 additions and 17 deletions.
32 changes: 32 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -180,3 +180,35 @@ Use:
| aria.zoomImage | Zoom Image
| aria.zoomIn | Zoom In
| aria.zoomOut | Zoom Out

## Adding New Values

To add a new value to the translation files, follow these steps:

1. **Add to `en.json`**: First, add the new key-value pair to the `en.json` file. This file serves as the source for all translations.

2. **Obtain Google Translate API Key**: You'll need a Google Translate API key to run the translation script. If you don't have one, follow Google's instructions to obtain an API key.

3. **Update `script-translate.js`**: Once you have the API key, update the `script-translate.js` file. Locate the following line and replace `'REPLACEME'` with your actual API key:

```js
const apiKey = 'REPLACEME'; // Replace with your API key
```

**Note**: Be careful not to commit this change to version control to keep your API key private.

4. **Run the Translation Script**: After adding your new key to `en.json` and updating the API key, run the translation script:

```bash
node script-translate.js
```

This script will:
- Read all language JSON files
- Identify the new key(s) added to `en.json`
- Translate the new value(s) to all other languages
- Update all language files with the new translations

5. **Review Translations**: After running the script, it's a good practice to review the generated translations for accuracy.

By following these steps, you ensure that new values are consistently added and translated across all language files in your project.
1 change: 0 additions & 1 deletion en.json
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,6 @@
"zoomImage": "Zoom Image",
"zoomIn": "Zoom In",
"zoomOut": "Zoom Out"

}
}
}
22 changes: 22 additions & 0 deletions script-genimports.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
const fs = require('fs');
const path = require('path');

// Set the directory where your JSON files are located
const jsonDir = '.';

// Read all files in the directory
fs.readdir(jsonDir, (err, files) => {
if (err) {
console.error(`Error reading directory: ${err}`);
return;
}

// Filter out JSON files
files.filter(file => path.extname(file) === '.json').forEach(file => {
// Get the filename without the extension
const filename = path.basename(file, '.json').replace(/-/g, '_');

// Print the import statement
console.log(`import locale_${filename} from 'primelocale/${file}';`);
});
});
63 changes: 47 additions & 16 deletions translate.js → script-translate.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
const fs = require('fs');
let promises = [];

// Function to read JSON file
/**
* Reads and parses a JSON file.
* @param {string} filename - The name of the file to read.
* @returns {Object|null} The parsed JSON object or null if an error occurs.
*/
function readJSONFile(filename) {
try {
const data = fs.readFileSync(filename, 'utf8');
Expand All @@ -12,19 +16,31 @@ function readJSONFile(filename) {
}
}

// Function to write JSON file
/**
* Writes data to a JSON file after sorting it.
* @param {string} filename - The name of the file to write to.
* @param {Object} data - The data to write to the file.
* @returns {Promise<void>}
*/
async function writeJSONFile(filename, data) {
try {
// Wait for all pending promises to settle
await Promise.allSettled(promises);
promises = [];

// Write sorted data to file
fs.writeFileSync(filename, JSON.stringify(sortJsonObject(data), null, 2));
console.log(`Data written to ${filename}`);
} catch (err) {
console.error(`Error writing to ${filename}:`, err);
}
}

/**
* Sorts a JSON object recursively.
* @param {Object} obj - The object to sort.
* @returns {Object} A new sorted object.
*/
function sortJsonObject(obj) {
const keysWithSubobjects = [];
const keysWithoutSubobjects = [];
Expand Down Expand Up @@ -54,20 +70,23 @@ function sortJsonObject(obj) {
return sortedObj;
}


// Function to translate text using Google Translate API
/**
* Translates text using Google Translate API.
* @param {string} text - The text to translate.
* @param {string} targetLanguage - The target language code.
* @returns {Promise<string>} The translated text.
*/
async function translateText(text, targetLanguage) {
const apiKey = 'REPLACEME'; // Replace with your API key
const url = `https://translation.googleapis.com/language/translate/v2?key=${apiKey}`;

const response = await fetch(url, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
charset: 'UTF-8',

},
Accept: 'application/json',
'Content-Type': 'application/json',
charset: 'UTF-8',
},
body: JSON.stringify({
q: text,
target: targetLanguage
Expand All @@ -78,16 +97,23 @@ async function translateText(text, targetLanguage) {
return data.data.translations[0].translatedText;
}

// Function to recursively copy missing keys from source to destination
/**
* Recursively copies missing keys from source to destination, translating as necessary.
* @param {Object} sourceData - The source data object.
* @param {Object} destinationData - The destination data object.
* @param {string} targetLanguage - The target language code.
*/
function copyMissingKeys(sourceData, destinationData, targetLanguage) {
for (const key in sourceData) {
if (!(key in destinationData)) {
const englishText = sourceData[key];


// Special handling for certain keys
if (key === "am" || key === "pm" || key === "fileSizeTypes") {
destinationData[key] = englishText;
console.log(`Added key '${key}' with value '${englishText}'`);
} else {
// Translate and add the key
const promise = translateText(englishText, targetLanguage)
.then(translation => {
console.log(`Translated "${englishText}" to ${targetLanguage}: "${translation}"`);
Expand All @@ -101,12 +127,17 @@ function copyMissingKeys(sourceData, destinationData, targetLanguage) {
promises.push(promise);
}
} else if (typeof sourceData[key] === 'object' && typeof destinationData[key] === 'object') {
// Recursively handle nested objects
copyMissingKeys(sourceData[key], destinationData[key], targetLanguage);
}
}
}

// Function to copy missing keys from source to destination
/**
* Copies missing keys from source file to all destination files in a directory.
* @param {string} sourceFile - The path to the source file.
* @param {string} destinationDir - The path to the destination directory.
*/
function copyMissingKeysRecursive(sourceFile, destinationDir) {
const sourceData = readJSONFile(sourceFile);

Expand All @@ -124,18 +155,19 @@ function copyMissingKeysRecursive(sourceFile, destinationDir) {
files.forEach(file => {
const destinationFile = `${destinationDir}/${file}`;

// Process only JSON files that are not the source file or package.json
if (file.endsWith('.json') && !destinationFile.endsWith(sourceFile) && !file.endsWith('package.json')) {
let destinationData = readJSONFile(destinationFile) || {};

if (!destinationData) {
console.error(`Error reading ${destinationFile}. Skipping.`);
return;
}

const sourceLanguage = Object.keys(sourceData)[0];
const destinationLanguage = Object.keys(destinationData)[0];

if (!sourceLanguage || !destinationLanguage) {
if (!sourceLanguage || !destinationLanguage) {
console.error("Root keys not found in source or destination file.");
return;
}
Expand All @@ -154,4 +186,3 @@ const sourceFile = 'en.json';
const destinationDir = '.';

copyMissingKeysRecursive(sourceFile, destinationDir);

0 comments on commit f3f9b03

Please sign in to comment.