-
-
Notifications
You must be signed in to change notification settings - Fork 32
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
bf6e6c0
commit 8813ca7
Showing
8 changed files
with
176 additions
and
164 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,82 @@ | ||
import * as defaultModifiers from './modifiers'; | ||
import { useDefault } from '../utils'; | ||
|
||
import type { CustomModifiers, ModifierOption, Parser } from './types'; | ||
|
||
const hasPlaceholders = (text:string = '') => /{{(?:(?!{{|}}).)+}}/.test(`${text}`); | ||
|
||
const unesc = (text:string) => text.replace(/\\(?=:|;|{|})/g, ''); | ||
|
||
const placeholders = (text: string, vars: Record<any, any> = {}, customModifiers: CustomModifiers = {}, locale?: string) => text.replace(/{{\s*(?:(?!{{|}}).)+\s*}}/g, (placeholder: string) => { | ||
const key = unesc(`${placeholder.match(/(?!{|\s).+?(?!\\[:;]).(?=\s*(?:[:;]|}}$))/)}`); | ||
const value = vars?.[key]; | ||
const [,defaultValue = ''] = useDefault(placeholder.match(/.+?(?!\\;).;\s*default\s*:\s*([^\s:;].+?(?:\\[:;]|[^;\s}])*)(?=\s*(?:;|}}$))/i), []); | ||
|
||
let [,modifierKey = ''] = useDefault(placeholder.match(/{{\s*(?:[^;]|(?:\\;))+\s*(?:(?!\\:).[:])\s*(?!\s)((?:\\;|[^;])+?)(?=\s*(?:[;]|}}$))/i), []); | ||
|
||
if (value === undefined && modifierKey !== 'ne') return defaultValue; | ||
|
||
const hasModifier = !!modifierKey; | ||
|
||
const modifiers: CustomModifiers = { ...defaultModifiers, ...useDefault(customModifiers) }; | ||
|
||
modifierKey = Object.keys(modifiers).includes(modifierKey) ? modifierKey : 'eq'; | ||
|
||
const modifier = modifiers[modifierKey]; | ||
const options: ModifierOption[] = useDefault<any[]>( | ||
placeholder.match(/[^\s:;{](?:[^;]|\\[;])+[^\s:;}]/gi), [], | ||
).reduce( | ||
(acc, option, i) => { | ||
// NOTE: First item is placeholder and modifier | ||
if (i > 0) { | ||
const optionKey = unesc(`${option.match(/(?:(?:\\:)|[^:])+/)}`.trim()); | ||
const optionValue = `${option.match(/(?:(?:\\:)|[^:])+$/)}`.trim(); | ||
|
||
if (optionKey && optionKey !== 'default' && optionValue) return ([ ...acc, { key: optionKey, value: optionValue }]); | ||
} | ||
|
||
return acc; | ||
}, [], | ||
); | ||
|
||
if (!hasModifier && !options.length) return `${value}`; | ||
|
||
return modifier(value, options, defaultValue, locale); | ||
|
||
}); | ||
|
||
const interpolate = (text: string, vars: Record<any, any> = {}, customModifiers?: CustomModifiers, locale?: string):string => { | ||
if (hasPlaceholders(text)) { | ||
const output = placeholders(text, vars, customModifiers, locale); | ||
|
||
return interpolate(output, vars, customModifiers, locale); | ||
} else { | ||
return unesc(`${text}`); | ||
} | ||
}; | ||
|
||
|
||
const parser: Parser = ({ customModifiers = {} }) => ({ | ||
parse: ({ translations = {}, key, payload, locale, fallbackLocale }) => { | ||
if (!key) throw new Error('No key provided to $t()'); | ||
if (!locale) throw new Error('No locale set!'); | ||
|
||
let text = useDefault(translations[locale])[key]; | ||
|
||
if (fallbackLocale && text === undefined) { | ||
text = useDefault(translations[fallbackLocale])[key]; | ||
} | ||
|
||
if (payload?.default && text === undefined) { | ||
text = `${payload.default}`; | ||
} | ||
|
||
if (text === undefined) { | ||
text = `${key}`; | ||
} | ||
|
||
return interpolate(text, payload, customModifiers, locale); | ||
}, | ||
}); | ||
|
||
export default parser; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
export type ModifierKey = 'lt' | 'lte' | 'eq' | 'gte' | 'gt'; | ||
|
||
export type ModifierOption = Record<'key' | 'value', string>; | ||
|
||
export type Modifier = (value: any, options:ModifierOption[], defaultValue?: string, locale?: string) => string; | ||
|
||
export type DefaultModifiers = Record<ModifierKey, Modifier>; | ||
|
||
export type CustomModifiers = Record<string, Modifier>; | ||
|
||
export type Parser = (config: { | ||
customModifiers?: CustomModifiers; | ||
}) => { | ||
fallbackLocale?: string, | ||
parse: (props: { | ||
translations: Record<string, Record<string, any>>; | ||
key: string; | ||
payload?: Record<any, any>; | ||
locale?: string; | ||
fallbackLocale?: string; | ||
}) => string | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
import type { ToDotNotation, FetchTranslations, Route, LoaderModule } from './types'; | ||
import type { ModifierOption } from './parser/types'; | ||
|
||
export const useDefault = <T = any>(value: any, def:any = {}): T => value || def; | ||
|
||
export const toDotNotation: ToDotNotation = (input, parentKey) => Object.keys(useDefault(input)).reduce((acc, key) => { | ||
const value = input[key]; | ||
const outputKey = parentKey ? `${parentKey}.${key}` : `${key}`; | ||
|
||
if (value && typeof value === 'object') return ({ ...acc, ...toDotNotation(value, outputKey) }); | ||
|
||
return ({ ...acc, [outputKey]: value }); | ||
}, {}); | ||
|
||
export const fetchTranslations: FetchTranslations = async (loaders) => { | ||
try { | ||
const data = await Promise.all(loaders.map(({ loader, ...rest }) => new Promise<LoaderModule & { data: any }>(async (res) => { | ||
let data; | ||
try { | ||
data = await loader(); | ||
} catch (error) { | ||
console.error(`Failed to load translation. Verify your '${rest.locale}' > '${rest.key}' loader.`); | ||
console.error(error); | ||
} | ||
res({ loader, ...rest, data }); | ||
}))); | ||
|
||
return data.reduce<Record<string, any>>((acc, { key, data, locale }) => data ? ({ | ||
...acc, | ||
[locale]: toDotNotation({ ...useDefault<Record<any, any>>(acc[locale]), [key]: data }), | ||
}) : acc, {}); | ||
} catch (error) { | ||
console.error(error); | ||
} | ||
|
||
return {}; | ||
}; | ||
|
||
export const testRoute = (route: string) => (input: Route) => { | ||
try { | ||
if (typeof input === 'string') return input === route; | ||
if (typeof input === 'object') return input.test(route); | ||
} catch (error) { | ||
throw new Error('Invalid route config!'); | ||
} | ||
|
||
return false; | ||
}; | ||
|
||
export const findOption = <T = string>(options: ModifierOption[], key: string, defaultValue?: string): T => ((options.find((option) => option.key === key))?.value || defaultValue) as any; |
This file was deleted.
Oops, something went wrong.
This file was deleted.
Oops, something went wrong.