All files / app-leaderboard/src/pages course-run.ts

96.15% Statements 25/26
68.18% Branches 45/66
100% Functions 4/4
100% Lines 22/22

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                                                  4x 4x                                           9x 9x 9x 9x 9x   9x 7x 7x 7x 7x 7x 7x 9x 9x   9x     9x                           9x                       9x 9x 9x                                                                                                                                                                                                                                                                                                            
import { html, nothing, renderHTML } from '@be-music/service-web-theme/server';
import { avatarURL } from '../avatars.ts';
import { courseCardURL } from '../cards.ts';
import { openDatabase } from '../db/client.ts';
import { loadCourseDetail } from '../courses/detail.ts';
import { toPlayInfo } from '../play-info.ts';
import { CourseStagesList } from './components/course-lists.ts';
import { Details } from './components/cards.ts';
import { EntityIcon } from './components/entity-icon.ts';
import { courseHref, LocalTime, playerHref, SectionHeading, Tag } from './components/basics.ts';
import { HelpTip } from './components/help-tip.ts';
import { ResultCards } from './components/lists.ts';
import { pickPlayInfoRows } from './components/play-info.ts';
import { ShareCard } from './components/share-card.ts';
import { courseShareText } from './course-card-data.ts';
import { courseCardData } from './course-run-card.ts';
import { loadCourseRun } from './data.ts';
import { RULESET_LABELS, rulesetName } from './format.ts';
import { helpHref } from './help-topics.ts';
import { type Messages } from './i18n/index.ts';
import { Layout, PageHeader } from './layout.ts';
import { displayRuleset, meta, notFound, PAGE_CACHE, pageMessages, type PageContext } from './page.ts';
 
/** The run's own player hides it, or shows it again (wired by the client script's `hide-score` / `show-score`). */
function RunVisibilityCard(props: { courseScoreId: string; hidden: boolean }, messages: Messages) {
  const t = messages.courseRun;
  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-course-score-id=${props.courseScoreId ?? nothing}
      >
        ${props.hidden ? t.show : t.hide}
      </button>
      <p class="text-destructive text-sm" data-visibility-status role="status" hidden></p>
    </div>
  </section>`;
}
 
/** One course run under every ruleset, broken down by stage under the display ruleset, with how it was played. */
export async function courseRunPage(c: PageContext<'/course-scores/:id'>) {
  const messages = pageMessages(c);
  const db = openDatabase(c.env.DB);
  const found = await loadCourseRun(db, c.req.param('id'));
  const viewer = c.get('viewer');
  const isOwner = viewer !== null && viewer.userId === found?.run.userId;
  // A hidden run is its player's alone: to anyone else it does not exist.
  if (found === undefined || found.player === null || (found.run.hidden && !isOwner)) return notFound(c, 'score');
  const course = await loadCourseDetail(db, found.run.courseFingerprint);
  Iif (course === undefined) return notFound(c, 'score');
  const { run, player } = found;
  const ruleset = displayRuleset(c);
  const t = pageMessages(c);
  const rules = t.rules.name(RULESET_LABELS[ruleset] ?? ruleset);
  const shown = found.results.find((result) => result.ruleset === ruleset);
  const played = found.results.find((result) => result.ruleset === run.playedRuleset);
  const description =
    played !== undefined
      ? `${player.displayName} · ${course.name} · EX ${played.exScore} (${rulesetName(played.ruleset)})`
      : `${player.displayName} · ${course.name}`;
  const info = toPlayInfo({
    scoreId: run.id,
    createdAt: run.createdAt,
    playedRuleset: run.playedRuleset,
    gauge: run.gauge,
    assistFlags: run.assistFlags,
    laneOption: null,
    durationMs: null,
    verification: run.verification,
    recordedBy: run.recordedBy,
    submittedBy: run.submittedBy,
    serverEngine: run.serverEngine,
  });
  const card =
    played === undefined
      ? undefined
      : courseCardData({
          course,
          played,
          player: {
            displayName: player.displayName,
            handle: player.handle,
            avatarUrl: avatarURL(player.handle, player.avatarKey),
          },
          playedAt: run.createdAt.getTime(),
        });
  const image = courseCardURL(run.id, run.cardKey);
  c.header('cache-control', PAGE_CACHE);
  return c.html(
    renderHTML(
      Layout({
        meta: {
          ...meta(c, `${course.name} — ${player.displayName}`, description, [
            { label: course.name, href: courseHref(course.courseFingerprint), kind: 'course' },
            { label: t.courseRun.crumb(player.displayName), kind: 'score' },
          ]),
          image: { path: image, alt: card !== undefined ? courseShareText(card) : description },
          // A hidden run stays out of search engines, and so does an anonymous one.
          noindex: run.hidden || player.anonymous,
        },
        children: html`${PageHeader({
            kind: 'score',
            title: html`<a
              class="underline-offset-4 hover:underline"
              href=${courseHref(course.courseFingerprint) ?? nothing}
              >${course.name}</a
            >`,
            children: html`${t.course.kinds[course.kind] ?? course.kind} · ${t.courseRun.runBy}${' '}<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}`,
          })}${
            run.unranked !== null
              ? html`<div class="alert" role="note">
                  <h2>${t.courseRun.unrankedTitle}</h2>
                  <section>${t.courseRun.unrankedReasons[run.unranked]}</section>
                </div>`
              : null
          }${
            run.hidden
              ? html`<div class="alert" role="note">
                  <h2>${t.courseRun.hiddenTitle}</h2>
                  <section>${t.courseRun.hiddenLead}</section>
                </div>`
              : player.anonymous
                ? html`<div class="alert" role="note">
                    <h2>${t.courseRun.notPublicTitle}</h2>
                    <section>
                      <p>${t.visibility.lead}</p>
                      <ul class="mt-1 list-disc space-y-0.5 ps-5">
                        <li>
                          ${
                            isOwner
                              ? t.visibility.sentences([t.visibility.reasonAnonymous, t.visibility.passkeyHint])
                              : t.visibility.reasonAnonymous
                          }
                        </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: found.results,
              stageCount: course.stages.length,
              playedRuleset: run.playedRuleset,
              displayRuleset: ruleset,
            },
            messages,
          )}
          <section class="space-y-3" aria-labelledby="stages">
            ${SectionHeading({
              id: 'stages',
              note: t.course.stages(course.stages.length),
              children: html`${t.courseRun.stages}`,
            })}
            <p class="text-muted-foreground text-sm">
              ${
                shown?.stages === null || shown?.stages === undefined
                  ? t.courseRun.noBreakdown
                  : t.courseRun.stagesLead(rules)
              }
            </p>
            ${CourseStagesList({ stages: course.stages, figures: shown?.stages ?? undefined }, messages)}
          </section>
          ${Details({
            title: t.courseRun.details,
            rows: [
              [t.score.played, LocalTime({ at: run.createdAt.getTime() })],
              ...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
                >`,
                run.gauge,
              ],
              [t.score.assists, run.assisted ? run.assistFlags.join(', ') : t.score.none],
              [
                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[run.verification] ?? run.verification,
              ],
              ...pickPlayInfoRows(info, t, ['app', 'sentFrom', 'scoredBy']),
              [
                t.courseRun.course,
                html`<a
                  class="inline-flex items-center gap-1 underline-offset-4 hover:underline"
                  href=${courseHref(course.courseFingerprint) ?? nothing}
                  >${EntityIcon({ kind: 'course', size: 'sm' })}${course.name}</a
                >`,
              ],
              [
                t.course.rows.fingerprint,
                html`<span class="font-mono text-xs break-all">${course.courseFingerprint}</span>`,
              ],
              [
                t.courseRun.replay,
                html`<a
                  class="underline-offset-4 hover:underline"
                  href=${`/api/v0/course-scores/${encodeURIComponent(run.id)}/replay`}
                  download
                  >${t.courseRun.downloadReplay}</a
                >`,
              ],
            ],
          })}${
            card !== undefined && !run.hidden
              ? ShareCard(
                  {
                    data: card,
                    text: courseShareText(card),
                    kind: 'course',
                    pageURL: c.req.url,
                    image: image,
                    upload: isOwner ? `/api/v0/course-scores/${encodeURIComponent(run.id)}/card` : undefined,
                    hasCard: run.cardKey !== null,
                  },
                  messages,
                )
              : null
          }${isOwner ? RunVisibilityCard({ courseScoreId: run.id, hidden: run.hidden }, messages) : null}`,
      }),
    ),
  );
}