mtcute/packages/i18n/src/utils.ts

64 lines
1.8 KiB
TypeScript
Raw Normal View History

import type * as dispatcherNs from '@mtcute/dispatcher'
2022-07-19 02:47:59 +03:00
import { I18nStrings, I18nValue } from './types.js'
2022-09-12 15:01:43 +03:00
/**
* Create an index of i18n strings delimited by "."
*
* @param strings Strings object
*/
2023-09-24 01:32:22 +03:00
export function createI18nStringsIndex(strings: I18nStrings): Record<string, I18nValue> {
2022-07-19 02:47:59 +03:00
const ret: Record<string, I18nValue> = {}
function add(obj: I18nStrings, prefix: string) {
2022-07-19 02:47:59 +03:00
for (const key in obj) {
const val = obj[key]
if (typeof val === 'object' && !('value' in val)) {
2022-07-19 02:47:59 +03:00
add(val, prefix + key + '.')
} else {
ret[prefix + key] = val as string
2022-07-19 02:47:59 +03:00
}
}
}
add(strings, '')
return ret
}
2022-09-12 15:01:43 +03:00
/**
* Extract language from `@mtcute/dispatcher` context.
* Can be used for customized adapters or external i18n libraries.
2022-09-12 15:01:43 +03:00
*
* @param update Update to extract language from
*/
export function extractLanguageFromUpdate(update: dispatcherNs.UpdateContextType): string | null | undefined {
if (!('_name' in update)) return null
// for whatever reason eslint doesn't like this
/* eslint-disable @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-return */
switch (update._name) {
case 'new_message': {
const { sender } = update
return sender.type === 'user' ? sender.language : null
}
case 'poll_vote': {
const { peer } = update
return peer?.type === 'user' ? peer.language : null
}
case 'chat_member':
case 'inline_query':
case 'chosen_inline_result':
case 'callback_query':
case 'bot_stopped':
case 'bot_chat_join_request':
return update.user.language
2022-07-19 02:47:59 +03:00
}
/* eslint-enable @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-return */
2022-07-19 02:47:59 +03:00
return null
}