All files / app-play/src player-header.ts

67.44% Statements 87/129
64.58% Branches 62/96
60% Functions 9/15
70.37% Lines 76/108

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 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307                                                                                    3x           3x     3x 3x 3x   3x   3x                         8x                     4x 4x 4x 1x 1x 1x   3x                                           8x                       8x     8x                                               8x 7x 6x 5x 4x 4x 3x 2x         3x 3x 3x                       3x                     8x 4x 4x 4x 2x 2x 1x 1x     8x 1x 1x 7x 1x 1x 1x 1x     8x 8x 8x 4x 4x 4x 1x 1x 1x 1x     8x                                       3x 3x   3x 3x                                                                             9x       9x 2x 1x 2x   7x       7x 5x 3x 5x   2x 1x 1x 1x   1x    
import { html, render, type TemplateResult } from 'lit';
import { type ServiceHeaderAccount } from '@be-music/service-web-theme';
import { serviceHeaderTemplate, serviceSkipLinkTemplate } from '@be-music/service-web-theme/client';
import {
  enterTouchFullscreen,
  getFullscreenElement,
  playerFullscreenElement,
  toggleFullscreen,
  type FullscreenDocumentLike,
  type FullscreenElementLike,
} from './fullscreen.ts';
import { onPlayerLangChange, playerLang, setPlayerLang, type PlayerLang } from './player-copy.ts';
import { leaderboardAvatarURL, leaderboardLink } from './service-links.ts';
 
/** The signed-in account the header shows. */
export interface PlayerHeaderAccount {
  handle: string;
  displayName: string;
  anonymous: boolean;
  /** The avatar as the Leaderboard API reports it (a Leaderboard path or an absolute URL). */
  avatarUrl?: string;
}
 
export interface PlayerHeaderActions {
  /** Opens the Options dialog when it is closed, and closes it when it is open. `null` clears a binding. */
  toggleOptions?: (() => void) | null;
  /** Opens the Help dialog. `null` clears a binding. */
  openHelp?: (() => void) | null;
  /** Installs the player, or explains how; the button shows only while {@link setPlayerHeaderInstallable} says so. */
  install?: (() => void) | null;
  /** Opens the player's sign-in dialog. `null` clears a binding. */
  openSignIn?: (() => void) | null;
  /** Switches the player language in place, the same path as Help. */
  selectLanguage?: (lang: PlayerLang) => void;
}
 
const actions: {
  toggleOptions?: () => void;
  openHelp?: () => void;
  install?: () => void;
  openSignIn?: () => void;
  selectLanguage: (lang: PlayerLang) => void;
} = {
  selectLanguage: (lang) => setPlayerLang(lang),
};
 
let account: PlayerHeaderAccount | undefined;
/** The account has not been read yet, so the header shows a placeholder rather than "Sign in". */
let accountLoading = true;
let host: HTMLElement | undefined;
/** An odd number of Settings clicks arrived before the menu existed, so the first bind should open it. */
let pendingMenu = false;
let pendingSignIn = false;
let pendingHelp = false;
/** Whether the Options dialog is open. The gear's `aria-expanded` follows it. */
let settingsOpen = false;
/** Whether the player can be installed here, so the header shows Install. */
let installable = false;
 
/** The document the header's fullscreen button reads. Fullscreen covers the play surface (`#main`) on every device. */
export interface PlayerHeaderFullscreenDocument extends FullscreenDocumentLike {
  documentElement: FullscreenElementLike & { classList: { contains(token: string): boolean } };
  querySelector(selector: string): FullscreenElementLike | null;
}
 
/**
 * The element the header toggles: the play surface (`#main`), the same target as a double-click and a phone's first
 * tap. The site header and the site footer sit outside it.
 */
export function playerHeaderFullscreenTarget(doc: PlayerHeaderFullscreenDocument): FullscreenElementLike {
  return playerFullscreenElement(doc);
}
 
/**
 * Enters or leaves fullscreen with the player's existing helpers. A phone that is still windowed uses
 * {@link enterTouchFullscreen} (the play surface, then landscape). Anything else uses {@link toggleFullscreen}.
 */
export async function togglePlayerHeaderFullscreen(
  doc: PlayerHeaderFullscreenDocument,
  screenLike?: { orientation?: { lock?: (orientation: string) => Promise<void> } },
): Promise<void> {
  const target = playerHeaderFullscreenTarget(doc);
  const enteringOnPhone = doc.documentElement.classList.contains('phone') && getFullscreenElement(doc) === null;
  if (enteringOnPhone) {
    Iif (screenLike === undefined) await enterTouchFullscreen(target, doc);
    else await enterTouchFullscreen(target, doc, screenLike);
    return;
  }
  await toggleFullscreen(target, doc);
}
 
/**
 * The shared header for Play: it spans the viewport, Settings sits where other services put the Play link, and
 * fullscreen sits beside Settings.
 */
export function playerServiceHeaderTemplate(input: {
  locale: PlayerLang;
  hostname: string;
  requestURL: string;
  account?: PlayerHeaderAccount;
  /** The account is still being read: a placeholder stands where it will show. */
  accountLoading?: boolean;
  /** The page is fullscreen, so the button offers to leave. */
  fullscreenActive?: boolean;
  /** The Options dialog is open, so the gear is expanded. */
  settingsOpen?: boolean;
  /** The player can be installed, so Install shows. */
  installable?: boolean;
}): TemplateResult {
  const signedIn: ServiceHeaderAccount | undefined =
    input.account === undefined
      ? undefined
      : {
          handle: input.account.handle,
          displayName: input.account.displayName,
          anonymous: input.account.anonymous,
          avatarURL:
            input.account.avatarUrl === undefined
              ? undefined
              : leaderboardAvatarURL(input.account.avatarUrl, input.hostname),
        };
  const accountHref =
    input.account === undefined
      ? '#sign-in'
      : leaderboardLink(`/players/${encodeURIComponent(input.account.handle)}`, input.hostname);
  return html`${serviceSkipLinkTemplate(input.locale)}${serviceHeaderTemplate({
    locale: input.locale,
    title: 'Be-Music Play',
    homeHref: '/',
    install: input.installable === true,
    help: true,
    settings: true,
    settingsOpen: input.settingsOpen === true,
    fullscreen: true,
    fullscreenActive: input.fullscreenActive === true,
    spanViewport: true,
    accountHref,
    account: signedIn,
    accountLoading: input.accountLoading === true,
    accountNewTab: true,
    requestURL: input.requestURL,
  })}`;
}
 
/** What a click in the header should do. `sign-in` only while signed out. */
export function classifyPlayerHeaderClick(
  target: { closest(selector: string): { lang?: string } | null },
  signedOut: boolean,
): 'install' | 'help' | 'settings' | 'fullscreen' | 'sign-in' | PlayerLang | undefined {
  if (target.closest('[data-service-header="install"]') !== null) return 'install';
  if (target.closest('[data-service-header="help"]') !== null) return 'help';
  if (target.closest('[data-service-header="fullscreen"]') !== null) return 'fullscreen';
  if (target.closest('[data-service-header="settings"]') !== null) return 'settings';
  const language = target.closest('#language-menu a');
  if (language?.lang === 'en' || language?.lang === 'ja') return language.lang;
  if (signedOut && target.closest('[data-service-header="account"]') !== null) return 'sign-in';
  return undefined;
}
 
/** Remembers who is signed in (`undefined`: signed out), ends the loading placeholder and repaints the header. */
export function setPlayerHeaderAccount(next: PlayerHeaderAccount | undefined): void {
  account = next;
  accountLoading = false;
  paint();
}
 
/** Shows Install while the player can be installed here, and hides it once it is installed. */
export function setPlayerHeaderInstallable(next: boolean): void {
  if (installable === next) return;
  installable = next;
  paint();
}
 
/** The gear's `aria-expanded` follows the Options dialog. */
export function setPlayerHeaderSettingsOpen(open: boolean): void {
  Eif (settingsOpen === open) return;
  settingsOpen = open;
  paint();
}
 
/**
 * Wires Help, Settings, Sign in and the language menu. Help, Settings and Sign in can arrive after the menu and the dialogs exist;
 * a click before that waits. A second Settings click before the menu exists cancels the first. Fullscreen calls
 * {@link togglePlayerHeaderFullscreen} itself.
 */
export function bindPlayerHeader(next: PlayerHeaderActions): void {
  if (next.toggleOptions === null) {
    actions.toggleOptions = undefined;
    pendingMenu = false;
  } else if (next.toggleOptions !== undefined) {
    actions.toggleOptions = next.toggleOptions;
    if (pendingMenu) {
      pendingMenu = false;
      next.toggleOptions();
    }
  }
  if (next.openHelp === null) {
    actions.openHelp = undefined;
    pendingHelp = false;
  } else if (next.openHelp !== undefined) {
    actions.openHelp = next.openHelp;
    Eif (pendingHelp) {
      pendingHelp = false;
      next.openHelp();
    }
  }
  Iif (next.install === null) actions.install = undefined;
  else Iif (next.install !== undefined) actions.install = next.install;
  if (next.openSignIn === null) {
    actions.openSignIn = undefined;
    pendingSignIn = false;
  } else if (next.openSignIn !== undefined) {
    actions.openSignIn = next.openSignIn;
    Eif (pendingSignIn) {
      pendingSignIn = false;
      next.openSignIn();
    }
  }
  if (next.selectLanguage !== undefined) actions.selectLanguage = next.selectLanguage;
}
 
/** Paints the header and keeps it on the player's language. Clicks stay on this element across repaints. */
export function mountPlayerHeader(root: HTMLElement): void {
  if (host === root) {
    paint();
    return;
  }
  // Adopt any server fallback once; subsequent updates belong to this render root.
  root.replaceChildren();
  host = root;
  root.addEventListener('click', onClick);
  onPlayerLangChange(() => paint());
  document.addEventListener('fullscreenchange', paint);
  document.addEventListener('webkitfullscreenchange', paint);
  paint();
}
 
function paint(): void {
  const root = host;
  Eif (root === undefined) return;
  const hostname = typeof location === 'undefined' ? 'localhost' : location.hostname;
  const requestURL = typeof location === 'undefined' ? '/' : `${location.pathname}${location.search}`;
  render(
    playerServiceHeaderTemplate({
      locale: playerLang(),
      hostname,
      requestURL,
      account,
      accountLoading,
      fullscreenActive: getFullscreenElement(document) !== null,
      settingsOpen,
      installable,
    }),
    root,
  );
}
 
function onClick(event: Event): void {
  const target = event.target;
  if (!(target instanceof Element)) return;
  const kind = classifyPlayerHeaderClick(
    {
      closest: (selector) => {
        const match = target.closest(selector);
        return match === null ? null : { lang: match instanceof HTMLAnchorElement ? match.lang : undefined };
      },
    },
    account === undefined,
  );
  if (kind === undefined) return;
  event.preventDefault();
  if (kind === 'en' || kind === 'ja') {
    const menu = host?.querySelector<HTMLElement>('#language-menu');
    if (menu?.matches(':popover-open')) menu.hidePopover();
  }
  runPlayerHeaderAction(kind);
}
 
export function runPlayerHeaderAction(
  kind: 'install' | 'help' | 'settings' | 'fullscreen' | 'sign-in' | PlayerLang,
): void {
  Iif (kind === 'install') {
    actions.install?.();
    return;
  }
  if (kind === 'help') {
    if (actions.openHelp !== undefined) actions.openHelp();
    else pendingHelp = true;
    return;
  }
  Iif (kind === 'fullscreen') {
    if (typeof document !== 'undefined') void togglePlayerHeaderFullscreen(document);
    return;
  }
  if (kind === 'settings') {
    if (actions.toggleOptions !== undefined) actions.toggleOptions();
    else pendingMenu = !pendingMenu;
    return;
  }
  if (kind === 'sign-in') {
    Iif (actions.openSignIn !== undefined) actions.openSignIn();
    else pendingSignIn = true;
    return;
  }
  actions.selectLanguage(kind);
}