All files / presentation/ui/src timePreferences.ts

95.23% Statements 20/21
93.33% Branches 14/15
100% Functions 5/5
95.23% Lines 20/21

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 47 48 49 50      68x 68x     14x 14x 14x 14x       1x         7x 7x       7x 7x       4x 4x 4x   1x         4x 4x 1x   3x   4x          
export type TimeFormat = "12h" | "24h";
export type TimezonePreference = "default" | "local" | "utc";
 
export const TIME_FORMAT_KEY = "TIME_FORMAT";
export const TIMEZONE_KEY = "TIMEZONE";
 
function readStoredValue(key: string): Record<string, unknown> {
  try {
    const stored = localStorage.getItem(key);
    const value: unknown = stored ? JSON.parse(stored) : {};
    return value !== null && typeof value === "object" && !Array.isArray(value)
      ? (value as Record<string, unknown>)
      : {};
  } catch {
    return {};
  }
}
 
export function fetchStoredTimeFormat(): TimeFormat {
  const format = readStoredValue(TIME_FORMAT_KEY).format;
  return format === "24h" ? "24h" : "12h";
}
 
export function fetchStoredTimezone(): TimezonePreference {
  const timezone = readStoredValue(TIMEZONE_KEY).timezone;
  return timezone === "local" || timezone === "utc" ? timezone : "default";
}
 
export function storeTimeFormat(format: TimeFormat): boolean {
  try {
    localStorage.setItem(TIME_FORMAT_KEY, JSON.stringify({ format }));
    return true;
  } catch {
    return false;
  }
}
 
export function storeTimezone(timezone: TimezonePreference): boolean {
  try {
    if (timezone === "default") {
      localStorage.removeItem(TIMEZONE_KEY);
    } else {
      localStorage.setItem(TIMEZONE_KEY, JSON.stringify({ timezone }));
    }
    return true;
  } catch {
    return false;
  }
}