UNPKG

vuestic-ui

Version:
1 lines 3.35 kB
{"version":3,"file":"useTranslation.mjs","sources":["../../../../src/composables/useTranslation.ts"],"sourcesContent":["import { computed, getCurrentInstance, PropType } from 'vue'\nimport { useGlobalConfig } from '../composables'\nimport { I18NKey, I18NKnownKey } from '../services/i18n'\nimport { warn } from '../utils/console'\nimport { StringWithAutocomplete } from '../utils/types/prop-type'\n\ntype Stringable = number | string | boolean | undefined\n\nexport type TranslationKey = `$t:${I18NKnownKey}`;\n\n// Also allows arbitrary keys\nexport type TranslationProp = StringWithAutocomplete<TranslationKey>\n\nconst isTranslationKey = (value: string): value is TranslationKey => value.startsWith('$t:')\n\nexport const useTranslationProp = (defaultValue: TranslationProp) => {\n return { type: String as PropType<TranslationProp>, default: defaultValue }\n}\n\nconst f: TranslationProp | undefined = '$t:back'\n\nconst applyI18nTemplate = (key: string, values?: Record<string, Stringable>) => {\n if (!values) { return key }\n\n Object.keys(values).forEach((valueKey) => {\n key = key.replace(`{${valueKey}}`, String(values[valueKey]))\n })\n return key\n}\n\nexport const useTranslation = () => {\n const { globalConfig } = useGlobalConfig()\n\n const config = computed(() => globalConfig.value.i18n)\n\n function t<Key extends I18NKey> (key: Key, values?: Record<string, Stringable>) {\n const $t = getCurrentInstance()?.appContext.config.globalProperties.$t\n\n // Try to resolve translation with vue-i18n injected $t function\n if (typeof $t === 'function') {\n const translated = $t(`vuestic.${key}`, values)\n\n if (translated) {\n return translated\n }\n }\n\n const translated = config.value[key]\n if (!translated) {\n warn(`${key} not found in VuesticUI i18n config`)\n return key\n }\n\n return (applyI18nTemplate(translated, values) || key)\n }\n\n /** Translate prop. Translate only if key has `$t:` prefix */\n function tp<Key extends TranslationProp | undefined> (key: Key, values?: Record<string, Stringable>): string {\n if (!key) { return '' }\n\n if (isTranslationKey(key)) {\n return t(key.slice(3), values)\n }\n\n return (applyI18nTemplate(key, values) || key)\n }\n\n return {\n tp,\n t,\n }\n}\n"],"names":["translated"],"mappings":";;;AAaA,MAAM,m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