electron/lib/renderer/extensions/i18n.ts

61 lines
2 KiB
TypeScript
Raw Normal View History

// Implementation of chrome.i18n.getMessage
// https://developer.chrome.com/extensions/i18n#method-getMessage
//
// Does not implement predefined messages:
// https://developer.chrome.com/extensions/i18n#overview-predefined
2020-03-20 20:28:31 +00:00
import * as ipcRendererUtils from '@electron/internal/renderer/ipc-renderer-internal-utils';
interface Placeholder {
content: string;
example?: string;
}
2016-06-07 22:34:17 +00:00
const getMessages = (extensionId: number) => {
2016-06-07 22:34:17 +00:00
try {
2020-03-20 20:28:31 +00:00
const data = ipcRendererUtils.invokeSync<string>('CHROME_GET_MESSAGES', extensionId);
return JSON.parse(data) || {};
} catch {
2020-03-20 20:28:31 +00:00
return {};
2016-06-07 22:34:17 +00:00
}
2020-03-20 20:28:31 +00:00
};
2016-06-07 22:34:17 +00:00
const replaceNumberedSubstitutions = (message: string, substitutions: string[]) => {
return message.replace(/\$(\d+)/, (_, number) => {
2020-03-20 20:28:31 +00:00
const index = parseInt(number, 10) - 1;
return substitutions[index] || '';
});
};
const replacePlaceholders = (message: string, placeholders: Record<string, Placeholder>, substitutions: string[] | string) => {
2020-03-20 20:28:31 +00:00
if (typeof substitutions === 'string') substitutions = [substitutions];
if (!Array.isArray(substitutions)) substitutions = [];
if (placeholders) {
Object.keys(placeholders).forEach((name: string) => {
2020-03-20 20:28:31 +00:00
let { content } = placeholders[name];
const substitutionsArray = Array.isArray(substitutions) ? substitutions : [];
content = replaceNumberedSubstitutions(content, substitutionsArray);
message = message.replace(new RegExp(`\\$${name}\\$`, 'gi'), content);
});
}
2020-03-20 20:28:31 +00:00
return replaceNumberedSubstitutions(message, substitutions);
};
const getMessage = (extensionId: number, messageName: string, substitutions: string[]) => {
2020-03-20 20:28:31 +00:00
const messages = getMessages(extensionId);
if (Object.prototype.hasOwnProperty.call(messages, messageName)) {
2020-03-20 20:28:31 +00:00
const { message, placeholders } = messages[messageName];
return replacePlaceholders(message, placeholders, substitutions);
2016-06-08 00:00:53 +00:00
}
2020-03-20 20:28:31 +00:00
};
2016-06-08 00:00:53 +00:00
exports.setup = (extensionId: number) => {
2016-06-08 00:00:53 +00:00
return {
getMessage (messageName: string, substitutions: string[]) {
2020-03-20 20:28:31 +00:00
return getMessage(extensionId, messageName, substitutions);
2016-06-07 22:34:17 +00:00
}
2020-03-20 20:28:31 +00:00
};
};