translate.ts 1.1 KB

1234567891011121314151617181920212223242526272829303132
  1. /**
  2. * Test double of the locale lookup chain: a translate stub over plain
  3. * dictionaries, mirroring LocaleRuntime's resolution order (first dictionary
  4. * that owns the key wins, then the key itself stays visible) and its
  5. * `{name}` template interpolation. Specs stub the framework-injected `t`
  6. * seat with `makeTranslate(zh, commonZh)` instead of re-implementing the
  7. * chain per suite.
  8. */
  9. /**
  10. * Build a translate stub resolving through `dicts` in order (namespace
  11. * first, then the shared common vocabulary), falling back to the key.
  12. * @param dicts - dictionaries consulted in order.
  13. * @returns the translate function (assignable to any `XxxProps['t']` seat).
  14. */
  15. export function makeTranslate(
  16. ...dicts: readonly Record<string, string>[]
  17. ): (key: string, params?: Record<string, unknown>) => string {
  18. return (key, params) => {
  19. let template = key
  20. for (const dict of dicts) {
  21. const hit = dict[key]
  22. if (hit !== undefined) {
  23. template = hit
  24. break
  25. }
  26. }
  27. if (!params) return template
  28. return template.replace(/\{(\w+)\}/g, (match, name: string) =>
  29. name in params ? String(params[name]) : match)
  30. }
  31. }