All files / app-leaderboard/src/pages score.ts

92.3% Statements 36/39
73.03% Branches 65/89
100% Functions 7/7
94.44% Lines 34/36

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                                                                        13x 13x                                                           4x 4x                                           4x 4x 4x 4x                 15x 15x 15x 15x 15x   15x 2x   13x 13x 13x 13x   13x     15x   15x 4x 4x   13x 13x 13x                         13x 13x   13x             26x 15x                   15x                                                                     12x                                                                                                                                                                          
import type { PageContent } from './template.ts';
import { html, nothing, renderHTML } from '@be-music/service-web-theme/server';
import { HelpTip } from './components/help-tip.ts';
import { openDatabase } from '../db/client.ts';
import { loadScoreDetail } from '../scores/detail.ts';
import { readStoredJSON } from '../scores/stored-json.ts';
import { ResultCards } from './components/lists.ts';
import { Details } from './components/cards.ts';
import { EntityIcon } from './components/entity-icon.ts';
import { chartHref, LocalTime, playerHref, Tag } from './components/basics.ts';
import { loadChartsetOf } from './data.ts';
import { pickPlayInfoRows } from './components/play-info.ts';
import { toPlayInfo } from '../play-info.ts';
import { avatarURL } from '../avatars.ts';
import { cardURL } from '../cards.ts';
import type { ScoreDetail } from '../scores/detail.ts';
import { chartTitle, djLevel, formatGauge, formatScoreRate, lampStyle, rulesetName } from './format.ts';
import { shareText, type ScoreCardData } from './score-card-data.ts';
import { ShareCard } from './components/share-card.ts';
import { scoreCardExcerpt } from './score-card-excerpt.ts';
import { Layout, PageHeader } from './layout.ts';
import { helpHref } from './help-topics.ts';
import { type Messages } from './i18n/index.ts';
import {
  displayRuleset,
  meta,
  notFound,
  PAGE_CACHE,
  pageMessages,
  withArtist,
  type PageContext,
  chartsetCrumbs,
} from './page.ts';
 
/** The share card's content: the play under the ruleset it was played with. */
function scoreCardData(detail: ScoreDetail, played: ScoreDetail['results'][number], title: string): ScoreCardData {
  const lamp = lampStyle(played.clearLamp);
  return {
    genre: detail.chart.genre,
    title,
    subtitle: detail.chart.subtitle,
    artist: detail.chart.artist,
    playerName: detail.player?.displayName ?? '',
    handle: detail.player?.handle ?? '',
    avatarUrl: detail.player !== null ? avatarURL(detail.player.handle, detail.player.avatarKey) : '',
    rulesetLabel: rulesetName(played.ruleset),
    lamp: { label: lamp.label, color: lamp.color },
    exScore: played.exScore,
    maxExScore: played.noteCount * 2,
    rate: formatScoreRate(played.exScore, played.noteCount),
    djRank: djLevel(played.exScore, played.noteCount),
    bp: played.missCount,
    maxCombo: played.maxCombo,
    judges: {
      pgreat: played.judges.pgreat ?? 0,
      great: played.judges.great ?? 0,
      good: played.judges.good ?? 0,
      bad: played.judges.bad ?? 0,
      poor: (played.judges.poor ?? 0) + (played.judges.emptyPoor ?? 0),
    },
    gauge: formatGauge(played.gaugeType, played.gaugeFinal),
    playedAt: detail.score.createdAt.getTime(),
  };
}
 
/** The play's own player hides it, or shows it again (wired by the client script's `hide-score` / `show-score`). */
function VisibilityCard(props: { scoreId: string; hidden: boolean }, messages: Messages) {
  const t = messages.score;
  return html`<section class="card gap-4" data-size="sm">
    <header>
      <h2>${t.visibility}</h2>
      <p>${props.hidden ? t.visibilityHiddenLead : t.visibilityShownLead}</p>
    </header>
    <div class="space-y-3 px-4">
      <button
        type="button"
        class="btn"
        data-variant="outline"
        data-account-action=${props.hidden ? 'show-score' : 'hide-score'}
        data-score-id=${props.scoreId ?? nothing}
      >
        ${props.hidden ? t.show : t.hide}
      </button>
      <p class="text-destructive text-sm" data-visibility-status role="status" hidden></p>
    </div>
  </section>`;
}
 
/** The excerpt for a play's card, from the chart's fingerprint document in R2; null when it cannot be read. */
async function loadCardExcerpt(c: PageContext, documentKey: string, laneMode: string | null) {
  Iif (laneMode === null) return null;
  try {
    const object = await c.env.BLOBS.get(documentKey);
    return object === null ? null : scoreCardExcerpt(await readStoredJSON(object), laneMode);
  } catch (error) {
    console.warn('could not read the chart document for a score card', error);
    return null;
  }
}
 
/** One play under every ruleset, with how it was played. */
export async function scorePage(c: PageContext<'/scores/:id'>) {
  const messages = pageMessages(c);
  const db = openDatabase(c.env.DB);
  const detail = await loadScoreDetail(db, c.req.param('id'));
  const viewer = c.get('viewer');
  const isOwner = viewer !== null && viewer.userId === detail?.score.userId;
  // A hidden play is its player's alone: to anyone else it does not exist.
  if (detail === undefined || detail.player === null || (detail.score.hidden && !isOwner)) {
    return notFound(c, 'score');
  }
  const { player } = detail;
  const filed = await loadChartsetOf(db, detail.chart.chartsetId);
  const title = chartTitle(detail.chart.title, detail.chart.chartFingerprint);
  const played = detail.results.find((result) => result.ruleset === detail.score.playedRuleset);
  const description =
    played !== undefined
      ? `${player.displayName} · ${title} · EX ${played.exScore} (${rulesetName(played.ruleset)})`
      : `${player.displayName} · ${title}`;
  const card = played === undefined ? undefined : scoreCardData(detail, played, title);
  // The play's own player draws the card when it has none yet: hand them the chart's notes for its playfield.
  if (card !== undefined && isOwner && detail.score.cardKey === null) {
    const excerpt = await loadCardExcerpt(c, detail.chart.documentKey, detail.chart.laneMode);
    Eif (excerpt !== null) card.excerpt = excerpt;
  }
  const image = cardURL(detail.score.id, detail.score.cardKey);
  const { hidden } = detail.score;
  const info = toPlayInfo({
    scoreId: detail.score.id,
    createdAt: detail.score.createdAt,
    playedRuleset: detail.score.playedRuleset,
    gauge: detail.score.gauge,
    assistFlags: detail.score.assistFlags,
    laneOption: detail.score.laneOption,
    durationMs: detail.score.durationMs,
    verification: detail.score.verification,
    recordedBy: detail.score.recordedBy,
    submittedBy: detail.score.submittedBy,
    serverEngine: detail.score.serverEngine,
  });
  c.header('cache-control', PAGE_CACHE);
  const t = pageMessages(c);
  // Why the rankings and lists leave a shown play out; the play's own player also reads how to change it.
  const notPublic = [
    detail.chart.status === 'listed' ? undefined : t.visibility.reasonNotListed,
    player.anonymous
      ? isOwner
        ? t.visibility.sentences([t.visibility.reasonAnonymous, t.visibility.passkeyHint])
        : t.visibility.reasonAnonymous
      : undefined,
  ].filter((reason) => reason !== undefined);
  const pageMeta = {
    ...meta(c, `${title} — ${player.displayName}`, description, [
      ...chartsetCrumbs(filed),
      { label: title, href: chartHref(detail.chart.chartFingerprint), kind: 'chart' as const },
      { label: t.score.crumb(player.displayName), kind: 'score' as const },
    ]),
    image: { path: image, alt: card !== undefined ? shareText(card) : description },
    // A play of a chart not listed yet stays out of search engines too, and so does a hidden one.
    noindex: hidden || detail.chart.status !== 'listed',
  };
  return c.html(
    renderHTML(
      Layout({
        meta: pageMeta,
        children: html`${PageHeader({
          kind: 'score',
          title: html`<a
            class="underline-offset-4 hover:underline"
            href=${chartHref(detail.chart.chartFingerprint) ?? nothing}
            >${title}</a
          >`,
          children: html`${withArtist(detail.chart.artist)}${t.score.playedBy}<a
              class="text-foreground font-medium underline-offset-4 hover:underline"
              href=${playerHref(player.handle) ?? nothing}
              >${player.displayName}</a
            >${player.anonymous ? Tag({ children: html`${t.lists.anonymous}` }) : null}`,
        })}${
          detail.score.unranked !== null
            ? html`<div class="alert" role="note">
                <h2>${t.score.unrankedTitle}</h2>
                <section>${t.score.unrankedReasons[detail.score.unranked]}</section>
              </div>`
            : null
        }${
          hidden
            ? html`<div class="alert" role="note">
                <h2>${t.score.hiddenTitle}</h2>
                <section>${t.score.hiddenLead}</section>
              </div>`
            : notPublic.length > 0
              ? html`<div class="alert" role="note">
                  <h2>${t.visibility.title}</h2>
                  <section>
                    <p>${t.visibility.lead}</p>
                    <ul class="mt-1 list-disc space-y-0.5 ps-5">
                      ${notPublic.map((reason) => html`<li>${reason}</li>`)}
                    </ul>
                    <a class="mt-1 inline-block underline underline-offset-4" href=${helpHref('visibility') ?? nothing}
                      >${t.help.more}</a
                    >
                  </section>
                </div>`
              : null
        }${ResultCards(
          { results: detail.results, playedRuleset: detail.score.playedRuleset, displayRuleset: displayRuleset(c) },
          messages,
        )}${Details({
          title: t.score.details,
          rows: [
            [t.score.played, LocalTime({ at: detail.score.createdAt.getTime() })],
            // What the lists' info popover shows of a play, here on every screen width, around the rows this page
            // writes with help tips of its own.
            ...pickPlayInfoRows(info, t, ['playedUnder']),
            [
              html`<span class="inline-flex items-center gap-0.5"
                >${t.score.gauge}${HelpTip(
                  { topic: 'gauges', label: t.score.gauge, children: html`${t.score.gaugeHelp}` },
                  messages,
                )}</span
              >`,
              detail.score.gauge,
            ],
            ...pickPlayInfoRows(info, t, ['lanes']),
            [t.score.assists, detail.score.assisted ? detail.score.assistFlags.join(', ') : t.score.none],
            ...pickPlayInfoRows(info, t, ['length']),
            [
              html`<span class="inline-flex items-center gap-0.5"
                >${t.score.verification}${HelpTip(
                  { topic: 'verification', label: t.score.verification, children: html`${t.score.verificationHelp}` },
                  messages,
                )}</span
              >`,
              t.playInfo.verification[detail.score.verification] ?? detail.score.verification,
            ],
            ...pickPlayInfoRows(info, t, ['app', 'sentFrom', 'scoredBy']),
            [
              t.score.chart,
              html`<a
                class="inline-flex items-center gap-1 underline-offset-4 hover:underline"
                href=${chartHref(detail.chart.chartFingerprint) ?? nothing}
                >${EntityIcon({ kind: 'chart', size: 'sm' })}${title}</a
              >`,
            ],
            [
              t.score.fingerprint,
              html`<span class="font-mono text-xs break-all">${detail.chart.chartFingerprint}</span>`,
            ],
            ...(detail.score.replayVisibility === 'public'
              ? ([
                  [
                    t.score.replay,
                    html`<a
                      class="underline-offset-4 hover:underline"
                      href=${`/api/v0/scores/${encodeURIComponent(detail.score.id)}/replay`}
                      download
                      >${t.score.downloadReplay}</a
                    >`,
                  ],
                ] as Array<[PageContent, PageContent]>)
              : []),
          ],
        })}${
          card !== undefined && !hidden
            ? ShareCard(
                {
                  data: card,
                  text: shareText(card),
                  pageURL: c.req.url,
                  image: image,
                  upload: isOwner ? `/api/v0/scores/${encodeURIComponent(detail.score.id)}/card` : undefined,
                  hasCard: detail.score.cardKey !== null,
                },
                messages,
              )
            : null
        }${isOwner ? VisibilityCard({ scoreId: detail.score.id, hidden: hidden }, messages) : null}`,
      }),
    ),
  );
}