All files / app mockDevice.ts

98.46% Statements 64/65
100% Branches 0/0
100% Functions 0/0
98.46% Lines 64/65

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                            2x 1x     1x           8x 8x   5x 5x 5x       5x   5x     5x 5x   5x             5x   1x 1x 1x           6x 6x 24x   6x 4x 4x   6x                     2x   37x 37x 37x 37x 37x 37x 37x   37x 37x 37x 37x 37x 37x   37x 37x 74x 3x 3x 2x       37x 74x   37x 1x 1x   37x 3x 3x 2x 2x 2x 2x 2x       2x 1x 1x   1x 1x 1x     37x    
import type { ReplaySessionController } from '@wstein/regrip-core/session/replay/replaySession';
import { byId, createDropdownMenu } from './dom';
 
type MockFixture = 'gocube-edge' | 'gan-ui12' | 'local';
 
export type MockDeviceReplayLoad =
  | { requested: false }
  | {
      requested: true;
      replay: ReplaySessionController | undefined;
      error?: string;
    };
 
async function bundledFixture(fixture: Exclude<MockFixture, 'local'>): Promise<string> {
  if (fixture === 'gan-ui12') {
    return (await import('@wstein/regrip-core/session/replay/fixtures/gan-ui12-ui.jsonl?raw'))
      .default;
  }
  return (await import('@wstein/regrip-core/session/replay/fixtures/gocube-edge-ui.jsonl?raw'))
    .default;
}
 
/** Resolve an explicitly requested replay without loading replay code on the normal path. */
export async function loadReplayFromUrl(): Promise<MockDeviceReplayLoad> {
  const params = new URLSearchParams(location.search);
  if (!params.has('replay')) return { requested: false };
 
  try {
    const fixture = params.get('fixture');
    if (fixture !== 'gocube-edge' && fixture !== 'gan-ui12' && fixture !== 'local') {
      throw new Error('Choose a bundled fixture or load a local JSONL file.');
    }
    const { createReplaySession, REPLAY_STORAGE_KEY } =
      await import('@wstein/regrip-core/session/replay/replaySession');
    const contents =
      fixture === 'local'
        ? sessionStorage.getItem(REPLAY_STORAGE_KEY)
        : await bundledFixture(fixture);
    if (!contents) throw new Error('The local replay is no longer available in this tab.');
    const requestedFeed = params.get('feed');
    const feed =
      requestedFeed === 'session'
        ? 'session'
        : requestedFeed === 'connection'
          ? 'connection'
          : fixture === 'local'
            ? 'session'
            : 'connection';
    return { requested: true, replay: createReplaySession(contents, feed) };
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    console.warn('Unable to load mock cube replay:', error);
    return { requested: true, replay: undefined, error: message };
  }
}
 
/** Build a mock-mode or real-device URL while retaining unrelated query parameters. */
export function buildMockDeviceUrl(currentHref: string, fixture?: MockFixture): string {
  const url = new URL(currentHref);
  for (const parameter of ['replay', 'fixture', 'feed', 'autoplay']) {
    url.searchParams.delete(parameter);
  }
  if (fixture) {
    url.searchParams.set('replay', '');
    url.searchParams.set('fixture', fixture);
  }
  return url.href;
}
 
type MockDevicePickerOptions = {
  load: MockDeviceReplayLoad;
  navigate?: (href: string) => void;
};
 
/** Mount the transport picker without eagerly importing replay validation or fixtures. */
export function mountMockDevicePicker({
  load,
  navigate = (href) => location.assign(href),
}: MockDevicePickerOptions): void {
  const toggle = byId('connect', HTMLButtonElement);
  const menu = byId('connect-menu');
  const fileInput = byId('mock-device-file', HTMLInputElement);
  const exit = byId('mock-device-exit', HTMLButtonElement);
  const activeMenuItem = exit?.closest('li');
  const status = byId('mock-device-status');
  if (!(activeMenuItem instanceof HTMLElement)) throw new Error('Missing element for replay exit');
 
  const active = load.requested && load.replay !== undefined;
  toggle.dataset.mockActive = String(active);
  if (active) toggle.textContent = 'Replay mode ▾';
  activeMenuItem.hidden = !active;
  status.textContent = load.requested && load.error ? load.error : '';
  status.hidden = status.textContent === '';
 
  const { close: closeMenu } = createDropdownMenu({ toggle, menu });
  menu.querySelectorAll<HTMLButtonElement>('[data-mock-fixture]').forEach((button) => {
    button.addEventListener('click', () => {
      const fixture = button.dataset.mockFixture;
      if (fixture === 'gocube-edge' || fixture === 'gan-ui12') {
        navigate(buildMockDeviceUrl(location.href, fixture));
      }
    });
  });
  for (const id of ['connect-bluetooth', 'disconnect-cube']) {
    document.getElementById(id)?.addEventListener('click', closeMenu);
  }
  menu.querySelector<HTMLButtonElement>('[data-mock-load]')?.addEventListener('click', () => {
    closeMenu();
    fileInput.click();
  });
  fileInput.addEventListener('change', async () => {
    const file = fileInput.files?.[0];
    if (!file) return;
    status.hidden = true;
    status.textContent = '';
    try {
      const contents = await file.text();
      const [{ validateJsonlReplay }, { REPLAY_STORAGE_KEY }] = await Promise.all([
        import('@wstein/regrip-core/session/replay/jsonlMock'),
        import('@wstein/regrip-core/session/replay/replaySession'),
      ]);
      validateJsonlReplay(contents);
      sessionStorage.setItem(REPLAY_STORAGE_KEY, contents);
      navigate(buildMockDeviceUrl(location.href, 'local'));
    } catch (error) {
      status.textContent = error instanceof Error ? error.message : String(error);
      status.hidden = false;
      fileInput.value = '';
    }
  });
  exit.addEventListener('click', () => navigate(buildMockDeviceUrl(location.href)));
}