Skip to content

Commit

Permalink
Added i18next parser config file, put all string in the example page …
Browse files Browse the repository at this point in the history
…into i18n hook, generated locale files

Missed support for generation of locales
  • Loading branch information
Mylanos committed Jun 20, 2023
1 parent c7b49c6 commit 5c01b0c
Show file tree
Hide file tree
Showing 10 changed files with 22,933 additions and 1,609 deletions.
7 changes: 7 additions & 0 deletions i18n-scripts/build-i18n.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
#!/usr/bin/env bash

set -exuo pipefail

FILE_PATTERN="{!(dist|node_modules)/**/*.{js,jsx,ts,tsx,json},*.{js,jsx,ts,tsx,json}}"

i18next "${FILE_PATTERN}" [-oc] -c "./i18next-parser.config.js" -o "locales/\$LOCALE/\$NAMESPACE.json"
34 changes: 34 additions & 0 deletions i18n-scripts/common.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
const fs = require('fs');
const path = require('path');

module.exports = {
isDirectory(filePath) {
try {
const stat = fs.lstatSync(filePath);
return stat.isDirectory();
} catch (e) {
// lstatSync throws an error if path doesn't exist
return false;
}
},
parseFolder(directory, argFunction, packageDir) {
(async () => {
try {
const files = await fs.promises.readdir(directory);
for (const file of files) {
const filePath = path.join(directory, file);
argFunction(filePath, packageDir);
}
} catch (e) {
console.error(`Failed to parseFolder ${directory}:`, e);
}
})();
},
deleteFile(filePath) {
try {
fs.unlinkSync(filePath);
} catch (e) {
console.error(`Failed to delete file ${filePath}:`, e);
}
},
};
31 changes: 31 additions & 0 deletions i18n-scripts/lexers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
const EventEmitter = require('events');
const jsonc = require('comment-json');

/**
* Custom JSON parser for localizing keys matching format: /%.+%/
*/
module.exports.CustomJSONLexer = class extends EventEmitter {
extract(content, filename) {
let keys = [];
console.log(1)
try {
jsonc.parse(
content,
(key, value) => {
if (typeof value === 'string') {
const match = value.match(/^%(.+)%$/);
if (match && match[1]) {
keys.push({ key: match[1] });
}
}
return value;
},
true,
);
} catch (e) {
console.error('Failed to parse as JSON.', filename, e);
keys = [];
}
return keys;
}
};
68 changes: 68 additions & 0 deletions i18n-scripts/set-english-defaults.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
const fs = require('fs');
const path = require('path');
const pluralize = require('pluralize');
const common = require('./common.js');

const publicDir = path.join(__dirname, './../locales/');

function determineRule(key) {
if (key.includes('WithCount_plural')) {
return 0;
}
if (key.includes('WithCount')) {
return 1;
}
if (key.includes('_plural')) {
return 2;
}
return 3;
}

function updateFile(fileName) {
const file = require(fileName);
const updatedFile = {};

const keys = Object.keys(file);

let originalKey;

for (let i = 0; i < keys.length; i++) {
if (file[keys[i]] === '') {
// follow i18next rules
// "key": "item",
// "key_plural": "items",
// "keyWithCount": "{{count}} item",
// "keyWithCount_plural": "{{count}} items"
switch (determineRule(keys[i])) {
case 0:
[originalKey] = keys[i].split('WithCount_plural');
updatedFile[keys[i]] = `{{count}} ${pluralize(originalKey)}`;
break;
case 1:
[originalKey] = keys[i].split('WithCount');
updatedFile[keys[i]] = `{{count}} ${originalKey}`;
break;
case 2:
[originalKey] = keys[i].split('_plural');
updatedFile[keys[i]] = pluralize(originalKey);
break;
default:
updatedFile[keys[i]] = keys[i];
}
} else {
updatedFile[keys[i]] = file[keys[i]];
}
}

fs.promises
.writeFile(fileName, JSON.stringify(updatedFile, null, 2))
.catch((e) => console.error(fileName, e));
}

function processLocalesFolder(filePath) {
if (path.basename(filePath) === 'en') {
common.parseFolder(filePath, updateFile);
}
}

common.parseFolder(publicDir, processLocalesFolder);
33 changes: 33 additions & 0 deletions i18next-parser.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// eslint-disable-next-line @typescript-eslint/no-var-requires, no-undef
const { CustomJSONLexer } = require('./i18n-scripts/lexers');

// eslint-disable-next-line no-undef
module.exports = {
input: ['src/**/*.{js,jsx,ts,tsx}'],
sort: true,
createOldCatalogs: false,
keySeparator: false,
locales: ['en'],
namespaceSeparator: '~',
reactNamespace: false,
defaultNamespace: 'plugin__crontab-plugin',
useKeysAsDefaultValue: true,

// see below for more details
lexers: {
hbs: ['HandlebarsLexer'],
handlebars: ['HandlebarsLexer'],

htm: ['HTMLLexer'],
html: ['HTMLLexer'],

mjs: ['JavascriptLexer'],
js: ['JavascriptLexer'], // if you're writing jsx inside .js files, change this to JsxLexer
ts: ['JavascriptLexer'],
jsx: ['JsxLexer'],
tsx: ['JsxLexer'],
json: [CustomJSONLexer],

default: ['JavascriptLexer'],
},
};
11 changes: 11 additions & 0 deletions locales/en/plugin__console-plugin.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"After cloning this project, replace references to": "After cloning this project, replace references to",
"and other plugin metadata in package.json with values for your plugin.": "and other plugin metadata in package.json with values for your plugin.",
"console-template-plugin": "console-template-plugin",
"exposedModules": "exposedModules",
"Hello, Plugin!": "Hello, Plugin!",
"in package.json mapping the reference to the module.": "in package.json mapping the reference to the module.",
"Nice!": "Nice!",
"This is a custom page contributed by the console plugin template. The extension that adds the page is declared in console-extensions.json in the project root along with the corresponding nav item. Update console-extensions.json to change or add extensions. Code references in console-extensions.json must have a corresonding property": "This is a custom page contributed by the console plugin template. The extension that adds the page is declared in console-extensions.json in the project root along with the corresponding nav item. Update console-extensions.json to change or add extensions. Code references in console-extensions.json must have a corresonding property",
"Your plugin is working.": "Your plugin is working."
}
Loading

0 comments on commit 5c01b0c

Please sign in to comment.