Skip to content

Commit

Permalink
refactor(locale): type-safe locale functions
Browse files Browse the repository at this point in the history
  • Loading branch information
dev-737 committed Jul 26, 2024
1 parent 1a27fa8 commit 910979c
Show file tree
Hide file tree
Showing 9 changed files with 280 additions and 277 deletions.
2 changes: 1 addition & 1 deletion locales
Submodule locales updated 1 files
+2 −3 src/locales/en.yml
35 changes: 24 additions & 11 deletions scripts/genLocaleTypes.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,32 +8,45 @@ import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

// Function to recursively generate type definitions from the translation keys
/** Recursively generate type definitions from the translation data
@param obj {{ [key: string]: string }} the object with all translation data
@returns {string[]}
*/
function generateTypes(obj, path = '') {
const keys = Object.keys(obj);
return keys
.map((key) => {
const fullPath = path ? `${path}.${key}` : key;
if (typeof obj[key] === 'object' && obj[key] !== null) {
return generateTypes(obj[key], fullPath);
}
return `'${fullPath}'`;
})
.flat();
/** @type {string[]} */
const allTypeDefs = [];
keys.forEach((key) => {
const fullPath = path ? `${path}.${key}` : key;
if (typeof obj[key] === 'object' && obj[key] !== null) {
const idk = generateTypes(obj[key], fullPath);
return allTypeDefs.push(...idk);
}

const regex = /\{([^\}]+)\}/g;
const variables = [...obj[key].matchAll(regex)].map((match) => `'${match[1]}'`);
const variablesStr = variables.length !== 0 ? variables.join(' | ') : 'never';

allTypeDefs.push(`'${fullPath}': ${variablesStr}`);
});

return allTypeDefs;
}

// Read the YAML file
const filePath = resolve(__dirname, '..', 'locales/src/locales/en.yml');
const file = readFileSync(filePath, 'utf8');

// Parse the YAML content
/** @type {{ [key: string]: string }} */
// @ts-expect-error
const data = yaml.load(file);

// Generate type definitions
const typeDefinitions = generateTypes(data);

// Create the .d.ts content
const dtsContent = `export type TranslationKey = ${typeDefinitions.join(' | ')};\n`;
const dtsContent = `export type TranslationKeys = {\n ${typeDefinitions.join(';\n ')};\n};\n`;

// Write the .d.ts file
const outputFilePath = resolve(__dirname, '..', 'src/typings/en.d.ts');
Expand Down
5 changes: 1 addition & 4 deletions src/commands/slash/Main/connection/pause.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,7 @@ export default class Pause extends Connection {
const leave_cmd = hubCmd ? slashCmdMention('hub', 'leave', hubCmd.id) : '`/hub leave`';

await interaction.reply({
content: t(
{ phrase: 'connection.paused.tips', locale },
{ emoji: emojis.dotBlue, unpause_cmd, leave_cmd },
),
content: t({ phrase: 'connection.paused.tips', locale }, { unpause_cmd, leave_cmd }),
embeds: [
simpleEmbed(
t(
Expand Down
27 changes: 9 additions & 18 deletions src/commands/slash/Main/connection/unpause.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,16 +60,13 @@ export default class Unpause extends Connection {

const webhook = await getOrCreateWebhook(channel).catch(() => null);
if (!webhook) {
await interaction.editReply({
embeds: [
simpleEmbed(
t(
{ phrase: 'errors.botMissingPermissions', locale },
{ emoji: emojis.no, permissions: 'Manage Webhooks' },
),
),
],
});
await this.replyEmbed(
interaction,
t(
{ phrase: 'errors.botMissingPermissions', locale },
{ emoji: emojis.no, permissions: 'Manage Webhooks' },
),
);
return;
}

Expand All @@ -86,18 +83,12 @@ export default class Unpause extends Connection {
}

await interaction.editReply({
content: t(
{ phrase: 'connection.unpaused.tips', locale },
{ emoji: emojis.dotBlue, pause_cmd, customize_cmd },
),
content: t({ phrase: 'connection.unpaused.tips', locale }, { pause_cmd, customize_cmd }),
embeds: [
simpleEmbed(
t(
{ phrase: 'connection.unpaused.desc', locale },
{
tick_emoji: emojis.tick,
channel: channelMention(channelId),
},
{ tick_emoji: emojis.tick, channel: channelMention(channelId) },
),
),
],
Expand Down
19 changes: 11 additions & 8 deletions src/commands/slash/Main/hub/invite.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { ChatInputCommandInteraction, CacheType, EmbedBuilder } from 'discord.js';
import Hub from './index.js';
import { LINKS, emojis } from '#main/utils/Constants.js';
import db from '#main/utils/Db.js';
import { t } from '#main/utils/Locale.js';
import Logger from '#main/utils/Logger.js';
import { getUserLocale, simpleEmbed } from '#main/utils/Utils.js';
import { captureException } from '@sentry/node';
import { LINKS, emojis } from '../../../../utils/Constants.js';
import db from '../../../../utils/Db.js';
import Logger from '../../../../utils/Logger.js';
import { getUserLocale, simpleEmbed } from '../../../../utils/Utils.js';
import { t } from '../../../../utils/Locale.js';
import { CacheType, ChatInputCommandInteraction, EmbedBuilder } from 'discord.js';
import parse from 'parse-duration';
import Hub from './index.js';

export default class Invite extends Hub {
readonly cooldown = 3000; // 3 seconds
Expand Down Expand Up @@ -116,7 +116,10 @@ export default class Invite extends Hub {
captureException(e);
await this.replyEmbed(
interaction,
t({ phrase: 'errors.unknown', locale }, { emoji: emojis.no }),
t(
{ phrase: 'errors.unknown', locale },
{ emoji: emojis.no, support_invite: LINKS.SUPPORT_INVITE },
),
{
ephemeral: true,
},
Expand Down
43 changes: 19 additions & 24 deletions src/commands/slash/Main/hub/manage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { genLogInfoEmbed } from '#main/scripts/hub/logs.js';
import { actionsSelect, hubEmbed } from '#main/scripts/hub/manage.js';
import { buildSettingsEmbed, buildSettingsMenu } from '#main/scripts/hub/settings.js';
import { HubSettingsBitField, HubSettingsString } from '#main/utils/BitFields.js';
import { colors, emojis } from '#main/utils/Constants.js';
import { colors, emojis, LINKS } from '#main/utils/Constants.js';
import { CustomID } from '#main/utils/CustomID.js';
import db from '#main/utils/Db.js';
import { setLogChannelFor } from '#main/utils/HubLogger/Default.js';
Expand Down Expand Up @@ -114,14 +114,11 @@ export default class Manage extends Hub {
// TODO: implement BlockNSFW, only allow hubs that are explicitly marked as NSFW to have this setting
// & only allow network channels to be marked as NSFW
if (selected === 'BlockNSFW') {
await interaction.reply({
embeds: [
simpleEmbed(
`${emojis.no} This setting cannot be changed yet. Please wait for the next update.`,
),
],
ephemeral: true,
});
await this.replyEmbed(
interaction,
`${emojis.no} This setting cannot be changed yet. Please wait for the next update.`,
{ ephemeral: true },
);
return;
}

Expand All @@ -133,10 +130,14 @@ export default class Manage extends Hub {

const locale = await getUserLocale(interaction.user.id);
if (!updHub) {
await interaction.reply({
embeds: [simpleEmbed(t({ phrase: 'errors.unknown', locale }, { emoji: emojis.no }))],
ephemeral: true,
});
await this.replyEmbed(
interaction,
t(
{ phrase: 'errors.unknown', locale },
{ emoji: emojis.no, support_invite: LINKS.SUPPORT_INVITE },
),
{ ephemeral: true },
);
return;
}

Expand Down Expand Up @@ -682,17 +683,11 @@ export default class Manage extends Hub {
});
}

await interaction.reply({
embeds: [
simpleEmbed(
t(
{ phrase: 'hub.manage.logs.reset', locale },
{ emoji: emojis.deleteDanger_icon, type },
),
),
],
ephemeral: true,
});
await this.replyEmbed(
interaction,
t({ phrase: 'hub.manage.logs.reset', locale }, { emoji: emojis.deleteDanger_icon, type }),
{ ephemeral: true },
);
}
}

Expand Down
5 changes: 4 additions & 1 deletion src/commands/slash/Main/hub/moderator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,10 @@ export default class Moderator extends Hub {
else if (!isUserMod) {
await this.replyEmbed(
interaction,
t({ phrase: 'hub.moderator.update.notModerator', locale }, { user: user.toString() }),
t(
{ phrase: 'hub.moderator.update.notModerator', locale },
{ user: user.toString(), emoji: emojis.no },
),
{ ephemeral: true },
);
break;
Expand Down
Loading

0 comments on commit 910979c

Please sign in to comment.