i18n.ts 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. import i18n from 'i18next'
  2. import { initReactI18next } from 'react-i18next'
  3. import LanguageDetector from 'i18next-browser-languagedetector'
  4. import HttpBackend from 'i18next-http-backend'
  5. // 'auto' means "follow the browser", and it is an explicit choice in
  6. // Settings: the detector must not keep a cached language for it.
  7. const savedLang = localStorage.getItem('netpulse-lang')
  8. if (!savedLang || savedLang === 'auto') {
  9. localStorage.removeItem('i18nextLng')
  10. }
  11. // Builds with a forced language (public demo, VITE_FORCE_LANG=en).
  12. const forcedLang = import.meta.env.VITE_FORCE_LANG as 'es' | 'en' | 'zh' | 'ru' | undefined
  13. // DEFAULT_LNG: English is the language this deployment shows unless somebody
  14. // asks for another. Following the browser as the default meant a Spanish or
  15. // Romanian locale opened the panel in Spanish, which is not what the people
  16. // running it read. A choice made in Settings still wins, and choosing 'auto'
  17. // there goes back to following the browser.
  18. const DEFAULT_LNG = 'en'
  19. const initialLng = savedLang
  20. ? savedLang === 'auto'
  21. ? undefined // explicit "follow the browser"
  22. : savedLang
  23. : (forcedLang ?? DEFAULT_LNG)
  24. i18n
  25. .use(HttpBackend)
  26. .use(LanguageDetector)
  27. .use(initReactI18next)
  28. .init({
  29. // With no previous choice the panel starts in English. Only an explicit
  30. // 'auto' in Settings leaves this undefined so the LanguageDetector reads
  31. // the browser (localStorage → navigator). (issue #3, #237)
  32. lng: initialLng,
  33. fallbackLng: 'en',
  34. supportedLngs: ['es', 'en', 'zh', 'ru'],
  35. nonExplicitSupportedLngs: true,
  36. load: 'languageOnly',
  37. backend: {
  38. loadPath: '/locales/{{lng}}/translation.json',
  39. },
  40. detection: {
  41. order: ['localStorage', 'navigator'],
  42. caches: ['localStorage'],
  43. lookupLocalStorage: 'i18nextLng',
  44. },
  45. interpolation: { escapeValue: false },
  46. react: { useSuspense: true },
  47. returnNull: false,
  48. })
  49. // Locales por idioma en un solo sitio. Un idioma nuevo son tres cosas: su
  50. // catálogo en public/locales, una entrada aquí y su opción en el selector.
  51. // Antes cada helper encadenaba un ternario por idioma y cada traducción
  52. // nueva tocaba ocho ficheros.
  53. const FALLBACK_LOCALE = { num: 'en-US', date: 'en-GB', html: 'en' }
  54. const LOCALES: Record<string, typeof FALLBACK_LOCALE> = {
  55. es: { num: 'es-ES', date: 'es-ES', html: 'es' },
  56. en: { num: 'en-US', date: 'en-GB', html: 'en' },
  57. zh: { num: 'zh-CN', date: 'zh-CN', html: 'zh-CN' },
  58. ru: { num: 'ru-RU', date: 'ru-RU', html: 'ru' },
  59. }
  60. function activeLocale(lng?: string) {
  61. const l = (lng ?? i18n.language ?? DEFAULT_LNG).slice(0, 2).toLowerCase()
  62. return LOCALES[l] ?? FALLBACK_LOCALE
  63. }
  64. // #666: the document's lang must follow the active language. Without it the
  65. // browser believes the page is in another language and offers to translate
  66. // it -- and the translator mangles the data (hostnames "crowed" →
  67. // "crowded"). With the right lang, a translated UI raises no such offer.
  68. const applyDocLang = (lng?: string) => {
  69. document.documentElement.lang = activeLocale(lng).html
  70. }
  71. applyDocLang()
  72. i18n.on('languageChanged', applyDocLang)
  73. export default i18n
  74. /** Locale numérico según el idioma activo */
  75. export function numLocale(): string {
  76. return activeLocale().num
  77. }
  78. /** Locale de fechas y horas (Intl) según el idioma activo */
  79. export function dateLocale(): string {
  80. return activeLocale().date
  81. }
  82. const REL_RE = /^hace\s+(\d+)\s*(s|min|h|días?|d)$/
  83. const REL_RE_EN = /^(\d+)\s*(s|sec|min|h|hr|d|days?)\s+ago$/
  84. /** Convierte tiempos relativos canónicos del dataset ("hace 12 min", "12 min ago", "hoy") al idioma activo */
  85. export function relTime(s: string): string {
  86. const t = s.trim()
  87. if (t === 'hoy' || t.toLowerCase() === 'today') return i18n.t('common.today')
  88. // A peer that has never handshaked: the server sends the canonical
  89. // Spanish and it was reaching the screen untranslated.
  90. if (t === 'nunca' || t.toLowerCase() === 'never') return i18n.t('common.never')
  91. const m = REL_RE.exec(t) ?? REL_RE_EN.exec(t)
  92. if (!m) return s
  93. const n = Number(m[1])
  94. const u = m[2]
  95. const unit = u === 's' || u === 'sec' ? 's' : u === 'min' ? 'min' : u === 'h' || u === 'hr' ? 'h' : 'd'
  96. return i18n.t(`common.ago.${unit}`, { count: n, n })
  97. }
  98. /**
  99. * Tiempo relativo desde un timestamp unix en SEGUNDOS (SPEC-ALERTAS §1: el
  100. * frontend calcula el relativo; el string `time` queda como fallback legado).
  101. * Devuelve null si `ts` no es usable (0/NaN/futuro lejano) → usar `relTime(time)`.
  102. */
  103. export function relTimeFromTs(ts: number | undefined, nowMs = Date.now()): string | null {
  104. if (!ts || !Number.isFinite(ts) || ts <= 0) return null
  105. const diffS = Math.floor(nowMs / 1000) - ts
  106. if (diffS < 0) return null
  107. if (diffS < 60) return i18n.t('common.ago.s', { count: diffS, n: diffS })
  108. const min = Math.floor(diffS / 60)
  109. if (min < 60) return i18n.t('common.ago.min', { count: min, n: min })
  110. const h = Math.floor(min / 60)
  111. if (h < 24) return i18n.t('common.ago.h', { count: h, n: h })
  112. const d = Math.floor(h / 24)
  113. return i18n.t('common.ago.d', { count: d, n: d })
  114. }
  115. /** Relativo de una alerta: desde `ts` si es válido; si no, el string legado. */
  116. export function alertRelTime(ev: { ts?: number; time: string }): string {
  117. return relTimeFromTs(ev.ts) ?? relTime(ev.time)
  118. }
  119. /** Relativo ("hace 3 días") desde epoch MILISEGUNDOS (#954 first/last seen
  120. * de clientes). 0/indefinido = desconocido → "—". */
  121. export function fmtSeenAgo(ms: number | undefined, nowMs = Date.now()): string {
  122. if (!ms || !Number.isFinite(ms) || ms <= 0) return '—'
  123. return relTimeFromTs(Math.floor(ms / 1000), nowMs) ?? '—'
  124. }
  125. /** Uptime canónico tipo "12d 4h" → "12 días, 4 h" / "12 days, 4 h" */
  126. export function fmtUptime(uptime: string): string {
  127. const m = /^(\d+)d\s*(\d+)h$/.exec(uptime.trim())
  128. if (!m) return uptime
  129. const d = Number(m[1])
  130. const h = Number(m[2])
  131. return i18n.t('common.uptime', { d, h, count: d })
  132. }
  133. const LEASE_RE = /^renueva en\s+(\d+)\s*h(?:\s*(\d+)\s*min)?$/
  134. // #1818: concesiones de más de un día ("renueva en 1d 4h 30min").
  135. const LEASE_DAYS_RE = /^renueva en\s+(\d+)d(?:\s+(\d+)h)?(?:\s+(\d+)min)?$/
  136. /** Concesión DHCP canónica: "renueva en 7 h 48 min" / "IP fija (reserva)" */
  137. export function dhcpLease(s: string): string {
  138. const t = s.trim()
  139. if (t === 'IP fija (reserva)') return i18n.t('common.staticLease')
  140. // #1818: un lease caducado es un hecho, no un texto en inglés incrustado.
  141. if (t === 'Expirado') return i18n.t('common.leaseExpired')
  142. const m = LEASE_RE.exec(t)
  143. if (m) {
  144. const h = Number(m[1])
  145. if (!m[2]) return i18n.t('common.leaseRenewsH', { h })
  146. return i18n.t('common.leaseRenews', { h, min: Number(m[2]) })
  147. }
  148. const md = LEASE_DAYS_RE.exec(t)
  149. if (md) {
  150. return i18n.t('common.leaseRenewsDays', { d: Number(md[1]), h: Number(md[2] ?? 0), min: Number(md[3] ?? 0) })
  151. }
  152. return s
  153. }
  154. const HEALTH_KEYS: Record<string, string> = {
  155. Excelente: 'excellent',
  156. Bueno: 'good',
  157. Atención: 'warning',
  158. Crítico: 'critical',
  159. }
  160. /** Etiqueta de salud canónica del dataset ("Excelente"…) → idioma activo */
  161. export function healthLabel(label: string): string {
  162. const k = HEALTH_KEYS[label]
  163. return k ? i18n.t(`common.health.${k}`) : label
  164. }
  165. /** Subscore de salud por clave ("wan" | "wifi" | "infra" | "services") → idioma activo */
  166. export function subscoreLabel(key: string, label: string): string {
  167. const known = ['wan', 'wifi', 'infra', 'services']
  168. return known.includes(key) ? i18n.t(`common.health.subscores.${key}`) : label
  169. }
  170. /** Fabricante OUI canónico del dataset ("Desconocido" = sin match) → idioma activo */
  171. export function manufacturerLabel(manufacturer: string): string {
  172. if (manufacturer === 'Desconocido') return i18n.t('devices.unknownManufacturer')
  173. return manufacturer
  174. }
  175. /** Rol canónico del dataset ("Principal" | "AP" | "SW" | "EXT") → idioma activo */
  176. export function roleLabel(role: string): string {
  177. if (role === 'Principal') return i18n.t('common.rolePrimary')
  178. if (role === 'AP') return i18n.t('common.roleAP')
  179. if (role === 'EXT') return i18n.t('common.roleExternal')
  180. return role
  181. }
  182. /** Sello del SO que el server declara para la unidad. Router.type es una
  183. * enum cerrada ('glinet' | 'openwrt' | 'managed-switch' | 'external',
  184. * adapters/types.go) y solo las dos primeras son OpenWrt (GL.iNet corre su
  185. * firmware). Vacío para las demás: una tarjeta de switch Mikrotik, un NAS o
  186. * un AP con firmware de fábrica no pueden llevar un SO que el server nunca
  187. * confirmó. */
  188. export function osBadge(type?: string): string {
  189. return !type || type === 'glinet' || type === 'openwrt' ? 'OpenWrt' : ''
  190. }
  191. const DAY_KEYS = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'] as const
  192. /** Abreviatura de día de la semana: dayAbbr(0) = Lun/Mon … dayAbbr(6) = Dom/Sun */
  193. export function dayAbbr(index: number): string {
  194. return i18n.t(`common.days.${DAY_KEYS[((index % 7) + 7) % 7]}`)
  195. }
  196. const HEALTH_BREAKDOWN_RE = {
  197. offline: /^(.+) offline$/,
  198. temp: /^temp\. (.+)$/,
  199. }
  200. /**
  201. * Canonical health-breakdown label from the server ("AdGuard inactivo",
  202. * "temp. Patio", "Salon offline") → active language. These are built by
  203. * concatenation server-side, so they are matched by shape, and anything
  204. * unrecognised is passed through rather than mangled.
  205. */
  206. export function healthBreakdownLabel(label: string): string {
  207. const t = label.trim()
  208. if (t === 'AdGuard inactivo') return i18n.t('common.health.adguardInactive')
  209. const off = HEALTH_BREAKDOWN_RE.offline.exec(t)
  210. if (off) return i18n.t('common.health.routerOffline', { name: off[1] })
  211. const temp = HEALTH_BREAKDOWN_RE.temp.exec(t)
  212. if (temp) return i18n.t('common.health.routerTemp', { name: temp[1] })
  213. return label
  214. }