use-phrases.ts 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import { useTranslation } from 'react-i18next'
  2. import { useMemo } from 'react'
  3. export const usePhrases = (): Record<string, string> => {
  4. const { t, i18n } = useTranslation()
  5. const codemirrorBuiltinsOverrides = useMemo(
  6. () => ({
  7. 'Fold line': t('fold_line'),
  8. 'Unfold line': t('unfold_line'),
  9. }),
  10. [t]
  11. )
  12. const translationProxy = useMemo(
  13. () => ({
  14. getOwnPropertyDescriptor(target: Record<string, string>, prop: string) {
  15. // If we've added an override
  16. if (Object.prototype.hasOwnProperty.call(target, prop)) {
  17. return Object.getOwnPropertyDescriptor(target, prop)
  18. }
  19. // If the translation exists, report a property:
  20. // non-enumerable: it won't show up in enumerating the keys of the target
  21. // configurable: we have to report it as configurable since it doesn't
  22. // exist in the base object
  23. // writable: an override can be added
  24. if (i18n.exists(prop)) {
  25. return { enumerable: false, configurable: true, writable: true }
  26. }
  27. return Object.getOwnPropertyDescriptor(target, prop)
  28. },
  29. get(target: Record<string, string>, prop: string) {
  30. // If we've specifically added an override
  31. if (Object.prototype.hasOwnProperty.call(target, prop)) {
  32. return target[prop]
  33. }
  34. if (i18n.exists(prop)) {
  35. return t(prop)
  36. }
  37. return target[prop]
  38. },
  39. }),
  40. [t, i18n]
  41. )
  42. const phrases = useMemo(
  43. () => new Proxy(codemirrorBuiltinsOverrides, translationProxy),
  44. [translationProxy, codemirrorBuiltinsOverrides]
  45. )
  46. return phrases
  47. }