All files / Bandstand/src/components Perform.tsx

69.73% Statements 318/456
71.42% Branches 50/70
41.66% Functions 10/24
69.73% Lines 318/456

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 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628    1x 1x                   1x           1x 1x 1x 1x 1x 1x                                                 1x 1x   10x 10x 10x 10x 10x       10x 10x 10x 10x   10x 10x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 10x 10x   10x 10x       10x 10x 10x 10x 10x 10x 10x   10x 10x 10x   10x 10x 10x 10x       10x 10x                                 10x 10x     10x 10x 5x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 10x     10x 5x 10x 10x     10x 9x                 9x 9x 10x   10x     10x 10x                             10x 2x 2x           2x 10x                 10x 10x                 10x 10x 10x   10x 10x 10x 10x 10x 10x   10x 10x         10x 10x 10x                   10x 10x 10x   10x 10x             10x 10x 10x 10x 10x   10x 10x 10x 10x         10x 10x   10x 10x 10x 10x 10x         10x 10x   10x 10x 10x 10x 10x 10x 10x   10x 10x 10x 10x 10x 10x 10x   10x 10x   10x 10x 10x 10x 10x 10x 10x   10x 10x 10x 10x 10x               10x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x             2x   8x 8x 8x 8x 8x 8x 8x 8x     10x 10x   10x 10x 10x   10x 10x 10x 10x 10x 10x   10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x   10x 10x                                                     10x 10x 10x   10x   10x 10x   10x                       1x                 1x 12x 12x 12x 12x   12x   12x 4x 4x 4x 28x 28x 28x 28x   28x 4x 4x 4x 4x 4x 24x 24x   24x 4x 4x   4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 12x   12x 4x 12x 12x 4x 4x 12x       12x 8x                             8x 8x 12x 12x   12x 12x                     12x 12x   12x   12x 12x 12x 12x   12x 12x 12x     12x 12x 12x 12x   12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x   12x             13x 13x 13x 13x 13x       13x 13x                 13x 13x   13x   13x   13x     10x 10x 10x 3x 3x 3x 3x 3x 10x 10x 10x   10x 10x   3x     3x                             10x 10x  
'use client'
 
import Link from 'next/link'
import {
  forwardRef,
  useCallback,
  useEffect,
  useImperativeHandle,
  useLayoutEffect,
  useMemo,
  useRef,
  useState,
} from 'react'
import {
  detectKey,
  parseChordPro,
  semitonesBetween,
  transposeChart,
} from '@/lib/chordpro'
import ChartBody from '@/components/chart/ChartBody'
import ChordPopover from '@/components/chart/ChordPopover'
import {OfflineBadge} from '@/components/pwa/PwaSetup'
import {useStoredState} from '@/components/useStoredState'
import {TEXT_SIZES} from '@/components/ChartScreen'
import {readOnlyCueSlots} from '@/components/cues/useCueSlots'
import type {Cue} from '@/lib/cues'
 
export type PerformSong = {
  id: string
  title: string
  leadSinger: string | null
  source: string
  /** Key for this set, when it differs from the chart */
  key: string | null
  note: string | null
  /** Your own cues on this song */
  cues: Cue[]
  /** Its place in its set, when the gig is divided into sets */
  set?: {label: string; n: number; count: number} | null
  /** What comes before the next song: a break, or the next set */
  after?:
    | {kind: 'break'; minutes: number | null; until: string | null}
    | {kind: 'set'; label: string}
    | null
}
 
type PerformMode = 'auto' | 'scroll' | 'pages'
 
// Below READABLE the song is paged instead of shrunk further
const READABLE = 16
const MAX_FIT = 34
 
export default function Perform({
  setId,
  name,
  songs,
}: {
  setId: string
  name: string
  songs: PerformSong[]
}) {
  const [index, setIndex] = useStoredState(`mw:perform:${setId}`, 0)
  const i = Math.min(Math.max(index, 0), Math.max(songs.length - 1, 0))
  const song = songs[i]
 
  const charts = useMemo(
    () =>
      songs.map((s) => {
        const chart = parseChordPro(s.source)
        const from = detectKey(chart)
        const steps = s.key && from ? semitonesBetween(from, s.key) : 0
        const shown = steps ? transposeChart(chart, steps) : chart
        return {
          chart: shown,
          cues: readOnlyCueSlots(shown, s.cues, from, steps),
        }
      }),
    [songs],
  )
 
  const chartRef = useRef<FittedChartHandle>(null)
  const [page, setPage] = useState({page: 0, pages: 1})
  // Scroll: one tall single column (never several columns, which would mean
  // scrolling back up mid-song). Pages: fitted columns, one screen at a time.
  // Phones default to scroll, tablets and desktops to pages.
  const narrow = useNarrow()
  const [modePref, setModePref] = useStoredState<PerformMode>(
    'mw:perform-mode',
    'auto',
  )
  const scroll = modePref === 'auto' ? narrow : modePref === 'scroll'
  const [sizeIdx, setSizeIdx] = useStoredState('mw:text-size', 2)
  // Pages: steps up or down from the size that fits the screen
  const [fitStep, setFitStep] = useStoredState('mw:perform-fit-step', 0)
  const scrollSize =
    TEXT_SIZES[Math.min(Math.max(sizeIdx, 0), TEXT_SIZES.length - 1)]
 
  const toSong = useCallback(
    (d: number) => setIndex(Math.min(Math.max(i + d, 0), songs.length - 1)),
    [i, songs.length, setIndex],
  )
 
  // Next/previous turns the page within a long song first, then changes song.
  // On phones "a page" is a screenful of scrolling.
  const go = useCallback(
    (d: number) => {
      if (scroll) {
        const el = document.scrollingElement ?? document.documentElement
        const atEnd =
          d > 0
            ? el.scrollTop + window.innerHeight >= el.scrollHeight - 8
            : el.scrollTop <= 8
        if (!atEnd) {
          window.scrollBy({
            top: d * window.innerHeight * 0.8,
            behavior: 'smooth',
          })
          return
        }
      } else if (chartRef.current?.turn(d)) return
      toSong(d)
    },
    [scroll, toSong],
  )
 
  // Scroll mode: is there more of the song below the screen?
  const [below, setBelow] = useState(false)
  useEffect(() => {
    if (!scroll) return
    const check = () => {
      const el = document.scrollingElement ?? document.documentElement
      setBelow(el.scrollTop + window.innerHeight < el.scrollHeight - 8)
    }
    check()
    window.addEventListener('scroll', check, {passive: true})
    window.addEventListener('resize', check)
    // Images and notation settle after the first paint
    const t = setTimeout(check, 400)
    return () => {
      window.removeEventListener('scroll', check)
      window.removeEventListener('resize', check)
      clearTimeout(t)
    }
  }, [scroll, i])
 
  // A new song starts at its top
  useEffect(() => {
    if (scroll) window.scrollTo({top: 0})
  }, [i, scroll])
  const jump = (n: number) => setIndex(n)
 
  // Page-turn pedals and keyboards send arrow / page keys
  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if (['ArrowRight', 'ArrowDown', 'PageDown', ' '].includes(e.key)) {
        e.preventDefault()
        go(1)
      } else if (['ArrowLeft', 'ArrowUp', 'PageUp'].includes(e.key)) {
        e.preventDefault()
        go(-1)
      }
    }
    window.addEventListener('keydown', onKey)
    return () => window.removeEventListener('keydown', onKey)
  }, [go])
 
  useWakeLock()
 
  // Swipe left/right
  const touch = useRef<{x: number; y: number} | null>(null)
  const onTouchStart = (e: React.TouchEvent) => {
    // A drag inside something that scrolls sideways (guitar tab) is that
    // thing scrolling, not a swipe to another song
    if ((e.target as Element).closest?.('[data-hscroll]')) {
      touch.current = null
      return
    }
    touch.current = {x: e.touches[0].clientX, y: e.touches[0].clientY}
  }
 
  // A tap on the left or right quarter of the chart turns back or on: in
  // pages mode a page (then the song), in scroll mode the song. Read from
  // the click, which browsers don't fire after a scroll or drag. Anything
  // tappable under the finger (a notation heading, a chord, a button) gets
  // the tap instead
  const onClick = (e: React.MouseEvent) => {
    const t = e.target as Element
    if (t.closest('a,button,summary,input,select,textarea,.chart-chord')) return
    // The header's own words and buttons aren't page-turners
    if (t.closest('header')) return
    const x = e.clientX / window.innerWidth
    if (x > 0.75) (scroll ? toSong : go)(1)
    else if (x < 0.25) (scroll ? toSong : go)(-1)
  }
  const onTouchEnd = (e: React.TouchEvent) => {
    if (!touch.current) return
    const dx = e.changedTouches[0].clientX - touch.current.x
    const dy = e.changedTouches[0].clientY - touch.current.y
    touch.current = null
    if (Math.abs(dx) > 70 && Math.abs(dx) > Math.abs(dy) * 1.5)
      toSong(dx < 0 ? 1 : -1)
  }
 
  if (!song)
    return (
      <main className="flex min-h-dvh flex-col items-center justify-center gap-4 bg-stage p-6 text-center">
        <p className="text-xl">This setlist has no songs yet.</p>
        <Link href={`/setlists/${setId}/edit`} className="text-amber">
          Add songs
        </Link>
      </main>
    )
 
  const {chart, cues} = charts[i]
  const next = songs[i + 1]
  const nextKey = next ? detectKey(charts[i + 1].chart) : null
 
  return (
    <main
      className={`flex flex-col bg-stage px-4 pb-[max(env(safe-area-inset-bottom),12px)] text-text md:px-8 ${scroll ? 'min-h-dvh' : 'h-dvh overflow-hidden pt-[max(env(safe-area-inset-top),12px)]'}`}
      onTouchStart={onTouchStart}
      onTouchEnd={onTouchEnd}
      onClick={onClick}
    >
      <header
        className={`flex shrink-0 flex-wrap items-center gap-x-2 gap-y-1 sm:gap-x-4 ${scroll ? 'sticky top-0 z-10 -mx-4 bg-stage/95 px-4 pb-2 pt-[max(env(safe-area-inset-top),12px)] backdrop-blur' : ''}`}
      >
        {/* Phones: where you are and the buttons on one line that never
            wraps (the position gives way first), the song below. Wider: one
            row, the song in the middle. */}
        <div className="flex w-full min-w-0 items-center gap-1.5 sm:contents">
          <span className="min-w-0 flex-1 truncate font-mono text-muted sm:flex-none">
            {song.set ? (
              <>
                <span className="font-sans font-semibold text-text">
                  {song.set.label}
                </span>
                <span className="hidden sm:inline"> · </span>
                <span className="sm:hidden"> </span>
                {song.set.n}/{song.set.count}
              </>
            ) : (
              <>
                {i + 1} / {songs.length}
              </>
            )}
            <OfflineBadge className="ml-2" />
            {!scroll && page.pages > 1 && (
              <span className="ml-1.5 text-sm sm:ml-2 sm:rounded-full sm:border sm:border-line sm:px-2 sm:py-0.5">
                <span className="hidden sm:inline">page </span>
                <span className="sm:hidden">p.</span>
                {page.page + 1}/{page.pages}
              </span>
            )}
          </span>
          <div
            role="group"
            aria-label="Text size"
            className="flex shrink-0 items-center rounded-lg border border-line sm:order-2"
          >
            <button
              type="button"
              aria-label="Smaller text"
              onClick={() =>
                scroll
                  ? setSizeIdx(Math.max(0, sizeIdx - 1))
                  : setFitStep(Math.max(-3, fitStep - 1))
              }
              className="h-11 w-9 text-sm font-semibold text-muted sm:w-10"
            >
              A
            </button>
            <button
              type="button"
              aria-label="Larger text"
              onClick={() =>
                scroll
                  ? setSizeIdx(Math.min(TEXT_SIZES.length - 1, sizeIdx + 1))
                  : setFitStep(Math.min(5, fitStep + 1))
              }
              className="h-11 w-9 text-xl font-semibold text-muted sm:w-10"
            >
              A
            </button>
          </div>
          <button
            type="button"
            onClick={() => setModePref(scroll ? 'pages' : 'scroll')}
            className="flex min-h-11 shrink-0 items-center rounded-lg border border-line px-2.5 text-sm text-muted sm:order-2 sm:px-3"
            aria-label={scroll ? 'Show as pages' : 'Show as one scrolling page'}
          >
            {scroll ? 'Pages' : 'Scroll'}
          </button>
          <Link
            href={`/setlists/${setId}`}
            className="flex min-h-11 shrink-0 items-center rounded-lg border border-line px-2.5 text-sm text-muted no-underline sm:order-2 sm:px-3.5"
            aria-label={`Exit ${name}`}
          >
            Exit
          </Link>
        </div>
        {/* The song and its key read together; the buttons sit apart */}
        <div className="flex w-full min-w-0 items-baseline gap-3 sm:order-1 sm:w-auto sm:flex-1">
          <h1 className="min-w-0 text-2xl font-extrabold leading-tight sm:truncate md:text-[34px]">
            {song.title}
          </h1>
          <span
            className="shrink-0 font-mono text-2xl font-bold text-amber md:text-[28px]"
            aria-label={`Key ${detectKey(chart) ?? 'unknown'}`}
          >
            {detectKey(chart)}
          </span>
        </div>
      </header>
      {(song.note || song.leadSinger) && (
        <p className="mt-2.5 shrink-0 rounded-lg bg-warn-bg px-3.5 py-2 text-[17px] text-warn-fg">
          {/* The set note carries this band's assignments ("Lead: Mark"); the
              song's own lead singer is only a fallback when there is none */}
          {song.note || `Lead (${song.leadSinger})`}
        </p>
      )}
 
      {scroll ? (
        <div className="mt-4 flex-1 pb-6" style={{fontSize: scrollSize}}>
          <ChartBody
            chart={chart}
            columns={false}
            top={cues.top}
            extra={cues.extra}
          />
          <div className="mt-6 flex justify-end">
            <PageMark more={false} />
          </div>
          {below && (
            <PageMark
              more
              onMore={() => go(1)}
              className="fixed bottom-[calc(max(env(safe-area-inset-bottom),12px)+4.5rem)] right-4 z-20"
            />
          )}
        </div>
      ) : (
        <FittedChart
          key={i}
          ref={chartRef}
          chart={chart}
          cues={cues}
          scale={1.12 ** fitStep}
          onPage={setPage}
        />
      )}
 
      <footer
        className={`flex shrink-0 items-center gap-4 border-t border-line pt-3 ${scroll ? 'sticky bottom-0 z-10 -mx-4 bg-stage/95 px-4 pb-[max(env(safe-area-inset-bottom),12px)] backdrop-blur' : ''}`}
      >
        <div
          className="hidden gap-1.5 sm:flex"
          aria-label={`Song ${i + 1} of ${songs.length}`}
        >
          {songs.map((s, n) => (
            <button
              key={n}
              type="button"
              aria-label={`Go to ${s.title}`}
              onClick={() => jump(n)}
              // A gap between sets, so the shape of the night shows
              className={`h-1.5 w-[18px] rounded ${n === i ? 'bg-accent' : n < i ? 'bg-line-2' : 'bg-line'} ${songs[n - 1]?.after ? 'ml-3' : ''}`}
            />
          ))}
        </div>
        <span className="flex-1" />
        <button
          type="button"
          onClick={() => toSong(-1)}
          disabled={i === 0}
          className="min-h-11 rounded-lg px-3 text-muted disabled:opacity-30"
          aria-label="Previous song"
        >
          ‹ Prev
        </button>
        {next ? (
          <button
            type="button"
            onClick={() => toSong(1)}
            className="flex min-h-11 items-center gap-3 rounded-lg px-2 text-left"
          >
            {song.after?.kind === 'break' ? (
              <span className="rounded-md bg-warn-bg px-2 py-0.5 text-sm font-semibold text-warn-fg">
                Break
                {song.after.minutes ? ` · ${song.after.minutes} min` : ''}
                {song.after.until ? `, back ${song.after.until}` : ''}
              </span>
            ) : song.after?.kind === 'set' ? (
              <span className="rounded-md bg-panel px-2 py-0.5 text-sm font-semibold">
                {song.after.label}
              </span>
            ) : (
              <span className="text-muted">Next</span>
            )}
            <span className="max-w-[40vw] truncate text-lg font-bold md:text-xl">
              {next.title}
            </span>
            <span className="font-mono text-lg font-bold text-amber">
              {nextKey}
            </span>
          </button>
        ) : (
          <span className="text-muted">
            {song.set ? 'End of the gig' : 'End of set'}
          </span>
        )}
      </footer>
 
      <ChordPopover />
    </main>
  )
}
 
type FittedChartHandle = {
  /** Turn a page within the song; false when already at that end. */
  turn: (d: number) => boolean
}
 
/**
 * Lays the chart out in columns that fill the screen at the largest text size
 * that fits on one screen. If it only fits below READABLE, it stays at
 * READABLE and is split into screen-wide pages of columns instead.
 */
const FittedChart = forwardRef<
  FittedChartHandle,
  {
    chart: ReturnType<typeof parseChordPro>
    cues: ReturnType<typeof readOnlyCueSlots>
    /** The reader's own size, against the size that fits (1: as fitted) */
    scale: number
    onPage: (p: {page: number; pages: number}) => void
  }
>(function FittedChart({chart, cues, scale, onPage}, ref) {
  const box = useRef<HTMLDivElement>(null)
  const [size, setSize] = useState(READABLE)
  const [pages, setPages] = useState(1)
  const [page, setPageState] = useState(0)
 
  const GAP_EM = 2.5
 
  const fit = useCallback(() => {
    const el = box.current
    if (!el) return
    const fits = (s: number) => {
      el.style.fontSize = `${s}px`
      return (
        el.scrollWidth <= el.clientWidth + 1 &&
        el.scrollHeight <= el.clientHeight + 1
      )
    }
    let best = READABLE
    if (fits(READABLE)) {
      let lo = READABLE
      let hi = MAX_FIT
      while (hi - lo > 0.5) {
        const mid = (lo + hi) / 2
        if (fits(mid)) lo = mid
        else hi = mid
      }
      best = Math.floor(lo * 2) / 2
    }
    // Bigger than fits spills onto more pages; smaller leaves room
    best = Math.max(10, Math.round(best * scale * 2) / 2)
    el.style.fontSize = `${best}px`
    const gap = best * GAP_EM
    const n = Math.max(
      1,
      Math.ceil((el.scrollWidth + gap - 1) / (el.clientWidth + gap)),
    )
    el.scrollLeft = 0
    setSize(best)
    setPages(n)
    setPageState(0)
  }, [scale])
 
  useLayoutEffect(() => {
    fit()
  }, [fit, chart])
  useEffect(() => {
    window.addEventListener('resize', fit)
    return () => window.removeEventListener('resize', fit)
  }, [fit])
 
  // Notation opened or closed: same text size, but the pages are counted
  // again, staying on this page (or the last, if it is now shorter)
  useEffect(() => {
    const repage = () => {
      const el = box.current
      if (!el) return
      const gap = size * GAP_EM
      const n = Math.max(
        1,
        Math.ceil((el.scrollWidth + gap - 1) / (el.clientWidth + gap)),
      )
      setPages(n)
      setPageState((p) => {
        const keep = Math.min(p, n - 1)
        el.scrollTo({left: keep * (el.clientWidth + gap), behavior: 'instant'})
        return keep
      })
    }
    window.addEventListener('ms:chart-size', repage)
    return () => window.removeEventListener('ms:chart-size', repage)
  }, [size])
  useEffect(() => onPage({page, pages}), [page, pages, onPage])
 
  const turn = useCallback(
    (d: number) => {
      const el = box.current
      const target = page + d
      if (!el || target < 0 || target >= pages) return false
      el.scrollTo({
        left: target * (el.clientWidth + size * GAP_EM),
        behavior: 'instant',
      })
      setPageState(target)
      return true
    },
    [page, pages, size],
  )
 
  useImperativeHandle(ref, () => ({turn}), [turn])
 
  return (
    <div className="relative mt-4 flex min-h-0 flex-1 flex-col">
      <div
        ref={box}
        // The strip under it holds the More / End marker, never over a chord
        className="mb-11 min-h-0 flex-1 overflow-hidden"
        style={{
          fontSize: size,
          // Columns fill top-to-bottom, then the next column, like a printed
          // page; overflow continues to the right as further "pages".
          columnWidth: '21em',
          columnGap: `${GAP_EM}em`,
          columnFill: 'auto',
        }}
      >
        <ChartBody
          chart={chart}
          columns={false}
          top={cues.top}
          extra={cues.extra}
        />
      </div>
      <PageMark
        more={page < pages - 1}
        onMore={() => turn(1)}
        className="absolute bottom-0 right-0"
      />
    </div>
  )
})
 
/**
 * Bottom right: "More ›" while there's more of this song (another page, or
 * more below), "End" once you've reached its end. Tapping More turns the
 * page, like the pedal.
 */
function PageMark({
  more,
  onMore,
  className = '',
}: {
  more: boolean
  onMore?: () => void
  className?: string
}) {
  return more ? (
    <button
      type="button"
      onClick={onMore}
      className={`flex min-h-9 items-center rounded-full bg-accent px-3 text-sm font-bold text-on-accent shadow-lg ${className}`}
    >
      More ›
    </button>
  ) : (
    <span
      className={`flex min-h-9 items-center gap-1.5 rounded-full border border-line bg-stage px-3 text-sm text-muted ${className}`}
    >
      <span aria-hidden="true" className="h-2 w-2 bg-muted" />
      End
    </span>
  )
}
 
/** True on phone-width screens (and while the window is that narrow). */
function useNarrow() {
  const [narrow, setNarrow] = useState(false)
  useEffect(() => {
    const mq = window.matchMedia('(max-width: 639px)')
    const update = () => setNarrow(mq.matches)
    update()
    mq.addEventListener('change', update)
    return () => mq.removeEventListener('change', update)
  }, [])
  return narrow
}
 
function useWakeLock() {
  useEffect(() => {
    type Sentinel = {release: () => Promise<void>}
    const nav = navigator as Navigator & {
      wakeLock?: {request: (t: 'screen') => Promise<Sentinel>}
    }
    if (!nav.wakeLock) return
    let lock: Sentinel | null = null
    const acquire = () =>
      nav.wakeLock!.request('screen').then(
        (l) => (lock = l),
        () => {},
      )
    acquire()
    // The lock is dropped whenever the page is hidden; take it back on return
    const onVis = () => document.visibilityState === 'visible' && acquire()
    document.addEventListener('visibilitychange', onVis)
    return () => {
      document.removeEventListener('visibilitychange', onVis)
      lock?.release().catch(() => {})
    }
  }, [])
}