All files / player-skin-sdk/src settings.ts

98.14% Statements 53/54
98.5% Branches 66/67
100% Functions 5/5
100% Lines 49/49

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 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150                                                                                                      122x               135x 44x 44x 44x 44x   103x 103x 1x 102x 2x   100x   103x 1x   103x   32x 1x 1x   90x 31x 31x 1x   31x     5x 5x 1x 4x 1x   5x 1x   5x 1x   5x     65x 65x   1x         44x                         26x 26x 58x 58x   18x 4x     18x   6x       6x   34x 34x     26x    
import type { BeMusicSkin } from './types.ts';
 
/** A skin setting picked from a fixed list (a colour theme, a layout variant). */
export interface BeMusicSkinChoiceSetting {
  readonly kind: 'choice';
  /** Key of the value in {@link BeMusicSkinSettingValues}; unique within the skin. */
  readonly id: string;
  /** Name shown in the host's settings UI. */
  readonly label: string;
  /** The choices: `value` is what the skin receives, `label` what the player sees. */
  readonly options: readonly { readonly value: string; readonly label: string }[];
  /** Value used until the player picks one; must be one of the option values. */
  readonly default: string;
}
 
/** A numeric skin setting with a range (an offset, an opacity). */
export interface BeMusicSkinNumberSetting {
  readonly kind: 'number';
  /** Key of the value in {@link BeMusicSkinSettingValues}; unique within the skin. */
  readonly id: string;
  /** Name shown in the host's settings UI. */
  readonly label: string;
  readonly min: number;
  readonly max: number;
  /** Increment the host's slider moves by. */
  readonly step?: number;
  /** Value used until the player picks one; must lie in `min..max`. */
  readonly default: number;
  /** Unit shown beside the value. */
  readonly unit?: 'px' | 'ms' | '%';
}
 
/** An on / off skin setting. */
export interface BeMusicSkinToggleSetting {
  readonly kind: 'toggle';
  /** Key of the value in {@link BeMusicSkinSettingValues}; unique within the skin. */
  readonly id: string;
  /** Name shown in the host's settings UI. */
  readonly label: string;
  readonly default: boolean;
}
 
/** One option a skin lets the player tune (see `BeMusicSkin.settings`). */
export type BeMusicSkinSetting = BeMusicSkinChoiceSetting | BeMusicSkinNumberSetting | BeMusicSkinToggleSetting;
 
/**
 * The player's value for every setting a skin declares, keyed by setting id: a `string` for a choice, a `number` for a
 * number, a `boolean` for a toggle.
 */
export type BeMusicSkinSettingValues = Readonly<Record<string, string | number | boolean>>;
 
const NUMBER_UNITS: ReadonlySet<string> = new Set(['px', 'ms', '%']);
 
/**
 * Problems with a skin's `settings` schema — duplicate or empty ids, empty labels, defaults outside their range or
 * options — as human-readable messages. Empty when the schema is fine (or absent). `validateBeMusicSkin` includes
 * these.
 */
export function validateBeMusicSkinSettings(settings: readonly BeMusicSkinSetting[] | undefined): string[] {
  if (settings === undefined) return [];
  Iif (!Array.isArray(settings)) return ['settings must be an array'];
  const problems: string[] = [];
  const ids = new Set<string>();
  settings.forEach((setting: BeMusicSkinSetting, index) => {
    const name =
      typeof setting?.id === 'string' && setting.id !== '' ? `setting "${setting.id}"` : `settings[${index}]`;
    if (typeof setting?.id !== 'string' || setting.id.trim() === '') {
      problems.push(`${name}: id must not be empty`);
    } else if (ids.has(setting.id)) {
      problems.push(`${name}: id is used more than once`);
    } else {
      ids.add(setting.id);
    }
    if (typeof setting?.label !== 'string' || setting.label.trim() === '') {
      problems.push(`${name}: label must not be empty`);
    }
    switch (setting?.kind) {
      case 'choice': {
        if (!Array.isArray(setting.options) || setting.options.length === 0) {
          problems.push(`${name}: options must not be empty`);
          break;
        }
        const values = setting.options.map((option) => option.value);
        if (new Set(values).size !== values.length) problems.push(`${name}: option values must be unique`);
        if (!values.includes(setting.default)) {
          problems.push(`${name}: default "${String(setting.default)}" is not one of the option values`);
        }
        break;
      }
      case 'number': {
        const { min, max, step } = setting;
        if (!Number.isFinite(min) || !Number.isFinite(max) || min > max) {
          problems.push(`${name}: min and max must be finite numbers with min <= max`);
        } else if (!Number.isFinite(setting.default) || setting.default < min || setting.default > max) {
          problems.push(`${name}: default ${String(setting.default)} is outside ${min}..${max}`);
        }
        if (step !== undefined && !(Number.isFinite(step) && step > 0)) {
          problems.push(`${name}: step must be a positive number`);
        }
        if (setting.unit !== undefined && !NUMBER_UNITS.has(setting.unit)) {
          problems.push(`${name}: unit "${String(setting.unit)}" must be one of ${[...NUMBER_UNITS].join(', ')}`);
        }
        break;
      }
      case 'toggle':
        if (typeof setting.default !== 'boolean') problems.push(`${name}: default must be a boolean`);
        break;
      default:
        problems.push(
          `${name}: kind "${String((setting as { kind?: unknown })?.kind)}" must be choice, number, or toggle`,
        );
    }
  });
  return problems;
}
 
/**
 * The values a skin draws with: `stored` (what the host persisted for the skin, possibly from an older release of it)
 * checked against the skin's `settings` schema. Each setting gets its stored value when that is still valid — a known
 * option, a finite number (clamped into `min..max`), a boolean — and its `default` otherwise. Stored keys the schema
 * no longer declares are dropped.
 */
export function resolveBeMusicSkinSettings(
  skin: Pick<BeMusicSkin, 'settings'>,
  stored?: Readonly<Record<string, unknown>>,
): BeMusicSkinSettingValues {
  const values: Record<string, string | number | boolean> = {};
  for (const setting of skin.settings ?? []) {
    const value = stored?.[setting.id];
    switch (setting.kind) {
      case 'choice':
        values[setting.id] =
          typeof value === 'string' && setting.options.some((option) => option.value === value)
            ? value
            : setting.default;
        break;
      case 'number':
        values[setting.id] =
          typeof value === 'number' && Number.isFinite(value)
            ? Math.min(setting.max, Math.max(setting.min, value))
            : setting.default;
        break;
      case 'toggle':
        values[setting.id] = typeof value === 'boolean' ? value : setting.default;
        break;
    }
  }
  return values;
}