Skip to content

Commit cecb734

Browse files
committed
feat(i18n): add helper function
1 parent 66f0bac commit cecb734

2 files changed

Lines changed: 31 additions & 1 deletion

File tree

packages/commandkit/src/CommandKit.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,8 @@ export class CommandKit extends EventEmitter {
8686
getMessageCommandPrefix: () => '!',
8787
};
8888

89+
public readonly store = new Map<string, any>();
90+
8991
public commandsRouter!: CommandsRouter;
9092
public eventsRouter!: EventsRouter;
9193
public readonly commandHandler = new AppCommandHandler(this);

packages/i18n/src/i18n.ts

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import type {
66
i18n,
77
InitOptions,
88
} from 'i18next';
9-
import {
9+
import CommandKit, {
1010
CommandKitPluginRuntime,
1111
Context as NativeContext,
1212
Logger,
@@ -96,6 +96,32 @@ NativeContext.prototype.locale = function (locale?: Locale) {
9696
} satisfies CommandLocalizationContext;
9797
};
9898

99+
/**
100+
* Retrieves the i18n instance from the commandkit store.
101+
* @param commandkit The commandkit instance.
102+
* @returns The i18n instance.
103+
* @throws Error if the i18n instance is not found in the store.
104+
* @example
105+
* ```ts
106+
* import { getI18n } from '@commandkit/i18n';
107+
* import { commandkit } from 'commandkit';
108+
*
109+
* const i18n = getI18n(commandkit);
110+
*
111+
* // Use the i18n instance
112+
* i18n.t('key');
113+
* ```
114+
*/
115+
export function getI18n(commandkit: CommandKit): i18n {
116+
const i18n = commandkit.store.get('i18n:plugin:instance') as i18n;
117+
118+
if (!i18n) {
119+
throw new Error('I18n not found, is the I18nPlugin registered?');
120+
}
121+
122+
return i18n;
123+
}
124+
99125
export class I18nPlugin extends RuntimePlugin<LocalizationPluginOptions> {
100126
public readonly name = 'I18nPlugin';
101127
private i18n!: i18n;
@@ -104,6 +130,8 @@ export class I18nPlugin extends RuntimePlugin<LocalizationPluginOptions> {
104130
public async activate(ctx: CommandKitPluginRuntime): Promise<void> {
105131
this.i18n = i18next;
106132

133+
ctx.commandkit.store.set('i18n:plugin:instance', this.i18n);
134+
107135
this.i18n.use(FsBackend);
108136

109137
if (this.options.plugins?.length) {

0 commit comments

Comments
 (0)