Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions apps/web/src/__tests__/lib/i18n.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { render, screen } from '@testing-library/react';
import { describe, expect, it } from 'vitest';
import { LocaleProvider, useLocale } from '#/lib/i18n';

function Probe() {
const { locale, t, formatNumber } = useLocale();
return (
<output>
{locale}|{t('nav.dashboard')}|{formatNumber(1234567)}
</output>
);
}

describe('i18n', () => {
it('falls back to English when no locale is stored', () => {
localStorage.removeItem('locale');
render(
<LocaleProvider>
<Probe />
</LocaleProvider>,
);
expect(screen.getByText(/\|Dashboard\|/)).toBeInTheDocument();
});

it('uses a stored supported locale and updates document language', () => {
localStorage.setItem('locale', 'zh-CN');
render(
<LocaleProvider>
<Probe />
</LocaleProvider>,
);
expect(screen.getByText(/zh-CN\|仪表盘\|/)).toBeInTheDocument();
expect(document.documentElement.lang).toBe('zh-CN');
});
});
39 changes: 39 additions & 0 deletions apps/web/src/i18n/en-GB.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
{
"nav.dashboard": "Dashboard",
"nav.applications": "Applications",
"nav.calendar": "Calendar",
"nav.analytics": "Analytics",
"nav.assistant": "Assistant",
"nav.settings": "Settings",
"nav.signOut": "Sign out",
"settings.language": "Language",
"settings.languageDescription": "Choose the language used across the web app.",
"settings.profile": "Profile",
"settings.experience": "Experience",
"settings.security": "Security",
"settings.integrations": "Integrations",
"settings.notifications": "Notifications",
"settings.data": "Data",
"errors.notFound": "Page not found",
"errors.goDashboard": "Go to dashboard",
"errors.somethingWrong": "Something went wrong",
"errors.reloadHelp": "Try reloading the page. If this keeps happening, let us know.",
"errors.reload": "Reload",
"auth.signIn": "Sign in",
"auth.signUp": "Sign up",
"auth.email": "Email",
"auth.password": "Password",
"auth.forgotPassword": "Forgot password?",
"common.save": "Save",
"common.cancel": "Cancel",
"common.delete": "Delete",
"common.loading": "Loading…",
"auth.noAccount": "Don't have an account?",
"auth.register": "Register",
"auth.twoFactor": "Two-factor authentication",
"auth.twoFactorHelp": "Enter the 6-digit code from your authenticator app, or one of your backup codes.",
"auth.code": "Code",
"auth.signingIn": "Signing in…",
"auth.noAccountFound": "No account found with this email.",
"auth.createOne": "to create one."
}
39 changes: 39 additions & 0 deletions apps/web/src/i18n/en.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
{
"nav.dashboard": "Dashboard",
"nav.applications": "Applications",
"nav.calendar": "Calendar",
"nav.analytics": "Analytics",
"nav.assistant": "Assistant",
"nav.settings": "Settings",
"nav.signOut": "Sign out",
"settings.language": "Language",
"settings.languageDescription": "Choose the language used across the web app.",
"settings.profile": "Profile",
"settings.experience": "Experience",
"settings.security": "Security",
"settings.integrations": "Integrations",
"settings.notifications": "Notifications",
"settings.data": "Data",
"errors.notFound": "Page not found",
"errors.goDashboard": "Go to dashboard",
"errors.somethingWrong": "Something went wrong",
"errors.reloadHelp": "Try reloading the page. If this keeps happening, let us know.",
"errors.reload": "Reload",
"auth.signIn": "Sign in",
"auth.signUp": "Sign up",
"auth.email": "Email",
"auth.password": "Password",
"auth.forgotPassword": "Forgot password?",
"common.save": "Save",
"common.cancel": "Cancel",
"common.delete": "Delete",
"common.loading": "Loading…",
"auth.noAccount": "Don't have an account?",
"auth.register": "Register",
"auth.twoFactor": "Two-factor authentication",
"auth.twoFactorHelp": "Enter the 6-digit code from your authenticator app, or one of your backup codes.",
"auth.code": "Code",
"auth.signingIn": "Signing in…",
"auth.noAccountFound": "No account found with this email.",
"auth.createOne": "to create one."
}
39 changes: 39 additions & 0 deletions apps/web/src/i18n/zh-CN.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
{
"nav.dashboard": "仪表盘",
"nav.applications": "求职申请",
"nav.calendar": "日历",
"nav.analytics": "分析",
"nav.assistant": "助手",
"nav.settings": "设置",
"nav.signOut": "退出登录",
"settings.language": "语言",
"settings.languageDescription": "选择网页应用使用的语言。",
"settings.profile": "个人资料",
"settings.experience": "经历",
"settings.security": "安全",
"settings.integrations": "集成",
"settings.notifications": "通知",
"settings.data": "数据",
"errors.notFound": "页面未找到",
"errors.goDashboard": "前往仪表盘",
"errors.somethingWrong": "发生错误",
"errors.reloadHelp": "请重新加载页面。如果问题持续,请通知我们。",
"errors.reload": "重新加载",
"auth.signIn": "登录",
"auth.signUp": "注册",
"auth.email": "电子邮箱",
"auth.password": "密码",
"auth.forgotPassword": "忘记密码?",
"common.save": "保存",
"common.cancel": "取消",
"common.delete": "删除",
"common.loading": "加载中…",
"auth.noAccount": "还没有账户?",
"auth.register": "注册",
"auth.twoFactor": "双重身份验证",
"auth.twoFactorHelp": "输入身份验证器应用中的六位数验证码,或一组备用验证码。",
"auth.code": "验证码",
"auth.signingIn": "登录中…",
"auth.noAccountFound": "未找到使用此邮箱的账户。",
"auth.createOne": "以创建账户。"
}
39 changes: 39 additions & 0 deletions apps/web/src/i18n/zh-HK.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
{
"nav.dashboard": "主頁",
"nav.applications": "求職申請",
"nav.calendar": "日曆",
"nav.analytics": "分析",
"nav.assistant": "助理",
"nav.settings": "設定",
"nav.signOut": "登出",
"settings.language": "語言",
"settings.languageDescription": "選擇網頁應用程式使用的語言。",
"settings.profile": "個人資料",
"settings.experience": "經歷",
"settings.security": "安全性",
"settings.integrations": "整合",
"settings.notifications": "通知",
"settings.data": "資料",
"errors.notFound": "找不到頁面",
"errors.goDashboard": "前往主頁",
"errors.somethingWrong": "發生錯誤",
"errors.reloadHelp": "請重新載入頁面。如問題持續,請通知我們。",
"errors.reload": "重新載入",
"auth.signIn": "登入",
"auth.signUp": "註冊",
"auth.email": "電郵",
"auth.password": "密碼",
"auth.forgotPassword": "忘記密碼?",
"common.save": "儲存",
"common.cancel": "取消",
"common.delete": "刪除",
"common.loading": "載入中…",
"auth.noAccount": "還未有帳戶?",
"auth.register": "註冊",
"auth.twoFactor": "雙重認證",
"auth.twoFactorHelp": "輸入認證器應用程式中的六位數代碼,或其中一組備用代碼。",
"auth.code": "代碼",
"auth.signingIn": "登入中…",
"auth.noAccountFound": "找不到此電郵的帳戶。",
"auth.createOne": "以建立帳戶。"
}
39 changes: 39 additions & 0 deletions apps/web/src/i18n/zh-TW.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
{
"nav.dashboard": "儀表板",
"nav.applications": "求職申請",
"nav.calendar": "行事曆",
"nav.analytics": "分析",
"nav.assistant": "助理",
"nav.settings": "設定",
"nav.signOut": "登出",
"settings.language": "語言",
"settings.languageDescription": "選擇網頁應用程式使用的語言。",
"settings.profile": "個人資料",
"settings.experience": "經歷",
"settings.security": "安全性",
"settings.integrations": "整合",
"settings.notifications": "通知",
"settings.data": "資料",
"errors.notFound": "找不到頁面",
"errors.goDashboard": "前往儀表板",
"errors.somethingWrong": "發生錯誤",
"errors.reloadHelp": "請重新載入頁面。如果問題持續,請通知我們。",
"errors.reload": "重新載入",
"auth.signIn": "登入",
"auth.signUp": "註冊",
"auth.email": "電子郵件",
"auth.password": "密碼",
"auth.forgotPassword": "忘記密碼?",
"common.save": "儲存",
"common.cancel": "取消",
"common.delete": "刪除",
"common.loading": "載入中…",
"auth.noAccount": "還沒有帳戶?",
"auth.register": "註冊",
"auth.twoFactor": "雙因素驗證",
"auth.twoFactorHelp": "輸入驗證器應用程式中的六位數代碼,或其中一組備份代碼。",
"auth.code": "驗證碼",
"auth.signingIn": "登入中…",
"auth.noAccountFound": "找不到此電子郵件的帳戶。",
"auth.createOne": "以建立帳戶。"
}
101 changes: 101 additions & 0 deletions apps/web/src/lib/i18n.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
import { createContext, useContext, useEffect, useMemo, useState } from 'react';
import en from '#/i18n/en.json';
import enGB from '#/i18n/en-GB.json';
import zhHK from '#/i18n/zh-HK.json';
import zhTW from '#/i18n/zh-TW.json';
import zhCN from '#/i18n/zh-CN.json';

export const SUPPORTED_LOCALES = ['en', 'en-GB', 'zh-HK', 'zh-TW', 'zh-CN'] as const;
export type Locale = (typeof SUPPORTED_LOCALES)[number];
export const LOCALE_STORAGE_KEY = 'locale';

export const LOCALE_OPTIONS: Array<{ value: Locale; label: string }> = [
{ value: 'en', label: 'English' },
{ value: 'en-GB', label: 'English (United Kingdom)' },
{ value: 'zh-HK', label: '中文(香港)' },
{ value: 'zh-TW', label: '繁體中文(台灣)' },
{ value: 'zh-CN', label: '简体中文' },
];

type Messages = Record<string, string>;

const messages: Record<Locale, Messages> = {
en,
'en-GB': enGB,
'zh-HK': zhHK,
'zh-TW': zhTW,
'zh-CN': zhCN,
};

export function isLocale(value: string | null | undefined): value is Locale {
return !!value && (SUPPORTED_LOCALES as readonly string[]).includes(value);
}

function detectLocale(): Locale {
if (typeof window === 'undefined') return 'en';
const stored = localStorage.getItem(LOCALE_STORAGE_KEY);
if (isLocale(stored)) return stored;
for (const language of navigator.languages) {
if (isLocale(language)) return language;
if (language.startsWith('zh-HK')) return 'zh-HK';
if (language.startsWith('zh-TW')) return 'zh-TW';
if (language.startsWith('zh')) return 'zh-CN';
if (language.startsWith('en-GB')) return 'en-GB';
if (language.startsWith('en')) return 'en';
}
return 'en';
}

interface LocaleContextValue {
locale: Locale;
setLocale: (locale: Locale) => void;
t: (key: string) => string;
formatDate: (value: Date | string | number, options?: Intl.DateTimeFormatOptions) => string;
formatNumber: (value: number, options?: Intl.NumberFormatOptions) => string;
}

const LocaleContext = createContext<LocaleContextValue | null>(null);

export function LocaleProvider({ children }: { children: React.ReactNode }) {
const [locale, setLocaleState] = useState<Locale>(detectLocale);

useEffect(() => {
document.documentElement.lang = locale;
localStorage.setItem(LOCALE_STORAGE_KEY, locale);
}, [locale]);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== Locate i18n file =="
fd -a 'i18n\.(tsx|ts)$' . | sed 's#^\./##'

echo "== Outline =="
ast-grep outline apps/web/src/lib/i18n.tsx --view expanded || true

echo "== Relevant file section =="
cat -n apps/web/src/lib/i18n.tsx | sed -n '1,220p'

echo "== Locate LocaleProvider usages and startup script references =="
rg -n "LocaleProvider|LOCALE_STORAGE_KEY|i18n|window\.localStorage|localStorage\.(get|set)Item" apps/web/src -S || true

echo "== Package/typescript info =="
if [ -f package.json ]; then cat package.json | sed -n '1,120p'; fi
if [ -f apps/web/package.json ]; then cat apps/web/package.json | sed -n '1,140p'; fi

Repository: mankatcheung/job-finder

Length of output: 15120


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== Root route relevant section =="
cat -n apps/web/src/routes/__root.tsx | sed -n '70,105p'

echo "== Runtime storage access model probe =="
node --input-type=module <<'JS'
for (const model of ['unavailable', 'blocked']) {
  const ns = model === 'unavailable'
    ? {}
    : { localStorage: { getItem() { throw new TypeError('Blocked') }, setItem() { throw new TypeError('Blocked') } } };
  const detectLocale = function (ns) {
    const LOCALE_STORAGE_KEY = 'locale';
    if (typeof ns.window === 'undefined') return 'en';
    const stored = ns.localStorage.getItem(LOCALE_STORAGE_KEY);
    if (stored && ['en','en-GB','zh-HK','zh-TW','zh-CN'].includes(stored)) return stored;
    for (const language of ns.navigator.languages) {
      if (['en','en-GB','zh-HK','zh-TW','zh-CN'].includes(language)) return language;
      if (language.startsWith('zh-HK')) return 'zh-HK';
      if (language.startsWith('zh-TW')) return 'zh-TW';
      if (language.startsWith('zh')) return 'zh-CN';
      if (language.startsWith('en-GB')) return 'en-GB';
      if (language.startsWith('en')) return 'en';
    }
    return 'en';
  };
  console.log(model, 'detectLocale throws:', (() => { try { detectLocale(ns); return false } catch { return true } })());
}
JS

echo "== Web Storage error handling documentation snippet =="
python3 - <<'PY'
# Deterministic model of current unguarded storage access: a throw from getItem throws before navigator fallback;
# a throw from setItem throws from the effect and is not caught by LOCALE_INIT_SCRIPT.
cases = {
    "detectLocale.getItemThrows": "throws before navigator fallback, falls back to en-GB if navigator.language can throw; storage falls back to en",
    "localeEffect.setItemThrows": "throws during effect; root catches",
}
for k, v in cases.items():
    print(f"{k}: {v}")
PY

Repository: mankatcheung/job-finder

Length of output: 2098


Handle blocked Web Storage in locale detection and persistence.

localStorage.getItem() can throw when storage is unavailable or blocked, and detectLocale() does not fall back to browser preferences in that case. localStorage.setItem() in the useEffect can also throw. Wrap storage reads and writes with try/catch; on failure, keep using browser preferences or the English default instead of crashing locale initialisation.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/web/src/lib/i18n.tsx` around lines 123 - 154, Update detectLocale to
wrap localStorage.getItem in try/catch, continuing through navigator.languages
and ultimately the English fallback when storage is unavailable. Also wrap the
localStorage.setItem call in LocaleProvider’s locale useEffect with try/catch so
blocked storage cannot crash persistence or locale initialization.

Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

const value = useMemo<LocaleContextValue>(
() => ({
locale,
setLocale: (next) => setLocaleState(next),
t: (key) => messages[locale][key] ?? messages.en[key] ?? key,
formatDate: (valueToFormat, options) =>
new Intl.DateTimeFormat(locale, options).format(
typeof valueToFormat === 'string' ? new Date(valueToFormat) : valueToFormat,
),
formatNumber: (valueToFormat, options) =>
new Intl.NumberFormat(locale, options).format(valueToFormat),
}),
[locale],
);

return <LocaleContext.Provider value={value}>{children}</LocaleContext.Provider>;
}

export function useLocale(): LocaleContextValue {
const context = useContext(LocaleContext);
if (context) return context;
return {
locale: 'en',
setLocale: () => undefined,
t: (key) => messages.en[key] ?? key,
formatDate: (valueToFormat, options) =>
new Intl.DateTimeFormat('en', options).format(
typeof valueToFormat === 'string' ? new Date(valueToFormat) : valueToFormat,
),
formatNumber: (valueToFormat, options) =>
new Intl.NumberFormat('en', options).format(valueToFormat),
};
}

export const LOCALE_INIT_SCRIPT = `(function(){try{var l=localStorage.getItem('${LOCALE_STORAGE_KEY}');if(!l){l=(navigator.languages||[]).find(function(x){return ['en','en-GB','zh-HK','zh-TW','zh-CN'].indexOf(x)>=0;})||'en';}document.documentElement.lang=l;}catch(e){}})();`;
Loading
Loading