Skip to content

Commit

Permalink
refactor: update script for translation support
Browse files Browse the repository at this point in the history
  • Loading branch information
ngocjohn committed Aug 8, 2024
1 parent b683f50 commit ddd3bca
Show file tree
Hide file tree
Showing 4 changed files with 74 additions and 48 deletions.
105 changes: 60 additions & 45 deletions scripts/update-languages.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
// The missing translations are output to the console and saved to a file named missing_translations.json. The file will the list of lang.json with the missing keys and their values.

// Usage: npm run update-languages (from the root of the project)
// Terminal: node scripts/update-languages.js
// Terminal: node scripts/update-languages.js [lang.json]

const fs = require('fs');
const path = require('path');
Expand All @@ -18,7 +18,8 @@ const languagesFolder = path.resolve(__dirname, '../src/languages');

// Path to the English language file
const enFilePath = path.join(languagesFolder, 'en.json');
const missingTranslationsFilePath = path.join(__dirname, 'missing_translations.json');
const missingTranslationsFilePath = path.resolve(__dirname, 'missing_translations.json');

// Function to recursively update target data with base data and maintain order
const updateWithBaseData = (base, target) => {
let result = {};
Expand Down Expand Up @@ -103,58 +104,72 @@ const updatedEnData = updateWithBaseData(baseData, enData);
fs.writeFileSync(enFilePath, JSON.stringify(updatedEnData, null, 4), 'utf8');
console.log(`Updated ${enFilePath} with new keys and values from ${baseFilePath}.`);

// Read all files in the languages folder
fs.readdir(languagesFolder, (err, files) => {
if (err) {
console.error('Error reading languages folder:', err);
// Function to process a single language file
const processLanguageFile = (file) => {
const langFilePath = path.join(languagesFolder, file);
let langData;

try {
langData = JSON5.parse(fs.readFileSync(langFilePath, 'utf8')); // Use JSON5.parse
} catch (error) {
console.error(`Error reading or parsing ${file}:`, error);
return;
}

let missingTranslations = {};

files.forEach((file) => {
if (path.extname(file) === '.json' && file !== 'en.json') {
const langFilePath = path.join(languagesFolder, file);
let langData;
// Find missing keys with values
const missingKeys = getMissingKeysWithValues(baseData, langData);
if (missingKeys.length > 0) {
missingTranslations[file] = missingKeys;
}

try {
langData = JSON5.parse(fs.readFileSync(langFilePath, 'utf8')); // Use JSON5.parse
} catch (error) {
console.error(`Error reading or parsing ${file}:`, error);
return;
}
// Add missing keys with empty values to the language data and maintain order
let updatedData = addMissingKeysWithEmptyValues(baseData, langData);

// Find missing keys with values
const missingKeys = getMissingKeysWithValues(baseData, langData);
if (missingKeys.length > 0) {
missingTranslations[file] = missingKeys;
}
// Remove extra keys not present in base
removeExtraKeys(baseData, updatedData);

// Add missing keys with empty values to the language data and maintain order
let updatedData = addMissingKeysWithEmptyValues(baseData, langData);
// Write the updated data back to the file
fs.writeFileSync(langFilePath, JSON.stringify(updatedData, null, 4), 'utf8');
console.log(`Updated ${file} with missing keys and removed extra keys.`);
};

// Remove extra keys not present in base
removeExtraKeys(baseData, updatedData);
// Process language files based on the argument
const arg = process.argv[2];
let missingTranslations = {};

// Write the updated data back to the file
fs.writeFileSync(langFilePath, JSON.stringify(updatedData, null, 4), 'utf8');
console.log(`Updated ${file} with missing keys and removed extra keys.`);
if (arg) {
if (fs.existsSync(path.join(languagesFolder, arg))) {
processLanguageFile(arg);
} else {
console.error(`The file ${arg} does not exist in the languages folder.`);
}
} else {
fs.readdir(languagesFolder, (err, files) => {
if (err) {
console.error('Error reading languages folder:', err);
return;
}
});

// Output the results
if (Object.keys(missingTranslations).length === 0) {
console.log('No missing translations found.');
} else {
Object.keys(missingTranslations).forEach((lang) => {
console.log(`Missing translations in ${lang}:`);
missingTranslations[lang].forEach(({ key, value }) => {
console.log(` - ${key}: ${JSON.stringify(value)}`);
});
files.forEach((file) => {
if (path.extname(file) === '.json' && file !== 'en.json') {
processLanguageFile(file);
}
});
}

// Save the missing translations to a file
fs.writeFileSync(missingTranslationsFilePath, JSON.stringify(missingTranslations, null, 4), 'utf8');
console.log('Missing translations have been saved to missing_translations.json.');
});
// Output the results
if (Object.keys(missingTranslations).length === 0) {
console.log('No missing translations found.');
} else {
Object.keys(missingTranslations).forEach((lang) => {
console.log(`Missing translations in ${lang}:`);
missingTranslations[lang].forEach(({ key, value }) => {
console.log(` - ${key}: ${JSON.stringify(value)}`);
});
});
}

// Save the missing translations to a file
fs.writeFileSync(missingTranslationsFilePath, JSON.stringify(missingTranslations, null, 4), 'utf8');
console.log('Missing translations have been saved to missing_translations.json.');
});
}
13 changes: 10 additions & 3 deletions src/editor.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { LitElement, html, TemplateResult, CSSResultGroup } from 'lit';
import { LitElement, html, TemplateResult, CSSResultGroup, PropertyValues } from 'lit';
import { customElement, property, state } from 'lit/decorators';
import YAML from 'yaml';

Expand Down Expand Up @@ -43,6 +43,13 @@ export class VehicleCardEditor extends LitElement implements LovelaceCardEditor
void loadHaComponents();
}

protected updated(_changedProperties: PropertyValues): void {
super.updated(_changedProperties);
if (_changedProperties.has('hass')) {
return;
}
}

private convertToNewConfig(oldConfig: VehicleCardConfig): VehicleImagesList {
if (Array.isArray(oldConfig.images) && oldConfig.images.length > 0 && typeof oldConfig.images[0] === 'object') {
return oldConfig as VehicleImagesList;
Expand Down Expand Up @@ -135,7 +142,7 @@ export class VehicleCardEditor extends LitElement implements LovelaceCardEditor
return this._config?.selected_language || this._system_language || 'en';
}
protected render(): TemplateResult | void {
if (!this.hass || !this._helpers) {
if (!this.hass || !this._config) {
return html``;
}

Expand Down Expand Up @@ -594,7 +601,7 @@ export class VehicleCardEditor extends LitElement implements LovelaceCardEditor
/* --------------------- ADDITIONAL HANDLERS AND METHODS -------------------- */

private _renderToast(): TemplateResult {
const toastMsg = this.localize('common.toastImageError');
const toastMsg = this.localize('card.common.toastImageError');
return html`
<div id="toast">
<ha-alert alert-type="warning" dismissable @alert-dismissed-clicked=${this._handleAlertDismissed}
Expand Down
3 changes: 3 additions & 0 deletions src/localize/languageImports.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import * as cs from '../languages/cs.json';
import * as de from '../languages/de.json';
import * as en from '../languages/en.json';
import * as lt from '../languages/lt.json';
import * as pl from '../languages/pl.json';
import * as sk from '../languages/sk.json';
import * as vi from '../languages/vi.json';
Expand All @@ -9,6 +10,7 @@ const languages: any = {
cs: cs,
de: de,
en: en,
lt: lt,
pl: pl,
sk: sk,
vi: vi,
Expand All @@ -18,6 +20,7 @@ export const languageOptions = [
{ key: 'cs', name: cs.name },
{ key: 'de', name: de.name },
{ key: 'en', name: en.name },
{ key: 'lt', name: lt.name },
{ key: 'pl', name: pl.name },
{ key: 'sk', name: sk.name },
{ key: 'vi', name: vi.name },
Expand Down
1 change: 1 addition & 0 deletions src/localize/languageList.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
"cs.json",
"de.json",
"en.json",
"lt.json",
"pl.json",
"sk.json",
"vi.json"
Expand Down

0 comments on commit ddd3bca

Please sign in to comment.