All files / app-play/src hi-speed-storage.ts

81.25% Statements 13/16
84.61% Branches 11/13
75% Functions 3/4
78.57% Lines 11/14

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      8x     8x       18x 9x         12x 12x     2x           3x 3x 2x 2x                          
import { snapHiSpeed } from '@be-music/player-scene-model';
import { optionDefault } from './option-defaults.ts';
 
const DEFAULT_HISPEED = optionDefault<number>('hiSpeed');
 
/** `localStorage` key of the hi-speed the next play starts at (the last one picked in play, the panel or the menu). */
export const HI_SPEED_STORAGE_KEY = 'be-music.hi-speed';
 
/** A stored hi-speed, snapped and clamped to the player's range; {@link DEFAULT_HISPEED} when missing or unreadable. */
export function parseStoredHiSpeed(raw: string | null | undefined): number {
  if (raw === null || raw === undefined || raw.trim() === '') return DEFAULT_HISPEED;
  return snapHiSpeed(Number(raw)) ?? DEFAULT_HISPEED;
}
 
/** The remembered hi-speed, or {@link DEFAULT_HISPEED} when none is stored or storage is blocked. */
export function readStoredHiSpeed(storage: Pick<Storage, 'getItem'> | undefined = defaultStorage()): number {
  try {
    return parseStoredHiSpeed(storage?.getItem(HI_SPEED_STORAGE_KEY));
  } catch {
    // Storage blocked — use the default.
    return DEFAULT_HISPEED;
  }
}
 
/** Remembers `value` (snapped and clamped) for the next play; ignores non-finite values. */
export function storeHiSpeed(value: number, storage: Pick<Storage, 'setItem'> | undefined = defaultStorage()): void {
  const snapped = snapHiSpeed(value);
  if (snapped === undefined) return;
  try {
    storage?.setItem(HI_SPEED_STORAGE_KEY, String(snapped));
  } catch {
    // Private windows / blocked storage: the value still applies for this session.
  }
}
 
function defaultStorage(): Storage | undefined {
  try {
    return typeof window === 'undefined' ? undefined : window.localStorage;
  } catch {
    return undefined;
  }
}