All files / src/lib/locale locale.client.ts

95.45% Statements 21/22
80% Branches 8/10
100% Functions 3/3
94.73% Lines 18/19

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 471x       1x   6x 6x 6x 6x             4x 4x 4x   4x   4x           2x     1x 5x   4x   4x     4x   4x          
'use client';
 
import { LOCALE_STORAGE_KEY } from './locale';
 
export const getStoredLocale = (): string => {
  // Try localStorage first (works on both server and client)
  Eif (globalThis.window !== undefined) {
    try {
      const stored = localStorage.getItem(LOCALE_STORAGE_KEY);
      if (stored) return stored;
    } catch {
      // Ignore localStorage errors
    }
  }
 
  // Fallback to cookies
  Eif (globalThis.window !== undefined) {
    try {
      const stored = document.cookie
        .split('; ')
        .find((row) => row.startsWith(`${LOCALE_STORAGE_KEY}=`))
        ?.split('=')[1];
      if (stored) return stored;
    } catch {
      // Ignore cookie errors
    }
  }
 
  return 'en-gb';
};
 
export const setStoredLocale = (locale: string): void => {
  if (globalThis.window === undefined) return;
 
  try {
    // Set in localStorage
    localStorage.setItem(LOCALE_STORAGE_KEY, locale);
 
    // Set in cookies (expires in 1 year)
    const maxAge = 60 * 60 * 24 * 365;
    // biome-ignore lint/suspicious/noDocumentCookie: We need to set the cookie manually for i18n
    document.cookie = `${LOCALE_STORAGE_KEY}=${locale}; path=/; max-age=${maxAge}`;
  } catch (error) {
    console.error('[setStoredLocale] Error setting locale:', error);
  }
};