diff --git a/code/modules/mob/dead/new_player/new_player.dm b/code/modules/mob/dead/new_player/new_player.dm index 512a64f410d..061b73ab6f6 100644 --- a/code/modules/mob/dead/new_player/new_player.dm +++ b/code/modules/mob/dead/new_player/new_player.dm @@ -65,7 +65,7 @@ vote_on_poll_handler(poll, href_list) //When you cop out of the round (NB: this HAS A SLEEP FOR PLAYER INPUT IN IT) -/mob/dead/new_player/proc/make_me_an_observer() +/mob/dead/new_player/proc/make_me_an_observer(confirmed = FALSE) // VOIDCREW EDIT CHANGE - lobby_terminal: confirmed skips the alert; the dock terminal asks in its own window - ORIGINAL: /mob/dead/new_player/proc/make_me_an_observer() if(QDELETED(src) || !src.client) ready = PLAYER_NOT_READY return FALSE @@ -74,7 +74,7 @@ if(SSlag_switch.measures[DISABLE_DEAD_KEYLOOP]) less_input_message = " - Notice: Observer freelook is currently disabled." // Don't convert this to tgui please, it's way too important - var/this_is_like_playing_right = alert(usr, "Are you sure you wish to observe? [get_respawn_notice()][less_input_message]", "Observe", "Yes", "No") // VOIDCREW EDIT: ghost respawn integration: display the applicable respawn notice (voidcrew/edits/mobs/ghost_respawn.dm) + var/this_is_like_playing_right = confirmed ? "Yes" : alert(usr, "Are you sure you wish to observe? [get_respawn_notice()][less_input_message]", "Observe", "Yes", "No") // VOIDCREW EDIT: ghost respawn integration: display the applicable respawn notice (voidcrew/edits/mobs/ghost_respawn.dm); lobby_terminal: no alert when already confirmed if(QDELETED(src) || !src.client || this_is_like_playing_right != "Yes") ready = PLAYER_NOT_READY return FALSE diff --git a/config/config.txt b/config/config.txt index a4249a78cf5..f0c77de0f25 100644 --- a/config/config.txt +++ b/config/config.txt @@ -192,7 +192,7 @@ IPINTEL_REJECT_BAD # WIKIURL http://tgstation13.org/wiki ## Rules address -# RULESURL http://tgstation13.org/wiki/Rules +RULESURL https://rules.voidcrew-lrp.com ## Github address # GITHUBURL https://www.github.com/tgstation/tgstation diff --git a/tgstation.dme b/tgstation.dme index 0be2b3f7f81..9139c17373f 100644 --- a/tgstation.dme +++ b/tgstation.dme @@ -7397,6 +7397,9 @@ #include "voidcrew\modules\lobby_terminal\lobby_character_preview.dm" #include "voidcrew\modules\lobby_terminal\lobby_crews.dm" #include "voidcrew\modules\lobby_terminal\lobby_housing.dm" +#include "voidcrew\modules\lobby_terminal\lobby_music.dm" +#include "voidcrew\modules\lobby_terminal\lobby_settings.dm" +#include "voidcrew\modules\lobby_terminal\lobby_settings_keys.dm" #include "voidcrew\modules\lobby_terminal\lobby_tgui.dm" #include "voidcrew\modules\lobby_terminal\lobby_yard.dm" #include "voidcrew\modules\loot\abandoned_crate.dm" @@ -7818,6 +7821,7 @@ #include "voidcrew\modules\ship_saves\ship_save_console.dm" #include "voidcrew\modules\ship_saves\ship_save_construction.dm" #include "voidcrew\modules\ship_saves\ship_save_lobby.dm" +#include "voidcrew\modules\ship_saves\ship_save_lobby_terminal.dm" #include "voidcrew\modules\ship_saves\ship_save_progress.dm" #include "voidcrew\modules\ship_saves\ship_save_store.dm" #include "voidcrew\modules\ship_saves\ship_save_survey.dm" diff --git a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/Bezel.tsx b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/Bezel.tsx index b920f8f4f49..5064e5489c0 100644 --- a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/Bezel.tsx +++ b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/Bezel.tsx @@ -1,115 +1,21 @@ /** - * The terminal's bezel: frame, top strip, deck with the big keys, grille and the tray of - * small lobby buttons. Class tree from the art's lobby_terminal.css: + * The terminal's bezel: the frame and its top strip around the glass. It covers the whole + * pane. Class tree from the art's lobby_terminal.css: * - * .lt-bezel (--s) > .lt-screen, .lt-frame > .lt-strip, .lt-deck > .lt-deck-row > - * .lt-keys > .lt-key..., .lt-grille-slot > .lt-grille, .lt-tray > .lt-sbtn... + * .lt-bezel (--s) > .lt-screen, .lt-frame > .lt-strip * - * Without the art (static.bezel null) the same tree is drawn by PLACEHOLDER_CSS. + * No keys, no focusables, no game data. Without the art (static.bezel null) the same tree is + * drawn flat by PLACEHOLDER_CSS. */ import type { ReactNode } from 'react'; -import { resolveAsset } from 'tgui/assets'; import { useBackend } from 'tgui/backend'; -import { useFocusable } from './nav'; -import type { LobbyData } from './types'; - -type KeyId = 'join' | 'ready' | 'notready' | 'observe' | 'character' | 'start'; - -const KEY_LABEL: Record = { - join: 'JOIN', - ready: 'READY', - notready: 'READY', - observe: 'OBSERVE', - character: 'CHARACTER', - start: 'START', -}; -function Key(props: { - id: KeyId; - disabled?: boolean; - /** Glows while its screen is open (CHARACTER). */ - lit?: boolean; - title: string; - onClick: () => void; -}) { - const { id, disabled, lit, title, onClick } = props; - const focus = useFocusable(!disabled, { - activate: onClick, - }); - return ( - - ); -} - -type SmallId = 'wiki' | 'poll' | 'crew_manifest' | 'settings' | 'changelog'; - -function SmallButton(props: { - id: SmallId; - title: string; - disabled?: boolean; - mark?: boolean; - onClick: () => void; -}) { - const { id, title, disabled, mark, onClick } = props; - const focus = useFocusable(!disabled, { - activate: onClick, - }); - const state = disabled ? '_disabled' : focus.focused ? '_highlighted' : ''; - return ( - - ); -} +import type { LobbyData } from './types'; -export function Bezel(props: { - s: number; - children: ReactNode; - /** The CHARACTER tab is open: the key glows. */ - characterLit?: boolean; - /** The CHARACTER key: switches to the CHARACTER tab. */ - onCharacter: () => void; -}) { - const { s, children, characterLit, onCharacter } = props; - const { data, act } = useBackend(); +export function Bezel(props: { s: number; children: ReactNode }) { + const { s, children } = props; + const { data } = useBackend(); const art = !!data.bezel; - const preRound = data.phase === 'loading' || data.phase === 'pregame'; - const ready = !!data.ready; - const showReady = preRound || data.phase === 'setup'; - return (
-
-
-
- {showReady ? ( - <> - act('ready')} - /> - - - ) : ( - act('join')} - /> - )} - act('observe')} - /> - - {data.localhost_admin && preRound ? ( - act('start_now')} - /> - ) : null} -
-
-
-
-
- act('wiki')} - /> - act('polls')} - /> - act('manifest')} - /> - act('settings')} - /> - act('changelog')} - /> -
-
-
); } -/** - * Keycap legends are baked into the art; only the placeholder (and the START key, which has - * no art) shows the text legend. - */ -const LEGEND_CSS = ` -.lt-key-legend { display: none; } -.lt-key--start { width: calc(var(--s) * 52px); height: calc(var(--s) * 34px); position: relative; - background: #9aa39f; box-shadow: inset 0 0 0 calc(var(--s) * 2px) #20202a; } -.lt-key--start .lt-key-legend, .lt-ph .lt-key-legend { display: block; position: absolute; - left: calc(var(--s) * 6px); right: calc(var(--s) * 6px); top: calc(var(--s) * 9px); height: calc(var(--s) * 13px); - background: #36373a; color: #7effbf; font-family: 'VCR', monospace; font-size: calc(var(--s) * 9px); - line-height: calc(var(--s) * 13px); text-align: center; letter-spacing: calc(var(--s) * 1px); } -.lt-key--start.is-focus .lt-key-legend { color: #ffc41f; } -.lt-key-legend { pointer-events: none; } -.lt-key.is-lit { position: relative; } -.lt-key.is-lit::after { content: ''; position: absolute; pointer-events: none; - left: calc(var(--s) * 9px); top: calc(var(--s) * 5px); width: calc(var(--s) * 77px); height: calc(var(--s) * 15px); - background: rgba(126,255,191,.16); mix-blend-mode: screen; - box-shadow: 0 0 calc(var(--s) * 6px) rgba(126,255,191,.55), inset 0 0 calc(var(--s) * 3px) rgba(126,255,191,.5); } -`; - -export const BEZEL_EXTRA_CSS = LEGEND_CSS; - -/** Stand-in for the art: the same layout in flat lobby colours. */ +/** Stand-in for the art: a flat frame in the bezel's body colour. */ const PLACEHOLDER_CSS = ` -.lt-ph.lt-bezel { --s: 1; position: absolute; inset: 0; overflow: hidden; background: #9aa39f; user-select: none; } +.lt-ph.lt-bezel { --s: 1; position: absolute; inset: 0; overflow: hidden; background: #43365a; user-select: none; } .lt-ph .lt-screen { position: absolute; top: calc(var(--s) * 15px); left: calc(var(--s) * 13px); - right: calc(var(--s) * 13px); bottom: calc(var(--s) * 52px); overflow: hidden; z-index: 1; } + right: calc(var(--s) * 13px); bottom: calc(var(--s) * 3px); overflow: hidden; z-index: 1; } .lt-ph .lt-frame { position: absolute; top: calc(var(--s) * 12px); left: calc(var(--s) * 10px); - right: calc(var(--s) * 10px); bottom: calc(var(--s) * 49px); box-sizing: border-box; - border: calc(var(--s) * 3px) solid #51575e; border-bottom-color: #e0e3dc; border-right-color: #e0e3dc; - pointer-events: none; z-index: 2; } + right: calc(var(--s) * 10px); bottom: 0; box-sizing: border-box; + border: calc(var(--s) * 3px) solid #33284a; border-bottom: 0; pointer-events: none; z-index: 2; } .lt-ph .lt-strip { position: absolute; top: calc(var(--s) * -10px); left: calc(50% - var(--s) * 30px); - width: calc(var(--s) * 61px); height: calc(var(--s) * 6px); background: #36373a; } -.lt-ph .lt-deck { position: absolute; left: 0; right: 0; bottom: 0; height: calc(var(--s) * 49px); z-index: 2; - border-top: calc(var(--s) * 2px) solid #e0e3dc; box-sizing: border-box; } -.lt-ph .lt-deck-row { position: absolute; top: calc(var(--s) * 6px); left: calc(var(--s) * 30px); - right: calc(var(--s) * 29px); display: flex; align-items: flex-start; } -.lt-ph .lt-keys { display: flex; align-items: flex-start; flex: none; } -.lt-ph .lt-key { display: block; flex: none; margin: 0; padding: 0; border: 0; outline: 0; position: relative; - height: calc(var(--s) * 34px); background: #bec4bf; box-shadow: inset 0 0 0 calc(var(--s) * 2px) #20202a; cursor: pointer; } -.lt-ph .lt-key + .lt-key { margin-left: calc(var(--s) * 4px); } -.lt-ph .lt-key--join, .lt-ph .lt-key--ready, .lt-ph .lt-key--notready { width: calc(var(--s) * 68px); } -.lt-ph .lt-key--observe { width: calc(var(--s) * 84px); } -.lt-ph .lt-key--character { width: calc(var(--s) * 100px); } -.lt-ph .lt-key.is-focus { background: #e0e3dc; } -.lt-ph .lt-key:active { background: #9aa39f; } -.lt-ph .lt-key.is-disabled { cursor: default; background: #9aa39f; } -.lt-ph .lt-key.is-disabled .lt-key-legend { color: #33676a; } -.lt-ph .lt-key--notready .lt-key-legend { color: #ff4f6a; } -.lt-ph .lt-lamp { flex: none; width: calc(var(--s) * 10px); height: calc(var(--s) * 9px); - margin: calc(var(--s) * 11px) calc(var(--s) * 1px) 0 calc(var(--s) * 2px); background: #20202a; } -.lt-ph .lt-lamp + .lt-key { margin-left: 0; } -.lt-ph .lt-lamp--ready { background: #7effbf; } -.lt-ph .lt-lamp--notready { background: #ff4f6a; } -.lt-ph .lt-grille-slot { flex: 1 1 0; min-width: 0; } -.lt-ph .lt-tray { flex: none; position: relative; display: flex; margin-top: calc(var(--s) * 1px); - padding: calc(var(--s) * 3px); width: calc(var(--s) * 142px); height: calc(var(--s) * 31px); - box-sizing: border-box; background: #36373a; } -.lt-ph .lt-sbtn { position: relative; flex: none; margin: 0; padding: 0; border: 0; background: none; - width: calc(var(--s) * 24px); height: calc(var(--s) * 24px); cursor: pointer; } -.lt-ph .lt-sbtn + .lt-sbtn { margin-left: calc(var(--s) * 4px); } -.lt-ph .lt-sbtn-icon, .lt-ph .lt-sbtn-mark { position: absolute; left: 0; top: 0; - transform: scale(var(--s)); transform-origin: 0 0; pointer-events: none; image-rendering: pixelated; } -.lt-ph .lt-sbtn-mark { top: calc(var(--s) * -1px); } + width: calc(var(--s) * 61px); height: calc(var(--s) * 6px); background: #241b36; } `; diff --git a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/Bill.tsx b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/Bill.tsx index cfb0b346a46..4192128cf14 100644 --- a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/Bill.tsx +++ b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/Bill.tsx @@ -1,269 +1,371 @@ /** - * BILL: the fitted ship and its crew on the left, the one bill on the right (each line, - * total, parts on account, any shortfall) and [ COMMISSION ]. When commissioning leaves a - * crew, one amber LEAVES line shows and the key reads CONFIRM after the first press. - * Narrow: the bill alone. + * BILL (spec 02, 3.6): a ledger. The crew, then one slab row an item (the hull, the finish, + * each room's option) with a fixed column for each part class, then TOTAL, ON ACCOUNT and + * SHORT under the same columns, then CHANGE FIT and COMMISSION. No free-form price text, so + * nothing can run into a neighbour. A tall pane puts the fitted ship on top. * - * The client sends the configuration, never prices; the server works out the bill again. + * The page sends the configuration and the total it showed; the server works the bill out + * again, charges only its own figure and refuses one higher than the page showed. */ -import type { ReactNode } from 'react'; +import { type ReactNode, useState } from 'react'; +import { useBackend } from 'tgui/backend'; +import { useLatePager, useWheel } from './CharFrame'; import { ShipPic } from './ShipPic'; -import { cut, Frame, lpad, Put, pad, RPut, Rule, TOP, useGrid } from './term'; -import type { Hull, LobbyActions } from './types'; import { - billOf, - costOf, - crewOf, - fitOf, + Band, + BODY_Y, + Box, + BOX_Y, + bodyRows, + CLASS_EDGES, + ClassFigures, + ClassHeads, + cut, + fig, + HRule, Key, - PART_ORDER, + PART_CLASSES, + Pager, + Put, + RPut, + Slab, + safe, + useGrid, + WipeAt, + wrap, + wrapMax, +} from './term'; +import type { LobbyData } from './types'; +import { + crewCount, + crewText, + fittable, partsOf, + stepsOf, usePreview, + YARD_OPENS, type YardCtx, } from './YardTab'; -export function Bill(props: { - ctx: YardCtx; - hull: Hull; - onCommission: (params: LobbyActions['yard_commission']) => void; -}) { - const { ctx, hull, onCommission } = props; - const { view, set, own } = ctx; - const { cols, rows, narrow } = useGrid(); - usePreview(hull.id); - const h = rows - 1 - TOP; - const fit = fitOf(hull, view.finish, view.picks); - const bill = billOf(own, fit, ctx.account); - const crew = crewOf(fit); - const crewN = crew.reduce((a, l) => a + l[1], 0); +/** Rounds down to a quarter row. */ +const f4 = (v: number) => Math.floor(v * 4) / 4; +const clamp = (v: number, lo: number, hi: number) => + Math.max(lo, Math.min(hi, v)); + +/** Body columns 1 to 61. */ +const W = 61; +/** A line's name: columns 3 to 28. */ +const NAME_W = 26; +/** The right end of words in a slab (`STOCK`, `NOTHING DUE`): column 60. */ +const WORD_END = 61; + +/** ` BERTHS` in white, two spaces, the jobs dim, wrapped to at most `max` lines of 61. */ +function crewLines(count: number, jobs: string, max: number) { + const head = `${count} BERTHS`; + // A stand-in word as wide as the head plus one, so the first line keeps two spaces after it. + const lead = 'x'.repeat(head.length + 1); + const all = wrap(jobs ? `${lead} ${jobs}` : lead, W); + const lines = wrapMax(jobs ? `${lead} ${jobs}` : lead, W, max); + return { head, need: all.length, lines }; +} + +export function Bill(props: { ctx: YardCtx }) { + const { ctx } = props; + const { data } = useBackend(); + const { rows } = useGrid(); + const [page, setPage] = useState(1); + // PageUp, PageDown and the mouse wheel turn the lines' pages when they page. + const pager = useLatePager(); + const wheel = useWheel(); + const hull = ctx.hull; + usePreview(hull?.id || null); + const fit = ctx.fit; + const bill = ctx.bill; + if (!hull || !fit || !bill) { + return null; + } + + const M = rows; + const B = bodyRows(M); + const tight = B < 18; + const n = bill.lines.length; + const due = partsOf(bill.total) > 0; + const ledgerOk = ctx.ledger === 'ok'; + const short = ledgerOk && Object.keys(bill.short).length > 0; + const beforeRound = + data.phase === 'loading' || + data.phase === 'pregame' || + data.phase === 'setup'; + const canChange = fittable(hull); + const live = ctx.open && !ctx.sent && !short && (!due || ledgerOk); + + const crew = crewLines(crewCount(fit), safe(crewText(fit)), 2); + const crewL = tight ? 0 : Math.min(2, crew.need); + const tableRows = tight + ? 1 + (due ? 1 : 0) + (short ? 1 : 0) + : 1.5 + (due ? 1 : 0) + (short ? 1.5 : 0); + const fixed = tight + ? 1 + 0.5 + tableRows + 0.25 + 1.5 + : crewL + 0.25 + 1 + 0.25 + 0.75 + tableRows + 0.5 + 2; + const avail = B - fixed; + // Lines that don't fit page; nothing is ever hidden behind "+N MORE". + const per = Math.max(1, Math.min(n, Math.floor(avail))); + const pages = Math.max(1, Math.ceil(n / per)); + const pg = clamp(page, 1, pages); + const shown = bill.lines.slice((pg - 1) * per, pg * per); + const turn = + pages > 1 + ? (step: number) => setPage(clamp(pg + step, 1, pages)) + : null; + pager.current = turn; + // Tight form: pitch 1, stretched to 1.5 when rows are spare so none sit empty. + const pitch = + pages > 1 ? 1 : clamp(f4(avail / n), 1, tight ? 1.5 : 2.25); + const spare = avail - per * pitch; + const pic = !tight && spare >= 6 ? f4(spare - 0.5) : 0; + const out: ReactNode[] = []; + out.push( + , + ); + let y = BODY_Y; - const lw = narrow ? 0 : Math.floor(cols * 0.5); - if (!narrow) { - out.push( - , - ); - const ph = Math.floor(h * 0.55); - out.push( - , - ); - let y = TOP + ph + 1; - out.push(); - y++; - out.push( - - CREW - , - - {String(crewN)} - , - ); - y += 2; - // Two columns only when every job title still fits whole in one; otherwise one column. - const longest = crew.reduce((m, [job]) => Math.max(m, job.length), 0); - const twoColW = Math.floor((lw - 6) / 2); - const columns = twoColW - 5 >= longest ? 2 : 1; - const colW = columns === 2 ? twoColW : lw - 6; - const per = Math.max(1, Math.ceil(crew.length / columns)); - crew.forEach(([job, n], i) => { - const cx = 3 + Math.floor(i / per) * colW; - const cy = y + (i % per); - if (cy >= TOP + h - 1) { - return; - } - out.push( - - {pad(job, colW - 5)} - , - - {lpad(n, 2)} - , - ); - }); + if (pic > 0) { + out.push(); + y += pic + 0.5; } - const x = narrow ? 0 : lw + 1; - const w = cols - x; - out.push(); - let y = TOP + 2; - // Keys on by; the status line two above; the parts table above that; the bill lines on top. - const by = TOP + h - 3; - const short = Object.keys(bill.short).length > 0; - const tableTop = by - (short ? 8 : 7); - const labelW = Math.min(14, Math.max(8, Math.floor(w * 0.25))); - const nameX = x + 3 + labelW + 1; - const lines = bill.lines; - lines.forEach(([label, name, cost], i) => { - const costText = cost ? costOf(cost) || '-' : '-'; - const nameRoom = x + w - 3 - nameX; - // A long price drops to its own row under the name. - const own = nameRoom - (costText.length + 2) < 10; - const need = own ? 2 : 1; - // Rows left above the table, keeping one for "+N MORE" unless this is the last line. - const left = tableTop - 1 - y - (i < lines.length - 1 ? 1 : 0); - if (y < 0 || need > left) { - if (y >= 0) { + if (crewL > 0) { + crew.lines.forEach((line, i) => { + if (i === 0) { out.push( - - {`+${lines.length - i} MORE`} + + {crew.head} + , + + {line.slice(crew.head.length + 2)} + , + ); + } else { + out.push( + + {line} , ); } - y = -1; - return; + }); + y += crewL + 0.25; + } + + // Heads, and the pager when the lines page. + if (due) { + out.push(); + } + out.push( + , + ); + y += tight ? 1 : 1.25; + + // One slab row a line. + shown.forEach((line, j) => { + const ly = y + j * pitch; + const h = pitch >= 1.25 ? pitch - 0.25 : 1; + const ty = ly + (h - 1) / 2; + const odd = ((pg - 1) * per + j) % 2 === 1; + // The name takes the row's free width: up to two cells before its first figure or word. + let start = WORD_END - (line.cost ? 0 : (line.word || '').length); + if (line.cost) { + const i = PART_CLASSES.findIndex((k) => !!fig(line.cost?.[k])); + if (i >= 0) { + start = CLASS_EDGES.R[i] + 1 - fig(line.cost[PART_CLASSES[i]]).length; + } } + const nameW = Math.max(NAME_W, start - 5); out.push( - - {pad(label, labelW)} - , - - {pad( - name, - own ? nameRoom : nameRoom - Math.max(9, costText.length + 2), + + + {cut(safe(line.name).toUpperCase(), nameW)} + + {line.cost ? ( + + ) : ( + + {line.word || ''} + )} + , + ); + }); + // A page of lines turning wipes the lines only. + out.push( + , + ); + y += per * pitch; + + // The rule, then TOTAL, ON ACCOUNT and SHORT under the same columns. + const ruleH = tight ? 0.5 : 0.75; + out.push(); + y += ruleH; + + const rowH = tight ? 1 : 1.5; + const labelY = tight ? y : y + 0.25; + const figY = tight ? y : y + 0.125; + if (due) { + out.push( + + TOTAL , + , ); - if (own) { - y++; - } + } else { out.push( - - {cut(costText, w - 6)} + + TOTAL + , + + NOTHING DUE , ); - y++; - }); + } + y += rowH; - // The parts table: one column per part, so TOTAL, ON ACCOUNT and SHORT line up and never - // run into each other however many parts there are. - out.push(); - const inner = w - 6; - const longLabels = inner >= 11 + 4 * 8; - const rowLabelW = longLabels ? 11 : 6; - const colW = Math.max(4, Math.min(9, Math.floor((inner - rowLabelW) / 4))); - const colX = (j: number) => x + 3 + rowLabelW + j * colW; - const cell = (n: number) => lpad(cut(String(n), colW - 1), colW - 1); - const due = partsOf(bill.total); - PART_ORDER.forEach((k, j) => { - const head = - colW - 1 >= k.length ? k.toUpperCase() : k.slice(0, 3).toUpperCase(); + if (due) { out.push( - - {lpad(head, colW - 1)} - , - 0 ? 'amb' : 'faint'} - > - {cell(bill.total[k] || 0)} - , - - {cell(ctx.account?.[k] || 0)} + + ON ACCOUNT , ); - if (short) { + if (ctx.ledger === 'off') { out.push( - - {bill.short[k] ? cell(bill.short[k] || 0) : lpad('-', colW - 1)} - , + + LEDGER OFFLINE + , + ); + } else if (ledgerOk) { + out.push( + // A balance: an empty class reads 0, as on the shipyard home. + , ); } - }); - out.push( - - TOTAL - , - - {longLabels ? 'ON ACCOUNT' : 'HELD'} - , - ); + y += 1; + } + if (short) { + const sh = tight ? 1 : 1.5; out.push( - + , + SHORT , + , ); + y += sh; } - const confirming = view.confirm === 'commission'; - const blocked = short || !ctx.open; - if (!short && !ctx.open) { + // The keys, and the one line that says why before the round. + const yK = tight ? M - 2.75 : M - 3.25; + const sideY = tight ? yK : yK + 0.5; + if (beforeRound) { out.push( - - {cut('THE YARD OPENS AT DEPARTURE', w - 6)} - , - ); - } else if (!short && ctx.crewChange) { - out.push( - - {pad(`LEAVES ${ctx.crewChange.toUpperCase()}`, w - 6)} + + {YARD_OPENS} , ); } - const commission = () => { - if (ctx.crewChange && !confirming) { - set({ confirm: 'commission' }); - return; - } - const modules: Record = {}; - for (const s of fit.slots) { - if (s.pick) { - modules[s.key] = s.pick.id; - } - } - onCommission({ - hull: hull.id, - finish: fit.finish?.id || '', - modules, - leave_crew: ctx.crewChange ? 1 : 0, - }); - }; - out.push( - , - ); - // A hull with nothing to fit has no CHANGE FIT. - if (fit.hull.finishes.length || fit.hull.slots.length) { + if (canChange) { out.push( set({ screen: 'fit' })} + auto={2} + onClick={() => ctx.go.fit(Math.max(0, stepsOf(fit) - 1))} />, ); } + out.push( + { + const modules: Record = {}; + for (const s of fit.slots) { + if (s.pick) { + modules[s.key] = s.pick.id; + } + } + ctx.found({ + action: 'yard_commission', + params: { + hull: hull.id, + finish: fit.finish?.id || '', + modules, + total: bill.total, + }, + label: 'COMMISSION', + }); + }} + />, + ); - return <>{out}; + return
{out}
; } diff --git a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/BodyEditor.tsx b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/BodyEditor.tsx index 96963c921db..df004bde20a 100644 --- a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/BodyEditor.tsx +++ b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/BodyEditor.tsx @@ -1,24 +1,59 @@ /** - * BODY (CHARACTER-PLAN 2.3/2.4): data-driven rows from CharData.prefs in BODY_KEYS order, char_set, the species confirm line, ColorEntry for free colours. - * Owner: C3. The props are fixed. + * BODY (design 03 section 4): two groups, IDENTITY and LOOKS, in the ID column under the + * viewscreen; the open group's rows in the work column. Rows come from CharData.prefs (the + * server's accessibility rules pick them), in IDENTITY_KEYS / LOOKS_KEYS order. A row opens + * its list picker or colour panel in the work column (level 2), flips a two-way choice, or + * types a number. `<` and `>` on a row are mouse targets; the arrows always move the focus. * - * A row shows only when the server sent its key (its accessibility rules pick the rows); - * species feature keys are also checked against the species' enabled_features in the - * catalog. Rows flow down one column, into a second when the box is too short, and onto - * pages when even that is not enough. Choice lists longer than PICK_OVER open a paged list - * when their value is clicked. + * Every change is a char_set and waits for the push; only typed text and a dragged colour are + * held on the page. */ import { type ReactNode, useEffect, useState } from 'react'; import { useBackend } from 'tgui/backend'; +import type { ServerData } from 'tgui/interfaces/PreferencesMenu/types'; -import { ColorEntry, parseHex } from './ColorEntry'; -import { useBack } from './nav'; -import { Btn, Cycler, Field, Panel, Put, pad, Swatch, wrap } from './term'; +import { + clamp, + ID_W, + ID_X, + IdColumn, + planId, + q, + StepKeys, + useChar, + useLatePager, + useListPager, + useWheel, + WORK_W, + WORK_X, +} from './CharFrame'; +import { ColourPanel, ListPicker } from './CharPickers'; +import { parseHex } from './ColorEntry'; +import { sfx, useChanged } from './motion'; +import { FocusGroup } from './nav'; +import { + Big, + BODY_Y, + bodyRows, + cut, + Field, + FlashAt, + HRule, + Key, + Pager, + Put, + Slab, + Swatch, + safe, + useGrid, + WipeAt, + wrapMax, +} from './term'; import { AGE_MAX, AGE_MIN, - BODY_KEYS, - type CellBox, + IDENTITY_KEYS, + LOOKS_KEYS, type LobbyData, NAME_MAX, NATIVE_COLOR_KEYS, @@ -27,30 +62,28 @@ import { choicesOf, namedHex, nameOf, - stepChoice, usePrefsCatalog, + voiceShort, } from './usePrefsCatalog'; +export type BodyGroup = 'identity' | 'looks'; + const LABELS: Record = { - real_name: 'NAME', age: 'AGE', species: 'SPECIES', - body_type: 'BODY', + body_type: 'BUILD', gender: 'PRONOUNS', background: 'BACKGROUND', + voice_pack: 'VOICE', + bark_speech_pitch: 'PITCH', + bark_speech_speed: 'SPEED', skin_tone: 'SKIN', hairstyle_name: 'HAIR', - hair_color: 'HAIR', hair_gradient: 'GRADIENT', - hair_gradient_color: 'GRADIENT', - facial_style_name: 'FACIAL HAIR', - facial_hair_color: 'FACIAL HAIR', + facial_style_name: 'FACIAL', feature_mcolor: 'SCALES', feature_ethcolor: 'GLOW', eye_color: 'EYES', - voice_pack: 'VOICE', - bark_speech_pitch: 'PITCH', - bark_speech_speed: 'SPEED', backpack: 'BAG', jumpsuit_style: 'UNIFORM', underwear: 'UNDERWEAR', @@ -70,85 +103,100 @@ const LABELS: Record = { feature_moth_markings: 'MARKINGS', }; -/** Species feature rows, in this order after SCALES; unknown ones follow, by key. */ -const FEATURE_ORDER = [ - 'feature_human_ears', - 'feature_human_tail', - 'feature_lizard_snout', - 'feature_lizard_horns', - 'feature_lizard_frills', - 'feature_lizard_spines', - 'feature_lizard_body_markings', - 'feature_lizard_legs', - 'feature_lizard_tail', - 'feature_moth_wings', - 'feature_moth_antennae', - 'feature_moth_markings', -]; - -/** Colours drawn on their style's row. */ -const PAIRED: Record = { - hairstyle_name: 'hair_color', - hair_gradient: 'hair_gradient_color', - facial_style_name: 'facial_hair_color', - underwear: 'underwear_color', +/** Colour rows that sit under their style (labelled COLOUR, indented). */ +const PAIRED = new Set([ + 'hair_color', + 'hair_gradient_color', + 'facial_hair_color', + 'underwear_color', +]); + +/** The colour panel's head (and crumb) for each body colour. */ +const COLOUR_LABELS: Record = { + hair_color: 'HAIR COLOUR', + hair_gradient_color: 'GRADIENT COLOUR', + facial_hair_color: 'FACIAL COLOUR', + underwear_color: 'UNDERWEAR COLOUR', + eye_color: 'EYES', + feature_mcolor: 'SCALES', }; -/** Named lists that show a swatch per choice. */ +/** Named-colour lists that show a chip per choice. */ const PALETTES = new Set(['skin_tone', 'feature_ethcolor']); -/** Numeric rows and the amount one click moves them. */ -const NUMERIC_STEPS: Record = { - bark_speech_pitch: 0.1, - bark_speech_speed: 0.5, +/** Typed numbers: range and the step of `<` `>`. */ +const NUMBERS: Record = { + age: { lo: AGE_MIN, hi: AGE_MAX, step: 1 }, + bark_speech_pitch: { lo: 0.4, hi: 2, step: 0.1 }, + bark_speech_speed: { lo: 4, hi: 16, step: 0.5 }, }; -/** Lists longer than this open the paged list when the value is clicked. */ -const PICK_OVER = 12; -/** Label column width. */ -const LW = 12; - -const labelOf = (key: string) => +export const labelOf = (key: string) => LABELS[key] || - key - .replace(/^feature_/, '') - .replace(/_/g, ' ') - .toUpperCase(); - -type Row = { - key: string; - h: number; - draw: (L: number, V: number, y: number, end: number) => ReactNode; -}; - -export function BodyEditor(props: CellBox) { - const { x, y, w, h } = props; - const { act, data } = useBackend(); - const cat = usePrefsCatalog(); - const char = data.char; - const prefs = char?.prefs || {}; - const [name, setName] = useState(String(prefs.real_name ?? '')); - const [page, setPage] = useState(0); - const [picker, setPicker] = useState(null); - - useEffect(() => { - setName(String(prefs.real_name ?? '')); - }, [prefs.real_name, char?.slot]); + COLOUR_LABELS[key] || + cut( + key + .replace(/^feature_/, '') + .replace(/_/g, ' ') + .toUpperCase(), + 10, + ); - if (!char) { - return null; +type Kind = + | 'name' + | 'number' + | 'species' + | 'build' + | 'voice' + | 'palette' + | 'colour' + | 'list' + | 'flip' + | 'fixed'; + +/** How a row behaves, from its key and the catalog. Null: no row. */ +function kindOf( + cat: ServerData | null, + key: string, + value: unknown, +): Kind | null { + if (key === 'real_name') { + return 'name'; } - - const set = (key: string, value: unknown) => act('char_set', { key, value }); - const commitName = () => { - const next = name.trim(); - if (next && next !== prefs.real_name) { - set('real_name', next); - } else { - setName(String(prefs.real_name ?? '')); + if (key in NUMBERS) { + return 'number'; + } + if (key === 'species') { + return 'species'; + } + if (key === 'body_type') { + return 'build'; + } + if (key === 'voice_pack') { + return 'voice'; + } + const list = choicesOf(cat, key); + if (list) { + if (PALETTES.has(key)) { + return 'palette'; } - }; + return list.length >= 3 ? 'list' : list.length === 2 ? 'flip' : 'fixed'; + } + if (parseHex(String(value ?? ''))) { + return 'colour'; + } + // A key the catalog doesn't describe (a new preference): its value, read only. + return typeof value === 'string' || typeof value === 'number' + ? 'fixed' + : null; +} +/** The keys of a group that show for this character, in order. */ +export function groupKeys( + cat: ServerData | null, + prefs: Record, + group: BodyGroup, +): string[] { const species = String(prefs.species ?? ''); const enabled = cat?.species?.[species]?.enabled_features; const shown = (k: string) => @@ -156,575 +204,820 @@ export function BodyEditor(props: CellBox) { (!k.startsWith('feature_') || !Array.isArray(enabled) || enabled.includes(k)); - const isColour = (k: string) => - !choicesOf(cat, k) && !!parseHex(String(prefs[k] ?? '')); + const named = new Set([...IDENTITY_KEYS, ...LOOKS_KEYS]); + const extra = Object.keys(prefs) + .filter((k) => k.startsWith('feature_') && !named.has(k)) + .sort(); + const order: string[] = + group === 'identity' + ? [...IDENTITY_KEYS] + : LOOKS_KEYS.flatMap((k) => (k === '@features' ? extra : [k])); + const bald = prefs.hairstyle_name === 'Bald'; + const hidden = (k: string) => + (bald && + (k === 'hair_color' || + k === 'hair_gradient' || + k === 'hair_gradient_color')) || + (k === 'hair_gradient_color' && prefs.hair_gradient === 'None') || + (k === 'facial_hair_color' && prefs.facial_style_name === 'Shaved') || + (k === 'underwear_color' && prefs.underwear === 'Nude'); + return order.filter( + (k) => shown(k) && !hidden(k) && kindOf(cat, k, prefs[k]) !== null, + ); +} - // Every colour on this file, offered in the colour panel's recent row. - const fileColours = [ - ...Object.values(prefs), +/** Every colour on this file (body and kit), for the colour panel's recent chips. */ +export function fileColours(char: LobbyData['char']): string[] { + if (!char) { + return []; + } + return [ + ...Object.values(char.prefs), ...Object.values(char.kit || {}).flatMap((it) => String(it.greyscale || '').split('#'), ), ] .map((c) => parseHex(String(c))) .filter((c): c is string => !!c); +} - const colour = (key: string, cx: number, cy: number, end: number) => ( - set(key, hex)} - onPicker={() => act('char_color_pick', { key })} - /> - ); - - /** Cycler width for a row whose controls start at V and must end by end. */ - const widthFor = (V: number, end: number, extra: number) => - Math.max(6, Math.min(20, end - V - 4 - extra)); - - const choiceRow = (key: string): Row => { - const list = choicesOf(cat, key); - const value = prefs[key]; - const pair = PAIRED[key] && shown(PAIRED[key]) ? PAIRED[key] : null; - const palette = PALETTES.has(key) && list ? sortPalette(key, list) : null; - let shownValue = nameOf(cat, key, value); - if (key === 'voice_pack') { - // "Group: Name" in the list; the row shows the name. - shownValue = shownValue.split(': ').pop() || shownValue; - } - let prev = () => list && set(key, stepChoice(list, value, -1)); - let next = () => list && set(key, stepChoice(list, value, 1)); - if (key === 'body_type') { - const fem = - value === 'female' || (value !== 'male' && prefs.gender === 'female'); - shownValue = fem ? 'Feminine' : 'Masculine'; - prev = () => set(key, fem ? 'male' : 'female'); - next = prev; - } - const long = !!list && list.length > PICK_OVER; - return { - key, - // A palette that can't sit beside the cycler gets more rows (heightOf). - h: 1, - draw: (L, V, ry, end) => { - let VW = widthFor(V, end, pair ? 11 : key === 'voice_pack' ? 9 : 0); - if (pair && VW < 12) { - VW = widthFor(V, end, 3); - } - const after = V + VW + 5; - const out: ReactNode[] = [ - - {labelOf(key)} - , - setPicker(key) : undefined} - />, - ]; - if (pair) { - out.push(colour(pair, after, ry, end)); - } - if (key === 'voice_pack' && after + 8 <= end) { - out.push( - act('char_voice_play')} - />, - ); - } - if (palette) { - out.push(...paletteChips(key, palette, after, ry, end, V)); - } - return out; - }, - }; - }; - - /** Skin tones light to dark; other palettes in the server's order. */ - const sortPalette = (key: string, list: string[]) => { - if (key !== 'skin_tone') { - return list; - } - const luma = (c: string) => { - const n = parseInt((namedHex(cat, key, c) || '#000000').slice(1), 16); - return 0.3 * (n >> 16) + 0.59 * ((n >> 8) & 255) + 0.11 * (n & 255); - }; - return [...list].sort((a, b) => luma(b) - luma(a)); - }; - - /** Swatches for a named-colour list: beside the cycler when they fit, else one more row. */ - const paletteChips = ( - key: string, - list: string[], - after: number, - ry: number, - end: number, - V: number, - ) => { - const beside = after + list.length * 2 <= end; - const per = Math.max(1, Math.floor((end - V) / 2)); - return list.map((c, i) => { - const hex = namedHex(cat, key, c) || '#000000'; - const sx = beside ? after + i * 2 : V + (i % per) * 2; - const sy = beside ? ry : ry + 1 + Math.floor(i / per); - return ( - set(key, c)} - /> - ); - }); +/** Skin tones light to dark; other palettes in the server's order. */ +function sortPalette(cat: ServerData | null, key: string, list: string[]) { + if (key !== 'skin_tone') { + return list; + } + const luma = (c: string) => { + const n = parseInt((namedHex(cat, key, c) || '#000000').slice(1), 16); + return 0.3 * (n >> 16) + 0.59 * ((n >> 8) & 255) + 0.11 * (n & 255); }; + return [...list].sort((a, b) => luma(b) - luma(a)); +} - /** A numeric preference (bark pitch, speed): steps within the catalog's range. */ - const numberRow = (key: string): Row => { - const spec = (cat?.[key] || {}) as { minimum?: number; maximum?: number }; - const step = NUMERIC_STEPS[key]; - const lo = spec.minimum ?? 0; - const hi = spec.maximum ?? lo + step * 20; - const value = Number(prefs[key]) || lo; - const to = (v: number) => - set(key, Math.round(Math.min(hi, Math.max(lo, v)) * 100) / 100); - const text = value.toFixed(1); - return { - key, - h: 1, - draw: (L, V, ry) => [ - - {labelOf(key)} - , - value > lo && to(value - step)} - onNext={() => value < hi && to(value + step)} - />, - ], - }; - }; +/** What BUILD shows: "Use gender" resolves to the build it gives. */ +function buildFem(prefs: Record) { + const v = prefs.body_type; + return v === 'female' || (v !== 'male' && prefs.gender === 'female'); +} - const colourRow = (key: string): Row => ({ - key, - h: 1, - draw: (L, V, ry, end) => [ - - {labelOf(key)} - , - colour(key, V, ry, end), - ], - }); +// --------------------------------------------------------------------------- +// Level 2 screens. Each reads live data, so the frame can keep the element as it was opened. - // ---- the rows, top to bottom - const extraFeatures = Object.keys(prefs) - .filter( - (k) => - k.startsWith('feature_') && - !(BODY_KEYS as readonly string[]).includes(k), - ) - .sort((a, b) => { - const ia = FEATURE_ORDER.indexOf(a); - const ib = FEATURE_ORDER.indexOf(b); - if (ia < 0 && ib < 0) { - return a < b ? -1 : 1; - } - return (ia < 0 ? 99 : ia) - (ib < 0 ? 99 : ib); - }); - const order: string[] = []; - for (const k of BODY_KEYS) { - if (k === 'real_name') { - continue; - } - if (k === 'voice_pack' && species === 'plasmaman') { - order.push('@suit'); - } - order.push(k); - if (k === 'feature_mcolor') { - order.push(...extraFeatures); +/** A list picker on a BODY key. Closes when its row goes away (species changed in tg's window). */ +export function BodyListPick(props: { k: string }) { + const { k } = props; + const { act, data } = useBackend(); + const cat = usePrefsCatalog(); + const { closeSub } = useChar(); + const prefs = data.char?.prefs || {}; + const gone = !(k in prefs); + useEffect(() => { + if (gone) { + closeSub(); } - } - const pairedShown = new Set( - Object.entries(PAIRED) - .filter(([style]) => shown(style)) - .map(([, c]) => c), + }, [gone]); + const list = choicesOf(cat, k) || []; + const palette = PALETTES.has(k); + return ( + nameOf(cat, k, v)} + hexOf={palette ? (v) => namedHex(cat, k, v) : undefined} + onPick={(v) => { + if (v !== String(prefs[k] ?? '')) { + act('char_set', { key: k, value: v }); + } + // A voice plays as it is picked (picking the current one plays it again). + if (k === VOICE_KEY) { + act('char_voice_play'); + } + }} + onClose={closeSub} + /> ); +} - const rows: Row[] = []; - for (const k of order) { - if (k === '@suit') { - rows.push({ - key: k, - h: 1, - draw: (L, V, ry) => [ - - {'SUIT'} - , - - {'ENVIROSUIT'} - , - ], - }); - continue; - } - if (!shown(k) || pairedShown.has(k)) { - continue; - } - if (k === 'age') { - const age = Number(prefs.age) || AGE_MIN; - rows.push({ - key: k, - h: 1, - draw: (L, V, ry) => [ - - {'AGE'} - , - age > AGE_MIN && set('age', age - 1)} - onNext={() => age < AGE_MAX && set('age', age + 1)} - />, - ], - }); - continue; - } - if (k in NUMERIC_STEPS) { - rows.push(numberRow(k)); - continue; - } - const row = isColour(k) ? colourRow(k) : choiceRow(k); - rows.push(row); - if (k === 'species' && char.confirm) { - rows.push(confirmRow()); - } - } - - function confirmRow(): Row { - const c = char!.confirm!; - const text = `${nameOf(cat, 'species', c.value)} can't keep: ${c.quirks.join(', ')}`; - return { - key: '@confirm', - h: 0, // set when laid out (depends on the column width) - draw: (L, _V, ry, end) => { - const lines = wrap(text.toUpperCase(), Math.max(10, end - L)); - return [ - ...lines.map((l, i) => ( - - {l} - - )), - act('char_confirm', { ok: 1 })} - />, - act('char_confirm', { ok: 0 })} - />, - ]; - }, - }; - } - - // ---- layout: one column, two, or pages - const nameY = y + 1; - const flowTop = nameY + (h >= 20 ? 2 : 1); - const last = y + h - 2; - const L0 = x + 3; +/** The voice pack preference: picking or stepping it plays the voice. */ +const VOICE_KEY = 'voice_pack'; - const heightOf = (r: Row, colEnd: number, L: number, V: number) => { - if (r.key === '@confirm') { - return ( - wrap( - `${nameOf(cat, 'species', char.confirm?.value)} can't keep: ${char.confirm?.quirks.join(', ')}`, - Math.max(10, colEnd - L), - ).length + 1 - ); - } - if (PALETTES.has(r.key)) { - const list = choicesOf(cat, r.key); - if (list) { - const VW = widthFor(V, colEnd, 0); - const after = V + VW + 5; - if (after + list.length * 2 > colEnd) { - const per = Math.max(1, Math.floor((colEnd - V) / 2)); - return 1 + Math.ceil(list.length / per); - } - } +/** The colour panel on a BODY colour key. */ +export function BodyColour(props: { k: string }) { + const { k } = props; + const { act, data } = useBackend(); + const { closeSub } = useChar(); + const char = data.char; + const prefs = char?.prefs || {}; + const gone = !(k in prefs); + useEffect(() => { + if (gone) { + closeSub(); } - return r.h; - }; + }, [gone]); + return ( + act('char_set', { key: k, value: hex })} + onPicker={() => act('char_color_pick', { key: k })} + onClose={closeSub} + /> + ); +} - type Placed = { row: Row; L: number; V: number; y: number; end: number }; - const layout = (ncol: number, cap: number): Placed[][] => { - const colW = Math.floor((w - 2) / ncol); - const pages: Placed[][] = [[]]; - let col = 0; - let yy = flowTop; - for (const r of rows) { - const L = L0 + col * colW; - const end = x + (col + 1) * colW - 1; - const rh = heightOf(r, end, L, L + LW); - if (yy + rh - 1 > flowTop + cap - 1 && yy > flowTop) { - col++; - yy = flowTop; - if (col >= ncol) { - col = 0; - pages.push([]); - } - } - const L2 = L0 + col * colW; - const end2 = x + (col + 1) * colW - 1; - pages[pages.length - 1].push({ - row: r, - L: L2, - V: L2 + LW, - y: yy, - end: end2, +/** The species picker (design 03 section 4.6): one column, the focused species' description. */ +export function SpeciesPick() { + const { act, data } = useBackend(); + const cat = usePrefsCatalog(); + const { rows: M } = useGrid(); + const value = String(data.char?.prefs.species ?? ''); + const list = choicesOf(cat, 'species') || []; + const [over, setOver] = useState(value); + const B = bodyRows(M); + // Rows stretch into the room the longest description leaves (at most 7 lines), so a tall + // pane fills instead of leaving the foot empty; short panes keep 1.25-row rows. + const longest = Math.max( + 2, + ...list.map( + (id) => + wrapMax(safe(String(cat?.species?.[id]?.desc ?? '')), WORK_W, 7).length, + ), + ); + const rowsRoom = M - 1.25 - 5.25 - 0.75 - longest; + const h = + B < 20 + ? 1.25 + : clamp(q((rowsRoom + 0.25) / Math.max(1, list.length) - 0.25), 1.5, 3); + const pitch = B < 20 ? 1.25 : h + 0.25; + // Rows that leave at least two lines of description under them. + const room = Math.floor((M - 1.25 - 2 - 0.75 - 5.25 + (pitch - h)) / pitch); + const fits = list.length <= room; + const per = Math.max( + 1, + fits + ? list.length + : Math.floor((M - 1.25 - 2 - 0.75 - 5.25 - 1.25 + (pitch - h)) / pitch), + ); + const pages = Math.max(1, Math.ceil(list.length / per)); + const [page, setPage] = useState(() => + Math.max(0, Math.floor(list.indexOf(value) / per)), + ); + const pg = Math.min(page, pages - 1); + useListPager(pg, pages, setPage); + const wheel = useWheel(); + const slice = list.slice(pg * per, pg * per + per); + const step = (by: number) => { + const n = list.length; + const at = list.indexOf(value); + if (n) { + act('char_set', { + key: 'species', + value: list[(((at < 0 ? 0 : at + by) % n) + n) % n], }); - yy += rh; } - return pages; }; - const cap = last - flowTop + 1; - let pages = layout(1, cap); - if (pages.length > 1 && w >= 64) { - pages = layout(2, cap); - } - if (pages.length > 1) { - pages = layout(w >= 64 ? 2 : 1, cap - 1); - } - const pg = Math.min(page, pages.length - 1); - - // ---- NAME, across the top - const V0 = L0 + LW; - const fw = Math.max(8, Math.min(24, x + w - V0 - 16)); - const nameRow = ( -
- - {'NAME'} - - 1 ? 1.25 : 0)); + const desc = safe(String(cat?.species?.[over]?.desc ?? '')); + return ( + // The mouse wheel turns the pages, one a notch. +
1 ? (by) => setPage(clamp(pg + by, 0, pages - 1)) : null, + )} + > + + {'SPECIES'} + + step(-1)} /> - act('char_random_name')} + step(1)} /> + + {slice.map((id, i) => { + const y = 5.25 + i * pitch; + const on = id === value; + return ( + f && setOver(id)} + onClick={() => act('char_set', { key: 'species', value: id })} + > + {h >= 2.25 ? ( + + {cut(safe(nameOf(cat, 'species', id)).toUpperCase(), 28)} + + ) : ( + + {cut(safe(nameOf(cat, 'species', id)).toUpperCase(), 36)} + + )} + + ); + })} + {wrapMax(desc, WORK_W, Math.max(0, descRows)).map((line, i) => ( + + {line} + + ))} + setPage(p - 1)} + right + /> + + {!list.length && ( + + {'NO MATCH.'} + + )}
); +} +// --------------------------------------------------------------------------- +// Rows + +/** One BODY row: the slab, its label, the value and the mouse-only `<` `>`. */ +function Row(props: { + y: number; + h: number; + alt: boolean; + label: string; + paired?: boolean; + /** Enter or a click on the row; null: the row is not a focus stop (a typed number). */ + onPress: (() => void) | null; + onStep?: (by: number) => void; + /** A number at its low or high end: that arrow is faint and inert. */ + ends?: [boolean, boolean]; + auto?: number; + /** Draws the value; ty = the text row (centred), by = the 1.25 Big row. */ + value: (ty: number, by: number, focused: boolean) => ReactNode; +}) { + const { y, h, alt, label, paired, onPress, onStep, ends, auto, value } = + props; + const [focused, setFocused] = useState(false); + const ty = y + (h - 1) / 2; + const by = y + (h - 1.25) / 2; return ( - <> - {nameRow} - {pages[pg].map((p) => ( - {p.row.draw(p.L, p.V, p.y, p.end)} - ))} - {pages.length > 1 && ( - - )} - {!!picker && ( - nameOf(cat, picker, v)} - onPick={(v) => { - setPicker(null); - if (v !== prefs[picker]) { - set(picker, v); - } - }} - onClose={() => setPicker(null)} - /> + + + {cut(label, paired ? 8 : 10)} + + {value(ty, by, focused)} + {!!onStep && ( + )} - + ); } -/** ` < ` n/m ` > `, ending just before column x. */ -function Pager(props: { +/** A row's value as text: Big when the row is tall and the text short. */ +function ValueText(props: { x: number; + w: number; + h: number; + ty: number; + by: number; + text: string; + cls?: string; + /** The page's value size (BodyEditor `big`); else the row decides alone. */ + big?: boolean; +}) { + const { x, w, h, ty, by, text, cls = '', big } = props; + // The value flashes when it changes, whoever changed it (this page or tg's own window). + if ((big ?? h >= 2.25) && text.length <= 15 && text.length * 1.25 <= w) { + return ( + + {text} + + ); + } + return ( + + {cut(text, w)} + + ); +} + +/** A typed number (AGE, PITCH, SPEED): digits and one dot; Enter submits, leaving restores. */ +function NumberField(props: { + k: string; y: number; - page: number; - pages: number; - onPage: (p: number) => void; + h: number; + value: number; + big?: boolean; + onSet: (v: number) => void; }) { - const { x, y, page, pages, onPage } = props; - const label = `${page + 1}/${pages}`; - const px = x - 8 - label.length; + const { k, y, h, value, big, onSet } = props; + const spec = NUMBERS[k]; + const shown = k === 'age' ? String(Math.round(value)) : value.toFixed(1); + const [text, setText] = useState(shown); + useEffect(() => setText(shown), [shown]); + const fh = Math.min(1.5, h); + return ( +
setText(shown)}> + { + const clean = v.replace(/[^0-9.]/g, ''); + const dot = clean.indexOf('.'); + setText( + dot < 0 + ? clean + : clean.slice(0, dot + 1) + + clean.slice(dot + 1).replace(/\./g, ''), + ); + }} + onEnter={() => { + const n = Number(text); + if (!text || !Number.isFinite(n)) { + setText(shown); + return; + } + const stepped = Math.round(n / spec.step) * spec.step; + const v = clamp(Math.round(stepped * 100) / 100, spec.lo, spec.hi); + setText(k === 'age' ? String(v) : v.toFixed(1)); + if (v !== value) { + onSet(v); + } + }} + /> +
+ ); +} + +/** The NAME row: a 3-row slab with [ RANDOM ] and the name field. */ +function NameRow(props: { auto?: number }) { + const { act, data } = useBackend(); + const real = String(data.char?.prefs.real_name ?? ''); + const slot = data.char?.slot; + const [text, setText] = useState(real); + const [typing, setTyping] = useState(false); + // A push sets the field unless the player is typing in it; a slot change always does. + useEffect(() => { + if (!typing) { + setText(real); + } + }, [real]); + useEffect(() => { + setText(real); + }, [slot]); + // The name was accepted (typed here, RANDOM, or tg's window): the field's band flashes once. + const [accepted, setAccepted] = useState(0); + useChanged(`${slot}|${real}`, (was) => { + if (was.split('|')[0] === String(slot)) { + setAccepted((n) => n + 1); + sfx('ok', { own: true }); + } + }); + const commit = () => { + const next = text.trim(); + if (next && next !== real) { + act('char_set', { key: 'real_name', value: next }); + } else { + setText(real); + } + }; + const y = BODY_Y; return ( <> - {page > 0 ? ( - onPage(page - 1)}> - {' < '} - - ) : ( - - {' < '} - - )} - - {label} + + + {'NAME'} - {page < pages - 1 ? ( - onPage(page + 1)} - > - {' > '} - - ) : ( - - {' > '} - - )} + act('char_random_name')} + /> +
setTyping(true)} + onBlur={() => { + setTyping(false); + commit(); + }} + > + +
+ ); } -/** - * The long-list picker (hairstyles and the like): a panel over the editor with a FIND field, - * the choices in columns, paged, the current one lit. Click picks; Escape or CANCEL closes. - */ -function ListPicker(props: { - box: CellBox; - title: string; - list: string[]; - value: string; - nameOf: (v: string) => string; - onPick: (v: string) => void; - onClose: () => void; +export function BodyEditor(props: { + group: BodyGroup; + setGroup: (g: BodyGroup) => void; }) { - const { box, title, list, value, nameOf: show, onPick, onClose } = props; - const px = box.x + 2; - const py = box.y; - const pw = Math.max(20, box.w - 4); - const ph = Math.max(8, box.h - 1); - const colW = Math.min(28, pw - 6); - const ncol = Math.max(1, Math.floor((pw - 4) / (colW + 2))); - const listTop = py + 4; - const listRows = Math.max(1, py + ph - 3 - listTop); - const per = listRows * ncol; + const { group, setGroup } = props; + const { act, data } = useBackend(); + const cat = usePrefsCatalog(); + const { sub, subOpen, closeSub, from, quiet } = useChar(); + const { rows: M } = useGrid(); + const char = data.char!; + const prefs = char.prefs; + // First focus: NAME when BODY opens; a row coming back from its picker; nothing on a group switch. + const [fresh, setFresh] = useState(true); + const [page, setPage] = useState(0); + // PageUp and PageDown turn the rows' pages (set below, once the pages are known). + const pager = useLatePager(); + const wheel = useWheel(); - const [find, setFind] = useState(''); - const [page, setPage] = useState(() => - Math.max(0, Math.floor(list.indexOf(value) / per)), - ); + const set = (key: string, value: unknown) => act('char_set', { key, value }); + // The species changed, with or without the dialog. + useChanged(String(prefs.species ?? ''), () => sfx('ok', { own: true })); + + // ---- ID column: the two group slabs + let gh = 1.25; + const plan = planId(M, 2.75, (la) => { + gh = clamp(q((la + 0.25) / 2 - 0.25), 1.25, 4.5); + return 2 * gh + 0.25; + }); + const groups: [BodyGroup, string][] = [ + ['identity', 'IDENTITY'], + ['looks', 'LOOKS'], + ]; + const idList = groups.map(([g, label], i) => { + const y = plan.top + i * (gh + 0.25); + return ( + { + // A group press leaves an open picker or colour panel. + if (subOpen) { + closeSub(); + } + if (g !== group) { + setFresh(false); + setPage(0); + setGroup(g); + } + }} + > + + {label} + + + ); + }); - useBack(onClose); + if (subOpen) { + pager.current = null; + return ( + + {idList} + + ); + } - const needle = find.trim().toLowerCase(); - const shown = needle - ? list.filter((v) => show(v).toLowerCase().includes(needle)) - : list; - const pages = Math.max(1, Math.ceil(shown.length / per)); - const pg = Math.min(page, pages - 1); - const slice = shown.slice(pg * per, (pg + 1) * per); + // ---- work column: the rows + const B = bodyRows(M); + const keys = groupKeys(cat, prefs, group).filter((k) => k !== 'real_name'); + const fixed = group === 'identity' ? 3.25 : 0; + const room = B - fixed; + const n = Math.max(1, keys.length); + let h = clamp(q((room + 0.25) / n - 0.25), 1.25, 4.5); + let pitch = h + 0.25; + let alt = false; + if (n * pitch - 0.25 > room + 1e-6) { + h = 1.25; + pitch = 1.25; + alt = true; + } + let per = n; + if (n * 1.25 > room + 1e-6) { + per = Math.max(1, Math.floor((room - 1.25) / 1.25)); + } + const pages = Math.ceil(keys.length / per); + const pg = Math.min(page, Math.max(0, pages - 1)); + const turnTo = (p: number) => { + setFresh(false); + setPage(clamp(p, 0, pages - 1)); + }; + const turn = pages > 1 ? (by: number) => turnTo(pg + by) : null; + pager.current = turn; + const shownKeys = keys.slice(pg * per, pg * per + per); + const y0 = BODY_Y + fixed; + // One value size for the page: 1.25x when the rows are tall and every value fits it whole, + // else every value at normal size. + const fits = (s: string, w: number) => s.length <= 15 && s.length * 1.25 <= w; + const big = + h >= 2.25 && + shownKeys.every((k) => { + const v = prefs[k]; + switch (kindOf(cat, k, v)) { + case 'number': + case 'build': + case 'colour': + return true; + case 'voice': + return fits(safe(voiceShort(nameOf(cat, k, v))), 10); + case 'palette': + return fits(safe(nameOf(cat, k, v)), 16); + default: + return fits(safe(nameOf(cat, k, v)), 19); + } + }); - return ( - - - {'FIND'} - - { - setFind(v); - setPage(0); - }} - onEnter={() => slice.length === 1 && onPick(slice[0])} - /> - {slice.map((v, i) => { - const cx = px + 3 + Math.floor(i / listRows) * (colW + 2); - const cy = listTop + (i % listRows); - const cur = v === value; + const rows = shownKeys.map((k, i) => { + const y = y0 + i * pitch; + const value = prefs[k]; + const kind = kindOf(cat, k, value)!; + const label = PAIRED.has(k) ? 'COLOUR' : labelOf(k); + const list = choicesOf(cat, k) || []; + const step = (by: number) => { + if (list.length) { + const at = list.indexOf(String(value)); + const nn = list.length; + set(k, list[(((at < 0 ? 0 : at + by) % nn) + nn) % nn]); + } + }; + const auto = !quiet && from === k ? 5 : undefined; + const common = { + y, + h, + alt: alt && i % 2 === 1, + label, + paired: PAIRED.has(k), + auto, + }; + const text = (s: string) => (ty: number, by: number) => ( + + ); + switch (kind) { + case 'number': { + const spec = NUMBERS[k]; + const v = Number(value) || spec.lo; return ( - onPick(v)} - auto={cur ? 1 : undefined} - > - {pad(show(v).toUpperCase(), colW)} - + = spec.hi]} + onStep={(by) => { + const next = clamp( + Math.round((v + by * spec.step) * 100) / 100, + spec.lo, + spec.hi, + ); + if (next !== v) { + set(k, next); + } + }} + value={() => ( + set(k, nv)} + /> + )} + /> ); - })} - {!slice.length && ( - - {'NO MATCH'} - - )} + } + case 'species': + return ( + sub(, 'SPECIES', k)} + onStep={step} + value={text(nameOf(cat, k, value))} + /> + ); + case 'build': { + const fem = buildFem(prefs); + const flip = () => set(k, fem ? 'male' : 'female'); + return ( + + ); + } + case 'voice': + return ( + sub(, label, k)} + onStep={(by) => { + step(by); + act('char_voice_play'); + }} + value={(ty, by) => ( + + )} + /> + ); + case 'palette': { + const hex = namedHex(cat, k, value) || '#000000'; + return ( + sub(, label, k)} + onStep={(by) => { + const sorted = sortPalette(cat, k, list); + const at = sorted.indexOf(String(value)); + const nn = sorted.length; + if (nn) { + set(k, sorted[(((at < 0 ? 0 : at + by) % nn) + nn) % nn]); + } + }} + value={(ty, by) => ( + <> + + + + )} + /> + ); + } + case 'colour': { + const hex = parseHex(String(value)) || '#000000'; + return ( + sub(, labelOf(k), k)} + value={(ty, by) => ( + <> + + + + )} + /> + ); + } + case 'list': + return ( + sub(, label, k)} + onStep={step} + value={text(nameOf(cat, k, value))} + /> + ); + case 'flip': + return ( + step(1)} + onStep={step} + value={text(nameOf(cat, k, value))} + /> + ); + default: + return ( + + ); + } + }); + + return ( + <> + + {idList} + + + {group === 'identity' && ( + + )} + {/* The mouse wheel turns the rows' pages, one a notch. */} +
{rows}
+
- turnTo(p - 1)} right - onClick={onClose} /> -
+ {/* The other group, or another page of rows, turns the page of the rows only. */} + 1 ? 1.25 : 0)} + k={`${group}:${pg}`} + n={(group === 'looks' ? 1000 : 0) + pg} + /> + ); } diff --git a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/Boot.tsx b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/Boot.tsx new file mode 100644 index 00000000000..4fcdb78085b --- /dev/null +++ b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/Boot.tsx @@ -0,0 +1,587 @@ +/** + * The terminal's start-up screen: the tube powers on, the Voidcrew symbol assembles, the name + * types out, a bar fills, and a LOGIN button waits for the player. Shown once per connection + * (data.boot, lobby_bezel.dm); LOGIN tells the server it has been seen. + * + * While it waits in the dark for its sounds and its font (a first connection), one dim block + * cursor blinks at the top left of the glass, so the tube reads as alive; it goes the instant + * the power-on line appears. + * + * Mount it inside the screen glass. It fills its parent and sizes itself from the glass rect + * alone, so the frame around it can change freely. It sits at z-index 20 in the glass's + * stacking order, above everything the terminal draws. Its children are drawn over it: pass + * the tube's scanline and glass layers when they sit lower than that, or it would hide them. + * While it is up it owns the keyboard (lockNav) and a clear sheet over the whole page keeps + * the mouse off the lobby underneath. + * + * It can never hold a player out of the lobby: with no sound it plays silent, and if anything + * throws it steps aside. + */ +import { + Component, + type ReactNode, + useEffect, + useLayoutEffect, + useRef, + useState, +} from 'react'; +import { createPortal } from 'react-dom'; +import { useBackend } from 'tgui/backend'; + +import { audioState, isLoaded, play, preload, stop, unload } from './audio'; +import { renderEmblem } from './emblemDraw'; +import { preloadSfx } from './motion'; +import { lockNav } from './nav'; +import type { LobbyData } from './types'; + +// --------------------------------------------------------------------------- +// Timeline. Seconds from the moment the power-on line appears. +// --------------------------------------------------------------------------- + +const FPS = 24; +/** Sounds are scheduled this far ahead and the picture waits as long, so no sound loses its first instant. */ +const LEAD = 0.1; +/** The power-on line holds, then collapses to the centre. */ +const LINE_HOLD = 0.25; +const LINE_END = 0.45; +/** The disc grows in. */ +const DISC_AT = 0.45; +const DISC_TIME = 1.1; +/** The V appears, spinning, and comes to rest at LOCK_AT. */ +const V_AT = 0.9; +const V_TURNS = 5; +const LOCK_AT = 3.2; +const FLASH_TIME = 0.12; +/** The tick ring and the three arcs sweep in. */ +const HUD_AT = 1.0; +const HUD_TIME = 1.2; +/** One letter of the name, and one block of the bar, every STEP. */ +const STEP = 0.09; +const NAME = 'VOIDCREW'; +const BAR_SHOWN_AT = 3.4; +const BAR_AT = 4.0; +const BLOCKS = 16; +const DONE_AT = 5.56; +const LOGIN_AT = 5.7; +/** After LOGIN: a beat, then the fade to the lobby. */ +const FADE_HOLD = 0.15; +const FADE_TIME = 0.45; + +/** Canvas the symbol and its start-up rings are drawn in, in art pixels, and the symbol's scale in it. */ +const CANVAS = 190; +const CANVAS_K = 1.45; + +const SND_POWER = 'lt_boot_power.ogg'; +const SND_SEQ = 'lt_boot_seq.ogg'; +const SND_KEY = 'lt_boot_key.ogg'; +const SND_TICK = 'lt_boot_tick.ogg'; +const SND_DONE = 'lt_boot_done.ogg'; +const SND_LOGIN = 'lt_boot_login.ogg'; +const SOUNDS = [SND_POWER, SND_SEQ, SND_KEY, SND_TICK, SND_DONE, SND_LOGIN]; +/** Only the start-up screen plays these; the keystroke and the tick stay loaded for the lobby. */ +const ONE_TIME_SOUNDS = [SND_POWER, SND_SEQ, SND_DONE, SND_LOGIN]; + +type Cue = { + t: number; + id: string; + rate?: number; + /** A long clip: if its moment has passed it joins part-way in instead of being dropped. */ + long?: boolean; +}; + +const KEY_RATES = [1, 0.97, 1.04, 0.99, 1.02, 0.96, 1.03, 1]; + +const CUES: Cue[] = [ + { t: 0, id: SND_POWER }, + { t: DISC_AT, id: SND_SEQ, long: true }, + // One keystroke per letter. + ...KEY_RATES.map((rate, i) => ({ + t: LOCK_AT + STEP * (i + 1), + id: SND_KEY, + rate, + })), + // One tick per block, rising in pitch. + ...Array.from({ length: BLOCKS }, (_, i) => ({ + t: BAR_AT + STEP * (i + 1), + id: SND_TICK, + rate: 1 + i * 0.035, + })), + { t: DONE_AT, id: SND_DONE }, +]; + +/** With sound running, cues are handed to the audio clock this far ahead, so a busy page can't delay them. */ +const CUE_AHEAD = 1; +/** A short cue this late is dropped; playing it now would be out of step with the picture. */ +const CUE_LATE = 0.05; + +/** The screen stays dark this long at most waiting for its sounds and font, then starts anyway. */ +const HOLD_FOR_ASSETS_MS = 6000; +/** And this long at most for the server to say the screen is showing. */ +const HOLD_FOR_SHOWN_MS = 12000; + +const ease = (x: number) => 1 - (1 - Math.min(1, Math.max(0, x))) ** 3; + +/** + * CSS px per art pixel for the start-up screen: the largest whole number of device pixels + * that keeps the symbol, the name and LOGIN clear of each other inside the glass. + */ +export function bootPixel(glassW: number, glassH: number, dpr: number) { + const ratio = dpr > 0 ? dpr : 1; + const fit = Math.floor(Math.min(glassH / 270, glassW / 250)); + const css = Math.max(1, Math.min(8, fit)); + return Math.max(1, Math.round(css * ratio)) / ratio; +} + +/** TRUE once the terminal font has loaded, so the name never draws in a stand-in font. */ +function fontReady() { + try { + for (const face of Array.from(document.fonts)) { + if ( + face.family.replace(/["']/g, '') === 'VCR' && + face.status === 'loaded' + ) { + return true; + } + } + } catch { + return true; + } + return false; +} + +type Stage = 'hold' | 'run' | 'off'; + +type Props = { + /** The screen glass, in CSS px. */ + glassW: number; + glassH: number; + dpr: number; + /** Layers drawn over the start-up screen (scanlines, glass). */ + children?: ReactNode; +}; + +/** The start-up screen. Draws nothing once it has played or when the server says it already has. */ +export function Boot(props: Props) { + const { data, act } = useBackend(); + const [stage, setStage] = useState(() => (data.boot ? 'hold' : 'off')); + /** What the run started with, sent with LOGIN so the server log can say whether clients get the sound. */ + const report = useRef({ sound: 'none', clips: 0, wait: 0 }); + const leave = () => { + act('boot_done', { ...report.current, failed: 1 }); + setStage('off'); + }; + // The lobby's own sounds load once this screen has its clips, or at once when it is not shown. + useEffect(() => { + if (stage !== 'hold') { + preloadSfx(); + } + }, [stage]); + if (stage === 'off') { + return null; + } + return ( + + { + report.current = { + sound: audioState(), + clips: SOUNDS.filter(isLoaded).length, + wait: Math.round(wait), + }; + setStage('run'); + }} + onLogin={() => act('boot_done', report.current)} + onDone={() => setStage('off')} + /> + + ); +} + +/** A render error in the start-up screen must never take the lobby with it. */ +class BootGuard extends Component< + { children: ReactNode; onError: () => void }, + { failed: boolean } +> { + state = { failed: false }; + static getDerivedStateFromError() { + return { failed: true }; + } + componentDidCatch() { + lockNav(false); + this.props.onError(); + } + render() { + return this.state.failed ? null : this.props.children; + } +} + +function BootScreen( + props: Props & { + stage: Stage; + /** The server says the terminal is on the player's screen. */ + shown: boolean; + /** The server says this connection has already seen it. */ + seen: boolean; + /** Starts the run; `waited` is how long the screen stayed dark, in ms. */ + onRun: (waited: number) => void; + onLogin: () => void; + onDone: () => void; + }, +) { + const { glassW, glassH, dpr, stage, shown, seen, children } = props; + const px = bootPixel(glassW, glassH, dpr); + const snap = (v: number) => Math.round(v * dpr) / dpr; + + const root = useRef(null); + const canvas = useRef(null); + const line = useRef(null); + const word = useRef(null); + const blocks = useRef(null); + const login = useRef(null); + const shield = useRef(null); + const cursor = useRef(null); + /** The callbacks change every render; the loops below read them from here. */ + const live = useRef(props); + live.current = props; + + // The keyboard and the mouse belong to this screen for as long as it is up. + useLayoutEffect(() => { + lockNav(true); + return () => lockNav(false); + }, []); + + // Dark until the screen is showing and its sounds and font are in, or the wait runs out. + const [assets, setAssets] = useState(false); + const mountedAt = useRef(performance.now()); + useEffect(() => { + let alive = true; + preload(SOUNDS).then(() => alive && setAssets(true)); + return () => { + alive = false; + }; + }, []); + useEffect(() => { + if (stage !== 'hold') { + return; + } + if (seen) { + live.current.onDone(); + return; + } + const check = () => { + const waited = performance.now() - mountedAt.current; + const loaded = (assets && fontReady()) || waited > HOLD_FOR_ASSETS_MS; + if ((shown && loaded) || waited > HOLD_FOR_SHOWN_MS) { + live.current.onRun(waited); + } + }; + check(); + const timer = setInterval(check, 50); + return () => clearInterval(timer); + }, [stage, shown, seen, assets]); + + // The run: one loop draws the picture at 24 frames a second and hands the sounds to the audio clock. + const loginAt = useRef(null); + const loginUp = useRef(false); + const pressLogin = useRef<() => void>(() => undefined); + useEffect(() => { + if (stage !== 'run') { + return; + } + const start = performance.now() + LEAD * 1000; + const pending = CUES.slice(); + let raf = 0; + let lastStep = -1; + let ended = false; + + const finish = () => { + if (ended) { + return; + } + ended = true; + cancelAnimationFrame(raf); + unload(ONE_TIME_SOUNDS); + live.current.onDone(); + }; + + const cue = (now: number) => { + const at = (now - start) / 1000; + const ahead = audioState() === 'running' ? CUE_AHEAD : 0; + while (pending.length && pending[0].t - at <= ahead) { + const next = pending.shift() as Cue; + const wait = next.t - at; + if (wait >= -CUE_LATE) { + play(next.id, { when: Math.max(0, wait), rate: next.rate }); + } else if (next.long && isLoaded(next.id)) { + play(next.id, { offset: -wait, rate: next.rate }); + } + } + }; + + const draw = (tau: number) => { + // The waiting cursor goes the instant the power-on line appears. + const cursorEl = cursor.current; + if (cursorEl && tau >= 0) { + cursorEl.style.display = 'none'; + } + const lineEl = line.current; + if (lineEl) { + lineEl.style.display = tau >= 0 && tau < LINE_END ? 'block' : 'none'; + const width = + tau < LINE_HOLD + ? 1 + : Math.max(0, 1 - (tau - LINE_HOLD) / (LINE_END - LINE_HOLD)); + lineEl.style.transform = `scaleX(${width})`; + } + const canvasEl = canvas.current; + if (canvasEl) { + if (tau < 0) { + canvasEl.style.visibility = 'hidden'; + } else { + canvasEl.style.visibility = 'visible'; + renderEmblem(canvasEl, { + t: tau, + k: CANVAS_K, + grow: tau < DISC_AT ? 0 : ease((tau - DISC_AT) / DISC_TIME), + yaw: (1 - ease(tau / LOCK_AT)) * V_TURNS * Math.PI * 2, + v: tau > V_AT, + ring: tau * 2.4, + hud: tau < HUD_AT ? 0 : (tau - HUD_AT) / HUD_TIME, + }); + const flash = tau > LOCK_AT && tau < LOCK_AT + FLASH_TIME; + canvasEl.style.filter = flash ? 'brightness(2.2)' : ''; + } + } + const wordEl = word.current; + if (wordEl) { + const letters = Math.max( + 0, + Math.min(NAME.length, Math.floor((tau - LOCK_AT) / STEP)), + ); + const text = NAME.slice(0, letters) + ' '.repeat(NAME.length - letters); + if (wordEl.textContent !== text) { + wordEl.textContent = text; + } + } + const blocksEl = blocks.current; + if (blocksEl) { + const filled = Math.max(0, Math.floor((tau - BAR_AT) / STEP)); + for (let i = 0; i < blocksEl.children.length; i++) { + blocksEl.children[i].classList.toggle('f', i < filled); + } + blocksEl.style.visibility = + tau > BAR_SHOWN_AT && tau < LOGIN_AT ? 'visible' : 'hidden'; + } + const loginEl = login.current; + if (loginEl) { + loginUp.current = tau >= LOGIN_AT; + loginEl.style.visibility = loginUp.current ? 'visible' : 'hidden'; + } + }; + + const frame = (now: number) => { + try { + if (loginAt.current !== null) { + const since = (now - loginAt.current) / 1000; + if (since > FADE_HOLD + FADE_TIME + 0.05) { + finish(); + return; + } + if (root.current) { + root.current.style.opacity = String( + Math.max(0, Math.min(1, 1 - (since - FADE_HOLD) / FADE_TIME)), + ); + } + } + cue(now); + const step = Math.floor(((now - start) / 1000) * FPS); + if (step !== lastStep) { + lastStep = step; + draw(step / FPS); + } + raf = requestAnimationFrame(frame); + } catch { + // A browser that can't draw this still gets its lobby. + if (loginAt.current === null) { + live.current.onLogin(); + } + finish(); + } + }; + + pressLogin.current = () => { + if (!loginUp.current || loginAt.current !== null || ended) { + return; + } + loginAt.current = performance.now(); + play(SND_LOGIN); + live.current.onLogin(); + }; + raf = requestAnimationFrame(frame); + return () => { + ended = true; + cancelAnimationFrame(raf); + pressLogin.current = () => undefined; + for (const id of SOUNDS) { + stop(id); + } + }; + }, [stage]); + + // Keys: Enter or Space presses LOGIN; the terminal's other keys do nothing until then. + useEffect(() => { + const onKey = (e: KeyboardEvent) => { + if (e.ctrlKey || e.altKey || e.metaKey) { + return; + } + if (e.key === 'Enter' || e.key === ' ') { + e.preventDefault(); + if (!e.repeat && loginUp.current && loginAt.current === null) { + const el = login.current; + el?.classList.add('down'); + setTimeout(() => el?.classList.remove('down'), 120); + pressLogin.current(); + } + return; + } + if ( + e.key.startsWith('Arrow') || + e.key === 'Escape' || + e.key === 'Backspace' || + e.key === 'Tab' + ) { + e.preventDefault(); + } + }; + window.addEventListener('keydown', onKey, true); + return () => window.removeEventListener('keydown', onKey, true); + }, []); + + // Mouse: the sheet over the page takes every click; LOGIN is the one place a click does anything. + const overLogin = (x: number, y: number) => { + const el = login.current; + if (!el || !loginUp.current) { + return false; + } + const box = el.getBoundingClientRect(); + return x >= box.left && x < box.right && y >= box.top && y < box.bottom; + }; + const hover = (x: number, y: number, down?: boolean) => { + const over = overLogin(x, y); + login.current?.classList.toggle('hover', over); + if (down !== undefined || !over) { + login.current?.classList.toggle('down', over && !!down); + } + if (shield.current) { + shield.current.style.cursor = over ? 'pointer' : 'default'; + } + return over; + }; + + const size = CANVAS * px; + const fontPx = Math.round(12 * px); + const barW = (BLOCKS * 5 + (BLOCKS - 1) * 2) * px; + return ( +
+ +
+ +
+
+
+ {Array.from({ length: BLOCKS }, (_, i) => ( + + ))} +
+
+
+ LOGIN +
+
+ {children} + {createPortal( +
hover(e.clientX, e.clientY)} + onMouseDown={(e) => { + e.preventDefault(); + hover(e.clientX, e.clientY, true); + }} + onMouseUp={(e) => hover(e.clientX, e.clientY, false)} + onMouseLeave={() => hover(-1, -1, false)} + onClick={(e) => { + e.stopPropagation(); + if (overLogin(e.clientX, e.clientY)) { + pressLogin.current(); + } + }} + />, + document.body, + )} +
+ ); +} + +/** + * Sizes are art pixels times --bp (see bootPixel) or em of the start-up screen's own font + * size, 12 art pixels. + */ +const BOOT_CSS = ` +.lt-boot { position: absolute; inset: 0; z-index: 20; overflow: hidden; background: #030008; + font-family: 'VCR', 'Consolas', monospace; line-height: 1.25; color: #dfc4ff; user-select: none; + text-shadow: 0 0 calc(var(--bp) * 1.5) rgba(190,140,255,.55); } +.lt-boot canvas { position: absolute; image-rendering: pixelated; } +.lt-boot-cursor { position: absolute; left: calc(var(--bp) * 8); top: calc(var(--bp) * 8); width: .586em; height: 1em; + background: #6a4ea0; animation: lt-boot-cursor 1.06s steps(1) infinite; } +@keyframes lt-boot-cursor { 50% { opacity: 0; } } +.lt-boot-line { position: absolute; left: 0; right: 0; height: var(--bp); background: #fff; + box-shadow: 0 0 12px #c79bff; } +.lt-boot-word { position: absolute; left: 0; right: 0; top: 74%; text-align: center; white-space: pre; + font-size: 2.1333em; letter-spacing: .5em; padding-left: .5em; color: #fff; + text-shadow: 0 0 calc(var(--bp) * 3) #a070ff; } +.lt-boot-bar { position: absolute; top: 89%; display: flex; gap: calc(var(--bp) * 2); } +.lt-boot-bar i { display: block; box-sizing: border-box; width: calc(var(--bp) * 5); height: calc(var(--bp) * 5); + border: var(--bp) solid #5b3f8c; } +.lt-boot-bar i.f { background: #dfc4ff; border-color: #dfc4ff; } +.lt-boot-row { position: absolute; left: 0; right: 0; top: 87%; display: flex; justify-content: center; } +.lt-boot-login { box-sizing: border-box; white-space: pre; letter-spacing: .4em; padding: .25em 1.1em .25em 1.5em; + color: #dfc4ff; background: rgba(223,196,255,.08); border: var(--bp) solid #dfc4ff; + animation: lt-boot-pulse 1.2s steps(2) infinite; } +@keyframes lt-boot-pulse { 50% { border-color: #8a66c4; } } +.lt-boot-login.hover { background: #ff66d6; border-color: #ff66d6; color: #1a0420; text-shadow: none; animation: none; } +.lt-boot-login.down { background: #fff; border-color: #fff; color: #1a0420; text-shadow: none; animation: none; + transform: translateY(var(--bp)); } +.lt-boot-shield { position: fixed; inset: 0; z-index: 2147483000; background: transparent; cursor: default; } +`; diff --git a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/CharFile.tsx b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/CharFile.tsx new file mode 100644 index 00000000000..e5f87518e8b --- /dev/null +++ b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/CharFile.tsx @@ -0,0 +1,372 @@ +/** + * The personnel file (design 03 section 3): FILES under the viewscreen, the name and the four + * section blocks (BODY, ROLES, TRAITS, KIT) in the work column. A block press opens its editor. + */ +import { type ReactNode, useState } from 'react'; +import { useBackend } from 'tgui/backend'; +import type { ServerData } from 'tgui/interfaces/PreferencesMenu/types'; + +import { + clamp, + ID_W, + ID_X, + IdColumn, + perPage, + planId, + q, + type Section, + useChar, + useListPager, + useWheel, + WORK_W, + WORK_X, +} from './CharFrame'; +import { + Big, + BODY_Y, + cut, + Pager, + Put, + RPut, + SEP, + Slab, + safe, + useGrid, + WipeAt, + wrapMax, +} from './term'; +import type { CharData, CharStatic, LobbyData } from './types'; +import { + decodeName, + kitName, + nameOf, + quirkOf, + voiceShort, +} from './usePrefsCatalog'; + +const SECTIONS: [Section, string][] = [ + ['body', 'BODY'], + ['roles', 'ROLES'], + ['traits', 'TRAITS'], + ['kit', 'KIT'], +]; + +/** Text of one block: lines (with a class each), the right item, and the empty text. */ +type BlockText = { lines: [string, string][]; right?: string }; + +/** Points the taken traits leave to spend (tg: a quirk's value is what it costs). */ +export function traitPoints(cat: ServerData | null, quirks: string[]) { + return -quirks.reduce((sum, k) => sum + (quirkOf(cat, k)?.value || 0), 0); +} + +function bodyText( + cat: ServerData | null, + char: CharData, + L: number, +): BlockText { + const p = char.prefs; + const pron = nameOf(cat, 'gender', p.gender).toLowerCase(); + const first = [nameOf(cat, 'species', p.species), String(p.age ?? ''), pron] + .filter(Boolean) + .join(` ${SEP} `); + const lines: [string, string][] = [[cut(safe(first), 36), '']]; + if ('voice_pack' in p) { + const voice = voiceShort(nameOf(cat, 'voice_pack', p.voice_pack)); + lines.push([cut(safe(`${voice} voice`), 36), '']); + } + if ('background' in p) { + lines.push([cut(safe(nameOf(cat, 'background', p.background)), 36), '']); + } + return { lines: lines.slice(0, L) }; +} + +function rolesText( + stat: CharStatic | undefined, + char: CharData, + L: number, +): BlockText { + const order = stat?.roles.map((r) => r[0]) || Object.keys(char.roles); + const at = (lvl: number) => order.filter((r) => char.roles[r] === lvl); + const high = at(3)[0]; + const rest = [...at(2), ...at(1)].map(safe); + if (!high && !rest.length) { + return { lines: [['ANY BERTH', 'dim']] }; + } + if (!high) { + return { + lines: wrapMax(rest.join(', '), 36, L).map( + (l) => [l, ''] as [string, string], + ), + }; + } + const HIGH = safe(high).toUpperCase(); + if (!rest.length) { + return { lines: [[cut(HIGH, 36), 'acc']] }; + } + if (L === 1) { + // One line: the HIGH role, then the rest after the separator. + return { + lines: [[cut(`${HIGH} ${SEP} ${rest.join(', ')}`, 36), 'acc-split']], + }; + } + return { + lines: [ + [HIGH, 'acc'], + ...wrapMax(`then ${rest.join(', ')}`, 36, L - 1).map( + (l) => [l, ''] as [string, string], + ), + ], + }; +} + +function listText(names: string[], empty: string, L: number): BlockText { + if (!names.length) { + return { lines: [[empty, 'dim']] }; + } + return { + lines: wrapMax(names.map(safe).join(', '), 36, L).map( + (l) => [l, ''] as [string, string], + ), + }; +} + +export function CharFile(props: { + cat: ServerData | null; + /** Opens an editor. */ + open: (section: Section) => void; + /** The section to give the focus to (coming back from it, or BODY on a fresh open). */ + focus: Section | null; + /** A file switch is on its way: FILES are dead. */ + switching: boolean; + onSlot: (slot: number) => void; + /** Drawn in the work column instead of the name and blocks (the records didn't answer). */ + ghost?: ReactNode; +}) { + const { cat, open, focus, switching, onSlot, ghost } = props; + const { data } = useBackend(); + const { rows: M } = useGrid(); + const { quiet } = useChar(); + const char = data.char!; + const stat = data.char_static; + const slots = char.slots || []; + const n = Math.max(1, slots.length); + const name = safe(String(char.prefs.real_name ?? '')); + const NAME = name.toUpperCase(); + + // ---- FILES: one slab a slot, bottom-anchored under the uniform row. + let slabH = 1.25; + let paged = false; + let per = n; + const plan = planId(M, 1 + 1.5 * n, (la) => { + const h = clamp(q((la - 1) / n - 0.25), 1.25, 4.5); + const used = 1.25 + n * (h + 0.25) - 0.25; + if (used > la + 1e-6) { + paged = true; + per = perPage(la, 1.25); + slabH = 1.25; + return la; + } + slabH = h; + return used; + }); + const pages = paged ? Math.ceil(n / per) : 1; + const [page, setPage] = useState(() => + paged ? Math.floor((char.slot - 1) / per) : 0, + ); + const pg = Math.min(page, pages - 1); + useListPager(pg, pages, setPage); + const wheel = useWheel(); + const listTop = paged ? BODY_Y + plan.pv + 2.25 : plan.top; + const shownSlots = slots + .map((s, i) => [s, i] as [string | null, number]) + .slice(pg * per, pg * per + per); + + const files: ReactNode[] = [ + + {'FILES'} + , + ]; + shownSlots.forEach(([saved, i], k) => { + const y = listTop + 1.25 + k * (slabH + 0.25); + const cur = i + 1 === char.slot; + const label = cur ? NAME : saved ? safe(saved).toUpperCase() : 'NEW FILE'; + const lines = wrapMax(label, 16, clamp(Math.floor(slabH), 1, 3)); + const ty = y + (slabH - lines.length) / 2; + files.push( + onSlot(i + 1)} + > + + {String(i + 1)} + + {lines.map((line, j) => ( + + {line} + + ))} + , + ); + }); + if (paged) { + files.push( + setPage(p - 1)} + right + />, + // A page of files turning wipes the list only. + , + ); + } + + // ---- the name, never cut + let nameNode: ReactNode; + if (NAME.length <= 31) { + nameNode = ( + + {NAME} + + ); + } else if (NAME.length <= 39) { + nameNode = ( + + {NAME} + + ); + } else { + const two = wrapMax(NAME, 39, 2); + nameNode = two.map((line, i) => ( + + {line} + + )); + } + + // ---- the four blocks + const h = q((M - 7.75) / 4); + const p = h >= 4.75 ? 0.25 : 0.125; + const L = clamp(Math.floor(h - 1.25 - 2 * p), 1, 6); + const points = traitPoints(cat, char.quirks || []); + const pointsOn = cat?.quirks?.points_enabled !== false; + const texts: Record = { + body: bodyText(cat, char, L), + roles: rolesText(stat, char, L), + traits: { + ...listText( + (char.quirks || []).map((k) => quirkOf(cat, k)?.name || k), + 'NONE', + L, + ), + right: + pointsOn && points > 0 ? `${Math.min(999, points)} POINTS` : undefined, + }, + kit: listText( + Object.entries(char.kit || {}).map(([path, it]) => + it.name ? decodeName(it.name) : kitName(cat, path), + ), + 'NOTHING PACKED', + L, + ), + }; + + const blocks = SECTIONS.map(([sec, title], i) => { + const y = 5.75 + i * (h + 0.25); + const t = texts[sec]; + return ( + open(sec)} + > + + {title} + + {!!t.right && ( + + {t.right} + + )} + {t.lines.map(([line, cls], j) => { + const ly = y + p + 1.25 + j; + if (cls === 'acc-split') { + // HIGH role in accent, the rest in fg, on one line. + const cutAt = line.indexOf(` ${SEP} `); + const head = cutAt < 0 ? line : line.slice(0, cutAt); + return ( + + + {head} + + {cutAt >= 0 && ( + + {line.slice(cutAt)} + + )} + + ); + } + return ( + + {line} + + ); + })} + + ); + }); + + return ( + <> + + {/* The mouse wheel turns the pages of FILES, one a notch. */} +
1 ? (by) => setPage(clamp(pg + by, 0, pages - 1)) : null, + )} + > + {files} +
+
+ {ghost || ( + <> + {nameNode} + {blocks} + + )} + {/* Another file opening turns the page of the work column. */} + + + ); +} diff --git a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/CharFrame.tsx b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/CharFrame.tsx new file mode 100644 index 00000000000..5832451e9d4 --- /dev/null +++ b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/CharFrame.tsx @@ -0,0 +1,423 @@ +/** + * The CHARACTER frame (design 03 section 1): the box, the two columns, the ID column + * (viewscreen, uniform row, a list per screen), the crumbs on the tab row, the level-2 router + * and the species confirm dialog. + * + * Columns of the main region: the ID column is 1 to 21, column 22 is an empty gap, the work + * column is 23 to 61 (WORK_X, WORK_W). TRAITS uses the whole body (1 to 61). + * + * The seam for the editors (ROLES, TRAITS, KIT): each is a screen that draws its own ID column + * with and its list, and its work column. A level-2 screen + * (a picker, a colour panel) is opened with useChar().sub(node, crumb, from): the frame then + * draws `node` instead of the editor's work column, shows the crumb, and Escape or [ BACK ] + * closes it. `node` is kept as given, so it must read live data itself (a component that calls + * useBackend()), not values captured when it was opened. `from` names what opened it; that + * row is given the focus back (useChar().from). + */ +import { + createContext, + type ReactNode, + type WheelEvent as ReactWheelEvent, + useContext, + useEffect, + useRef, + useState, +} from 'react'; +import { useBackend } from 'tgui/backend'; + +import { turned, Viewscreen } from './CharPreview'; +import { quietDialogClose, useChanged } from './motion'; +import { Back, usePager } from './nav'; +import { + Band, + BODY_Y, + Box, + Btn, + bodyRows, + cut, + Dialog, + Hit, + Key, + Put, + safe, + useGrid, + wrapMax, +} from './term'; +import type { CharDir, LobbyData } from './types'; +import { nameOf, usePrefsCatalog } from './usePrefsCatalog'; + +export const ID_X = 1; +export const ID_W = 21; +export const WORK_X = 23; +export const WORK_W = 39; + +/** Rounds down to a quarter row. */ +export const q = (v: number) => Math.floor(v * 4 + 1e-6) / 4; +export const clamp = (v: number, lo: number, hi: number) => + Math.max(lo, Math.min(hi, v)); + +/** The open section; null is the file view. */ +export type Section = 'body' | 'roles' | 'traits' | 'kit'; + +export type CharNav = { + /** The facing on screen (kept while CHARACTER is open). */ + dir: CharDir; + turn: (by: 1 | -1) => void; + /** Opens a level-2 screen in the work column. from: what opened it (gets the focus back). */ + sub: (node: ReactNode, crumb: string, from?: string) => void; + /** Closes the level-2 screen. */ + closeSub: () => void; + /** TRUE while a level-2 screen is open. */ + subOpen: boolean; + /** What opened the last level-2 screen, while it is closed again; null otherwise. */ + from: string | null; + /** First-focus claims are off (the shell opened CHARACTER before the round). */ + quiet: boolean; +}; + +export const CharContext = createContext({ + dir: 2, + turn: () => undefined, + sub: () => undefined, + closeSub: () => undefined, + subOpen: false, + from: null, + quiet: false, +}); + +export const useChar = () => useContext(CharContext); + +/** + * The ID column's height rule (design 03 section 1.2). need: the list's smallest unpaged + * height. layout(la): lays the list out in `la` rows and returns the rows it used. + * Returns the viewscreen height, the room the list had, and the row the list starts on when + * it is bottom-anchored. + */ +export function planId( + M: number, + need: number, + layout: (la: number) => number, +) { + const B = bodyRows(M); + const pv0 = clamp(q(B - 2.25 - need), 6, 10.5); + const la = B - pv0 - 2.25; + const used = Math.min(la, layout(la)); + const spare = Math.max(0, la - used); + const pv = pv0 + Math.min(spare, 14 - pv0); + return { pv, la, used, top: M - 1.25 - used }; +} + +/** Slabs a page when an ID-column list has to page (headRows: 1.25 with a head, else 0). */ +export const perPage = (la: number, headRows: number) => + Math.max(1, Math.floor((la - headRows - 1) / 1.5)); + +/** + * The ID column above its list: the viewscreen and the uniform row. uniform: 'live' (one focus + * stop, Enter shows the next uniform), 'plain' (a label, as ROLES has it) or 'blank'. + */ +export function IdColumn(props: { + pv: number; + uniform?: 'live' | 'plain' | 'blank'; + children?: ReactNode; +}) { + const { pv, uniform = 'live', children } = props; + const { act, data } = useBackend(); + const { dir, turn } = useChar(); + const char = data.char; + const cats = (data.char_static?.roles || []) + .map((r) => r[0]) + .filter((c) => c !== 'Silicon'); + const dress = char?.dress || ''; + const step = (by: number) => { + if (!cats.length) { + return; + } + const at = cats.indexOf(dress); + const next = + cats[ + (((at < 0 ? 0 : at + by) % cats.length) + cats.length) % cats.length + ]; + act('char_dress', { category: next }); + }; + const uy = BODY_Y + pv + 0.25; + const label = cut(safe(dress).toUpperCase(), 15); + const show = uniform !== 'blank' && !!char; + return ( + <> + + + {!!show && ( + + {label} + + )} + {!!show && uniform === 'live' && ( + <> + step(-1)} + > + {'<'} + + step(1)} + > + {'>'} + + step(1)} /> + + )} + {children} + + ); +} + +/** One crumb: a label and where it goes (null: the last crumb, white and inert). */ +export type Crumb = [label: string, go: (() => void) | null]; + +/** `[ BACK ]`, two spaces, the crumbs: the tab row's right zone, right-aligned to column 62. */ +export function Crumbs(props: { crumbs: Crumb[]; onBack: () => void }) { + const { onBack } = props; + let parts = props.crumbs; + let lead = ''; + const text = () => lead + parts.map((p) => p[0]).join(' / '); + while (text().length > 23 && parts.length > 1) { + parts = parts.slice(1); + lead = '… / '; + } + const len = Math.min(23, text().length); + let x = 63 - len; + const y = 0.25; + const out: ReactNode[] = [ + , + ]; + if (lead) { + out.push( + + {lead} + , + ); + x += lead.length; + } + parts.forEach(([label, go], i) => { + const last = i === parts.length - 1; + const shown = cut(label, 63 - x); + out.push( + + {shown} + , + ); + x += shown.length; + if (!last) { + out.push( + + {' / '} + , + ); + x += 3; + } + }); + return <>{out}; +} + +/** The species confirm (design 03 section 4.7), drawn over any CHARACTER screen. */ +export function SpeciesConfirm() { + const { act, data } = useBackend(); + const cat = usePrefsCatalog(); + const confirm = data.char?.confirm; + const { cols, rows, cw, ch } = useGrid(); + if (!confirm) { + return null; + } + const species = safe(nameOf(cat, 'species', confirm.value)).toUpperCase(); + const quirks = (confirm.quirks || []).map((n) => safe(n).toUpperCase()); + const lines = wrapMax(quirks.join(', '), 41, 3); + const w = 45; + const x = Math.floor((63 - w) / 2); + const y = BODY_Y + 2; + const by = y + 2 + lines.length + 0.5; + return ( + <> + {/* The screen under the dialog dimmed, as LEAVE CREW does. Clicks stop here. */} +
e.stopPropagation()} + /> + + act('char_confirm', { ok: 0 })} /> + + {cut(`${species} CAN'T KEEP:`, 41)} + + {lines.map((line, i) => ( + + {line} + + ))} + act('char_confirm', { ok: 0 })} + /> + { + // Answered, not backed out of: the box goes without the back sound. + quietDialogClose(); + act('char_confirm', { ok: 1 }); + }} + /> + + + ); +} + +/** The box of every CHARACTER screen, with its caption, and SAVED on the border after a save. */ +export function CharBox(props: { caption: string }) { + const { rows } = useGrid(); + const { data } = useBackend(); + const [saved, setSaved] = useState(false); + useChanged(data.char_saved ?? 0, () => setSaved(true)); + useEffect(() => { + if (!saved) { + return; + } + const t = window.setTimeout(() => setSaved(false), 2000); + return () => window.clearTimeout(t); + }, [saved, data.char_saved]); + return ( + <> + + {!!saved && ( + + {' SAVED '} + + )} + + ); +} + +/** Calls fn once `ms` after `when` turns true, unless it turns false first. */ +export function useAfter(when: boolean, ms: number, fn: () => void) { + const ref = useRef(fn); + ref.current = fn; + useEffect(() => { + if (!when) { + return; + } + const t = window.setTimeout(() => ref.current(), ms); + return () => window.clearTimeout(t); + }, [when]); +} + +/** + * PageUp and PageDown (design 03 section 6) for a paged list: steps `page` (0-based) within + * `pages`, or does nothing on one page. + */ +export function useListPager( + page: number, + pages: number, + set: (p: number) => void, +) { + usePager(pages > 1 ? (step) => set(clamp(page + step, 0, pages - 1)) : null); +} + +/** + * The mouse wheel for a paged list (as CREWS and SETTINGS have it): one page a notch, at most + * one turn every 150 ms. Call it before any early return; `wheel(turn)` gives the handler for + * the list's wrapper, turn(1) the next page. A null turn (one page) does nothing. + */ +export function useWheel() { + const last = useRef(0); + return (turn: ((by: 1 | -1) => void) | null) => (e: ReactWheelEvent) => { + const now = Date.now(); + if (!turn || !e.deltaY || now - last.current < 150) { + return; + } + last.current = now; + turn(e.deltaY > 0 ? 1 : -1); + }; +} + +/** + * The same for a screen that returns early before its pages are known (hooks can't follow an + * early return): set `.current` while drawing, null when nothing pages. + */ +export function useLatePager() { + const ref = useRef<((step: number) => void) | null>(null); + usePager((step) => ref.current?.(step)); + return ref; +} + +/** + * A row's `<` and `>`: two 3-cell cap keys from column x, mouse targets only (the row's own + * keys step it). `ends`: the value sits at its low or high end; that arrow is drawn faint and + * does nothing, as the pagers draw theirs. A cycling list has no ends. + */ +export function StepKeys(props: { + x: number; + y: number; + h: number; + onStep: (by: 1 | -1) => void; + ends?: [atLow: boolean, atHigh: boolean]; +}) { + const { x, y, h, onStep, ends } = props; + return ( + <> + onStep(-1)} + /> + onStep(1)} + /> + + ); +} + +/** The facing after a turn, for the router's dir state. */ +export const nextDir = turned; diff --git a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/CharPickers.tsx b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/CharPickers.tsx new file mode 100644 index 00000000000..689410ce44a --- /dev/null +++ b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/CharPickers.tsx @@ -0,0 +1,414 @@ +/** + * The shared level-2 screens of CHARACTER (design 03 section 4.5): the list picker and the + * colour panel. Both are laid out in a column (x, w) of the main region: (23, 39) from BODY and + * KIT, (1, 31) from TRAITS. They fill rows 3.0 to M - 1.25. Escape and [ BACK ] belong to the + * frame (CharFrame), which closes them. + * + * A picker press applies at once and the picker stays open. A colour bar applies when it is let + * go, a hex on Enter, a chip on a press. Nothing is sent while a bar is dragged. + */ +import { useEffect, useRef, useState } from 'react'; + +import { useListPager } from './CharFrame'; +import { + barGradient, + type HSV, + hexToHsv, + hsvToHex, + parseHex, + readStored, + remember, +} from './ColorEntry'; +import { + Bar, + Big, + BODY_Y, + bodyRows, + cut, + Field, + HRule, + Key, + Pager, + Put, + Slab, + Swatch, + safe, + useGrid, + WipeAt, + wrapMax, +} from './term'; + +const q = (v: number) => Math.floor(v * 4) / 4; + +export type PickerProps = { + x: number; + w: number; + /** The crumb and the head, e.g. 'HAIR'. */ + label: string; + choices: string[]; + value: string; + nameOf: (v: string) => string; + /** Palette lists: the colour a choice shows. */ + hexOf?: (v: string) => string | null; + onPick: (v: string) => void; + onClose: () => void; +}; + +export type ColourPanelProps = { + x: number; + w: number; + /** 'HAIR COLOUR', 'EYES', 'COLOUR 2'. */ + label: string; + /** '#rrggbb'. */ + value: string; + /** Colours on this file; the viewer's last ones are added after them. */ + recent: string[]; + /** Show [ PICKER ] (BYOND's colour dialog). */ + native?: boolean; + onApply: (hex: string) => void; + onPicker?: () => void; + onClose: () => void; +}; + +/** Rows 3.0 to 4.5: the label, big and white. */ +function Head(props: { x: number; label: string; w: number }) { + const { x, label, w } = props; + const text = safe(label).toUpperCase(); + return text.length * 1.25 <= w ? ( + + {text} + + ) : ( + + {cut(text, w)} + + ); +} + +export function ListPicker(props: PickerProps) { + const { x, w, label, choices, value, nameOf, hexOf, onPick } = props; + const { rows: M } = useGrid(); + const wide = w >= 39; + const [find, setFind] = useState(''); + const findOn = choices.length > 24; + + const shown = (v: string) => safe(nameOf(v)); + const needle = find.trim().toLowerCase(); + const list = needle + ? choices.filter((v) => shown(v).toLowerCase().includes(needle)) + : choices; + + // Two columns when at most one name in ten is longer than 17 (the full list decides, so + // typing in FIND never reflows the page). + const long17 = choices.filter((v) => shown(v).length > 17).length; + // A list that fits one column whole stays in one column. + const short = choices.length * 1.25 <= M - 6.5; + const ncol = wide && !short && long17 * 10 <= choices.length ? 2 : 1; + const colW = ncol === 2 ? 19 : w; + const palette = !!hexOf; + const nameW = (ncol === 2 ? 17 : w - 3) - (palette ? 3 : 0); + const two = !wide && choices.some((v) => shown(v).length > nameW); + const baseH = two ? 2.25 : 1.25; + + const fitAll = Math.floor((M - 6.5) / baseH); + const paged = fitAll * ncol < list.length; + // A short list that fits on one page: its rows grow (to 2.25) so the column fills. When + // there is room they stand apart as slabs a quarter row apart (as BODY's rows and the + // species list do), so a list that ends early reads as whole, not cut. + const rowsUsed = Math.max(1, Math.ceil(choices.length / ncol)); + const gapped = + short && !paged && !two && rowsUsed * 1.5 - 0.25 <= M - 6.5 + 1e-6; + const rowH = + paged || two + ? baseH + : gapped + ? Math.max(baseH, Math.min(2.25, q((M - 6.25) / rowsUsed - 0.25))) + : Math.max(baseH, Math.min(2.25, q((M - 6.5) / rowsUsed))); + const pitch = gapped ? rowH + 0.25 : rowH; + // One page: the columns share the list evenly, so the second is never left empty. + const perCol = Math.max( + 1, + paged + ? Math.floor((M - 7.75) / baseH) + : Math.min(fitAll, Math.ceil(list.length / ncol)), + ); + const per = perCol * ncol; + const pages = Math.max(1, Math.ceil(list.length / per)); + const pageOf = (v: string) => Math.max(0, Math.floor(list.indexOf(v) / per)); + const [page, setPage] = useState(() => pageOf(value)); + // The open value's page follows it (< and >, or a push from tg's window). + useEffect(() => { + if (list.includes(value)) { + setPage(pageOf(value)); + } + }, [value]); + const pg = Math.min(page, pages - 1); + useListPager(pg, pages, setPage); + const lastWheel = useRef(0); + const slice = list.slice(pg * per, (pg + 1) * per); + + const step = (by: number) => { + const at = choices.indexOf(value); + const n = choices.length; + if (n) { + onPick(choices[(((at < 0 ? 0 : at + by) % n) + n) % n]); + } + }; + + return ( + // The mouse wheel turns the pages, one a notch. +
{ + const now = Date.now(); + if (pages <= 1 || !e.deltaY || now - lastWheel.current < 150) { + return; + } + lastWheel.current = now; + setPage(Math.max(0, Math.min(pages - 1, pg + (e.deltaY > 0 ? 1 : -1)))); + }} + > + + {!!findOn && ( + { + setFind(v); + setPage(0); + }} + onEnter={() => { + if (list.length === 1) { + onPick(list[0]); + } + }} + /> + )} + {/* Nothing to step to on a list of one: no arrows. */} + {choices.length > 1 && ( + <> + step(-1)} + /> + step(1)} + /> + + )} + + {slice.map((v, i) => { + const col = Math.floor(i / perCol); + const r = i % perCol; + const cx = x + col * (colW + 1); + const cy = 5.25 + r * pitch; + const on = v === value; + const hex = hexOf?.(v); + const nx = cx + 2 + (palette ? 3 : 0); + const lines = two + ? wrapMax(shown(v), nameW, 2) + : [cut(shown(v), nameW)]; + return ( + onPick(v)} + > + {!!palette && ( + + )} + {lines.map((line, j) => ( + + {line} + + ))} + + ); + })} + {!slice.length && ( + + {'NO MATCH.'} + + )} + setPage(p - 1)} + right + /> + {/* A page turn wipes the rows only. */} + +
+ ); +} + +const PANEL_CSS = ` +.lt-tui .lt-hexbad .lt-field { color: var(--lt-faint); text-shadow: none; } +`; + +export function ColourPanel(props: ColourPanelProps) { + const { x, w, label, value, recent, native, onApply, onPicker } = props; + const { rows: M } = useGrid(); + const B = bodyRows(M); + // Tall panes give the room to thicker bars, then a taller swatch, so the foot never sits empty. + const g = B >= 20 ? Math.min(3.25, Math.max(2.25, q((B - 13.25) / 3))) : 1.75; + const S = Math.min(10, Math.max(3, q(B - 5.25 - 3 * g))); + const yb = 5.5 + S; + + const current = parseHex(value) || '#000000'; + const [was] = useState(current); + const [hsv, setHsv] = useState(() => hexToHsv(current)); + const [text, setText] = useState(current.toUpperCase()); + const live = useRef(hsv); + live.current = hsv; + const dragging = useRef(false); + + // A push (ours or tg's window) moves the panel unless a bar is held. + useEffect(() => { + if (!dragging.current) { + setHsv(hexToHsv(current)); + setText(current.toUpperCase()); + } + }, [current]); + + const typed = parseHex(text); + const draft = typed || hsvToHex(hsv); + + const apply = (hex: string | null) => { + if (!hex) { + return; + } + remember(hex); + setHsv(hexToHsv(hex)); + setText(hex.toUpperCase()); + if (hex !== current) { + onApply(hex); + } + }; + + const chips = [...recent.map((c) => parseHex(c)), ...readStored()] + .filter((c, i, all): c is string => !!c && all.indexOf(c) === i) + .slice(0, Math.min(12, Math.floor((w + 1) / 3))); + + const channels: ['h' | 's' | 'v', string][] = [ + ['h', 'H'], + ['s', 'S'], + ['v', 'V'], + ]; + + return ( + <> + + + + +
+ { + setText(v); + const hex = parseHex(v); + if (hex) { + setHsv(hexToHsv(hex)); + } + }} + onEnter={() => apply(typed)} + /> +
+ + {'WAS'} + + apply(was)} /> + {channels.map(([c, name], i) => { + const by = yb + i * g; + const bh = g - 0.75; + const t = c === 'h' ? hsv.h / 360 : hsv[c]; + const at = (v: number): HSV => ({ + ...live.current, + [c]: c === 'h' ? v * 359.9 : v, + }); + return ( + + + {name} + + { + dragging.current = true; + const next = at(v); + live.current = next; + setHsv(next); + setText(hsvToHex(next).toUpperCase()); + }} + onRelease={() => { + dragging.current = false; + apply(hsvToHex(live.current)); + }} + /> + + ); + })} + {chips.map((c, i) => ( + apply(c)} + /> + ))} + {!!native && !!onPicker && ( + + )} + + ); +} diff --git a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/CharPreview.tsx b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/CharPreview.tsx index 99945fa1bdd..3d0de515600 100644 --- a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/CharPreview.tsx +++ b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/CharPreview.tsx @@ -1,43 +1,122 @@ /** - * The character preview (CHARACTER-PLAN 2.5 / 3): a viewscreen over cells (x, y, w, h) - * showing the server's render of the dressed mannequin facing dir, on the dark floor tile. - * Keeps a client cache of char_preview pushes (key -> dir -> png, last 6 looks) and sends - * char_turn only for a facing it doesn't have for the current look. Keeps the last image on - * screen while a new one is on its way. The turn keys and dress label around it belong to - * CharacterTab. Owner: C2. + * The viewscreen (design 03 section 2): the server's render of the dressed mannequin facing + * dir, on the violet floor tile, over cells (x, y, w, h). One focus stop: Enter turns it + * clockwise. `«` and `»` inside the picture are mouse targets. + * + * Keeps a page cache of char_preview pushes (look key -> dir -> png, last LOOKS looks) and + * sends char_turn only for a facing it doesn't hold for the current look (char.look). While a + * render is on its way the last picture stays; after PENDING_MS it dims and SCANNING shows. + * + * A turn squashes the picture sideways in two steps (60 ms), swaps the facing at its thinnest + * and opens it in two steps (60 ms); a facing not held yet waits thin until it lands. A new + * look (an edit, a uniform) is revealed by a wipe over the viewscreen, never a turn. */ import { type CSSProperties, useEffect, useRef, useState } from 'react'; import { resolveAsset } from 'tgui/assets'; import { useBackend } from 'tgui/backend'; -import { useGrid } from './term'; -import type { CellBox, CharDir, LobbyData } from './types'; +import { sfxInstead, Wipe } from './motion'; +import { useFocusable } from './nav'; +import { Put, useGrid } from './term'; +import type { CharDir, LobbyData } from './types'; -/** Looks kept client side, as many as the server keeps. */ -const LOOKS = 6; +/** Looks kept page side, as many as the server keeps (LOBBY_CHAR_CACHE_LOOKS). */ +const LOOKS = 10; /** Mannequin tile, in sprite pixels. */ const TILE = 32; -/** An unanswered char_turn may be sent again after this long (ms). */ +/** An unanswered char_turn is sent again after this long (ms). */ const ASK_AGAIN = 3000; -/** char_face (a turn to a cached facing) goes out at most this often (ms). */ +/** char_face (a turn to a held facing) goes out at most this often (ms). */ const FACE_EVERY = 400; +/** A render this late dims the last picture and shows SCANNING (ms). */ +const PENDING_MS = 250; +/** Rows past this only add floor below the picture: the body never jumps between screens. */ +const PIC_ROWS = 10.5; +/** Each half of a turn: squashing, then opening (ms). */ +const TURN_HALF = 60; +/** A turn waiting thin on a facing that never lands opens anyway after this long (ms). */ +const TURN_GIVE_UP = 3000; + +/** A turn under way: the picture it started from, and how far along it is. */ +type Turn = { + serial: number; + from: string | null; + phase: 'close' | 'hold' | 'open'; +}; + +/** Facings in clockwise order: S, W, N, E. */ +export const TURN: CharDir[] = [2, 8, 1, 4]; + +/** The facing `by` steps clockwise from dir. */ +export function turned(dir: CharDir, by: number): CharDir { + const i = TURN.indexOf(dir); + return TURN[((((i < 0 ? 0 : i) + by) % 4) + 4) % 4]; +} type Look = Partial>; -export function CharPreview(props: CellBox & { dir: CharDir }) { - const { x, y, w, h, dir } = props; +// Kept across mounts while the window lives: switching screens never loses held facings. +const cache = new Map(); +const asked = new Map(); + +function store(key: string, dir: CharDir, png: string) { + const look = cache.get(key) || {}; + look[dir] = png; + cache.delete(key); + cache.set(key, look); + while (cache.size > LOOKS) { + cache.delete(cache.keys().next().value as string); + } + asked.delete(`${key}:${dir}`); +} + +export function Viewscreen(props: { + x: number; + y: number; + w: number; + h: number; + dir: CharDir; + /** Turn by one facing: 1 clockwise (`»`, Enter), -1 back (`«`). */ + onTurn: (by: 1 | -1) => void; + auto?: number; +}) { + const { x, y, w, h, dir, onTurn } = props; const { cw, ch } = useGrid(); const { data, act } = useBackend(); const pushed = data.char_preview; + const [, setTick] = useState(0); + + // Every push goes into the cache. + useEffect(() => { + if (pushed?.png) { + store(pushed.key, pushed.dir, pushed.png); + setTick((t) => t + 1); + } + }, [pushed?.key, pushed?.dir, pushed?.png]); + + // The look the character has now: char.look, or the last pushed key from an older server. + const look = data.char?.look || pushed?.key || ''; + const png = look ? cache.get(look)?.[dir] : undefined; + + // The picture on screen: the held facing, else the last one shown. + const last = useRef(null); + if (png) { + last.current = png; + } + const shown = png || last.current; + + // The server renders its current facing on every edit, so a new look counts as asked. + const seen = useRef(''); + if (look && look !== seen.current) { + seen.current = look; + if (!asked.has(`${look}:${dir}`)) { + asked.set(`${look}:${dir}`, Date.now()); + } + } - // key -> look, oldest first. - const cache = useRef(new Map()); - // "key:dir" -> when char_turn asked for it. - const asked = useRef(new Map()); - // The facing the server last heard about (char_turn or char_face), and the one on screen. const told = useRef<{ sent: CharDir; want: CharDir; timer: number | null }>({ - sent: 2, - want: 2, + sent: dir, + want: dir, timer: null, }); useEffect( @@ -48,33 +127,15 @@ export function CharPreview(props: CellBox & { dir: CharDir }) { }, [], ); - const [current, setCurrent] = useState(null); - const [shown, setShown] = useState(null); - const [size, setSize] = useState<[number, number]>([TILE, TILE]); - // Every push goes into the cache; its key becomes the current look. + // Held: tell the server which side is on screen (rarely). Not held: ask, then every 3 s. + const [late, setLate] = useState(false); useEffect(() => { - if (!pushed?.png) { + if (!look) { return; } - const looks = cache.current; - const look = looks.get(pushed.key) || {}; - look[pushed.dir] = pushed.png; - looks.delete(pushed.key); - looks.set(pushed.key, look); - while (looks.size > LOOKS) { - looks.delete(looks.keys().next().value as string); - } - asked.current.delete(`${pushed.key}:${pushed.dir}`); - setCurrent(pushed.key); - }, [pushed?.key, pushed?.dir, pushed?.png]); - - // Show the facing if this look has it; otherwise ask once and keep the last image. - const png = current ? cache.current.get(current)?.[dir] : undefined; - useEffect(() => { if (png) { - setShown(png); - // A cached facing: only tell the server which side is on screen, at most every FACE_EVERY ms. + setLate(false); const t = told.current; t.want = dir; if (t.timer === null) { @@ -88,66 +149,206 @@ export function CharPreview(props: CellBox & { dir: CharDir }) { } return; } - told.current.sent = dir; - told.current.want = dir; - const ask = `${current || ''}:${dir}`; - const at = asked.current.get(ask); - if (at === undefined || Date.now() - at > ASK_AGAIN) { - asked.current.set(ask, Date.now()); - act('char_turn', { dir }); + const ask = () => { + const at = asked.get(`${look}:${dir}`); + if (at === undefined || Date.now() - at >= ASK_AGAIN) { + asked.set(`${look}:${dir}`, Date.now()); + told.current.sent = dir; + told.current.want = dir; + act('char_turn', { dir }); + } + }; + ask(); + const dim = window.setTimeout(() => setLate(true), PENDING_MS); + const again = window.setInterval(ask, 500); + return () => { + window.clearTimeout(dim); + window.clearInterval(again); + }; + }, [look, dir, !!png]); + + // Turning: the notch sound in place of the key press, a little lower going back. + const turnBy = (by: 1 | -1) => { + sfxInstead('turn', { rate: by < 0 ? 0.9 : 1 }); + onTurn(by); + }; + const focus = useFocusable(true, { + activate: () => turnBy(1), + auto: props.auto, + }); + + // The turn. It starts from the picture drawn last, whatever facing is asked for now. + const drawn = useRef(null); + const lastDir = useRef(dir); + const [turnState, setTurn] = useState(null); + let turn = turnState; + if (lastDir.current !== dir) { + lastDir.current = dir; + turn = { + serial: (turnState?.serial || 0) + 1, + from: drawn.current, + phase: 'close', + }; + setTurn(turn); + } + const held = useRef(false); + held.current = !!png; + const turnSerial = turn?.serial; + const turnPhase = turn?.phase; + useEffect(() => { + if (!turnSerial || !turnPhase) { + return; + } + const mine = (cur: Turn | null) => !!cur && cur.serial === turnSerial; + let id: number; + if (turnPhase === 'close') { + // At its thinnest the facing swaps; it opens at once when the new one is held. + id = window.setTimeout( + () => + setTurn((cur) => + mine(cur) && cur + ? { ...cur, phase: held.current ? 'open' : 'hold' } + : cur, + ), + TURN_HALF, + ); + } else if (turnPhase === 'open') { + id = window.setTimeout( + () => setTurn((cur) => (mine(cur) ? null : cur)), + TURN_HALF, + ); + } else { + id = window.setTimeout( + () => setTurn((cur) => (mine(cur) && cur ? { ...cur, phase: 'open' } : cur)), + TURN_GIVE_UP, + ); + } + return () => window.clearTimeout(id); + }, [turnSerial, turnPhase]); + // The facing it waited for has landed. + useEffect(() => { + if (turnPhase === 'hold' && png) { + setTurn((cur) => (cur && cur.phase === 'hold' ? { ...cur, phase: 'open' } : cur)); } - }, [current, dir, png]); + }, [turnPhase, !!png]); + const pic = turn && turn.phase === 'close' ? turn.from : shown; + drawn.current = pic; + const turnCls = + turn?.phase === 'close' + ? 'lt-turn-a' + : turn?.phase === 'hold' + ? 'lt-turn-hold' + : turn?.phase === 'open' + ? 'lt-turn-b' + : undefined; + + // A new look landing (not a turn): its picture is revealed by a wipe over the viewscreen. + const landedLook = useRef(png ? look : ''); + const landed = useRef(0); + if (png && look !== landedLook.current) { + landed.current += 1; + landedLook.current = look; + } const sx = Math.round(x * cw); const sy = Math.round(y * ch); - const sw = Math.round(w * cw); - const sh = Math.round(h * ch); + const sw = Math.round((x + w) * cw) - sx; + const sh = Math.round((y + h) * ch) - sy; - // Largest whole scale that leaves a margin round the tile, as the mockup draws it. - const k = Math.max(1, Math.floor(Math.min(sw * 0.82, sh * 0.86) / TILE)); + // Scale and tile centre come from at most PIC_ROWS rows, so the body holds still between screens. + const ph = Math.min(sh, Math.round(PIC_ROWS * ch)); + const k = Math.max(1, Math.floor((Math.min(sw, ph) * 0.93) / TILE)); const t = TILE * k; const ox = Math.round((sw - t) / 2); - const oy = Math.round((sh - t) / 2) + Math.round(t * 0.08); + const oy = Math.round((ph - t) / 2); + const [size, setSize] = useState<[number, number]>([TILE, TILE]); const [iw, ih] = size; + const pending = !png && (late || !shown); const floor: CSSProperties = { position: 'absolute', inset: 0, - opacity: 0.38, + opacity: 0.5, backgroundImage: `url(${resolveAsset('char_floor.png')})`, backgroundSize: `${t}px ${t}px`, backgroundPosition: `${ox}px ${oy}px`, imageRendering: 'pixelated', }; + const markY = y + h - 1.25; return ( -
-
- {!!shown && ( - - setSize([ - e.currentTarget.naturalWidth, - e.currentTarget.naturalHeight, - ]) - } - style={{ - position: 'absolute', - // A render bigger than one tile stays centred on it, feet on the tile. - left: ox - Math.round(((iw - TILE) * k) / 2), - top: oy - (ih - TILE) * k, - width: iw * k, - height: ih * k, - imageRendering: 'pixelated', - zIndex: 1, - }} + <> +
{ + e.stopPropagation(); + turnBy(1); + }} + > +
+ {!!pic && ( + + setSize([ + e.currentTarget.naturalWidth, + e.currentTarget.naturalHeight, + ]) + } + style={{ + position: 'absolute', + // A render bigger than one tile stays centred on it, feet on the tile. + left: ox - Math.round(((iw - TILE) * k) / 2), + top: oy - (ih - TILE) * k, + width: iw * k, + height: ih * k, + imageRendering: 'pixelated', + opacity: pending ? 0.45 : 1, + zIndex: 1, + }} + /> + )} + +
+
+ {pending ? ( + + {'SCANNING'} + + + ) : ( + <> + turnBy(-1)} + > + {'«'} + + turnBy(1)} + > + {'»'} + + )} -
-
+ ); } diff --git a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/CharacterTab.tsx b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/CharacterTab.tsx index a0e89488c2c..61bcc7015ba 100644 --- a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/CharacterTab.tsx +++ b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/CharacterTab.tsx @@ -1,567 +1,274 @@ /** - * CHARACTER tab, layout A "personnel file" (CHARACTER-PLAN 2.2): FILES, the preview, the - * PERSONNEL FILE cells and the crumbs; one editor sub-screen at a time. - * Owner: C3. + * CHARACTER (design 03): the router. Level 0 is the personnel file, level 1 an editor (BODY, + * ROLES, TRAITS, KIT), level 2 a picker or colour panel in the work column. The frame pieces + * (box, ID column, crumbs, species dialog) are in CharFrame.tsx. * - * Editors get the inside of the frame CharacterTab draws for them: CellBox (x, y = frame top - * + 1, w = frame width, h = frame height - 1), as the mockup's editors do. BODY, ROLES and KIT - * keep the preview on the left; TRAITS and every narrow screen use the full width. + * Props the shell wires: home (bumped when CHARACTER is pressed while open: back to the file), + * auto (the shell opened it before the round: char_open {auto: 1}, no focus claim), onLeave + * (Escape at the file view: back to the tab that was open before). */ -import { type ReactNode, useEffect, useState } from 'react'; +import { type ReactNode, useEffect, useRef, useState } from 'react'; import { useBackend } from 'tgui/backend'; -import { BodyEditor } from './BodyEditor'; -import { CharPreview } from './CharPreview'; -import { parseHex } from './ColorEntry'; +import { BodyEditor, type BodyGroup } from './BodyEditor'; +import { CharFile } from './CharFile'; +import { + CharBox, + CharContext, + type CharNav, + type Crumb, + Crumbs, + IdColumn, + nextDir, + type Section, + SpeciesConfirm, + WORK_W, + WORK_X, +} from './CharFrame'; import { KitEditor } from './KitEditor'; +import { useScreen } from './motion'; import { useBack } from './nav'; import { RolesEditor } from './RolesEditor'; import { TraitsEditor } from './TraitsEditor'; import { - Frame, - Hit, - Put, - pad, - RPut, - Rule, - Swatch, - TOP, + BODY_Y, + bodyRows, + Key, + NameLine, + Slab, + safe, useGrid, - wrap, + WipeAt, } from './term'; -import type { - CellBox, - CharData, - CharDir, - CharSection, - CharStatic, - LobbyData, -} from './types'; -import { - kitName, - namedHex, - nameOf, - quirkOf, - usePrefsCatalog, -} from './usePrefsCatalog'; +import type { CharDir, LobbyData } from './types'; +import { usePrefsCatalogState } from './usePrefsCatalog'; -const SECTIONS: [CharSection, string][] = [ - ['body', 'BODY'], - ['roles', 'ROLES'], - ['traits', 'TRAITS'], - ['kit', 'KIT'], -]; -const PRIO = ['NEVER', 'LOW', 'MED', 'HIGH']; -/** Facings in clockwise order: S, W, N, E. */ -const TURN: CharDir[] = [2, 8, 1, 4]; +const TITLES: Record = { + body: 'BODY', + roles: 'ROLES', + traits: 'TRAITS', + kit: 'KIT', +}; -/** A `[ LABEL ]` key, dim at rest, lit on hover (the mockup's key()). */ -function Key(props: { - x: number; - y: number; - label: string; - cls?: string; - bg?: boolean; - onClick: () => void; -}) { - const { x, y, label, cls = 'dim', bg, onClick } = props; +/** A file switch is taken as done (or lost) after this long. */ +const SWITCH_MS = 3000; +/** A push this far behind char_rev is asked for again. */ +const STALE_MS = 2000; +const STALE_EVERY = 5000; + +type Sub = { node: ReactNode; crumb: string; from: string | null }; + +/** The ghost block in the work column while the file is fetched or the records don't answer. */ +function Ghost(props: { text: string; onRetry?: () => void }) { + const { text, onRetry } = props; return ( - - {label} - + <> + + + {!!onRetry && ( + + )} + ); } -/** The category with the highest level (first in role order on a tie), or null. */ -function topRole(char: CharData, stat?: CharStatic) { - let best: string | null = null; - let lvl = 0; - const order = stat?.roles.map((r) => r[0]) || Object.keys(char.roles); - for (const cat of order) { - const v = char.roles[cat] || 0; - if (v > lvl) { - lvl = v; - best = cat; - } - } - return best; -} - -export function CharacterTab(props: { home: number }) { - const { home } = props; +export function CharacterTab(props: { + home: number; + auto?: boolean; + onLeave?: () => void; +}) { + const { home, auto, onLeave } = props; const { act, data } = useBackend(); - const { cols, rows, narrow } = useGrid(); - const cat = usePrefsCatalog(); - const [section, setSection] = useState(null); - useBack(section ? () => setSection(null) : null); + const { rows: M } = useGrid(); + const { cat, failed, retry } = usePrefsCatalogState(); + const char = data.char; + + const [section, setSection] = useState
(null); + const [sub, setSub] = useState(null); + const [from, setFrom] = useState(null); + /** The section the file view gives the focus to: BODY on a player's open, else the one left. */ + const [focusSec, setFocusSec] = useState
( + auto ? null : 'body', + ); + const [group, setGroup] = useState('identity'); const [dir, setDir] = useState(2); + const [switchAt, setSwitchAt] = useState(0); + const quiet = !!auto && !section && focusSec === null; useEffect(() => { - act('char_open'); + act('char_open', auto ? { auto: 1 } : {}); }, []); - useEffect(() => { - setSection(null); - }, [home]); - - const char = data.char; - const stat = data.char_static; - const h = rows - 1 - TOP; - const name = String(char?.prefs.real_name ?? ''); - const NAME = name.toUpperCase(); - // ---- the preview with its turn keys and dress label - const preview = (x: number, y: number, w: number, ph: number) => { - const ky = Math.ceil(y + ph) + 1; - const turn = (by: number) => { - const i = TURN.indexOf(dir); - setDir(TURN[(i + by + TURN.length) % TURN.length]); - }; - const out: ReactNode[] = [ - , - turn(-1)} />, - turn(1)} - />, - ]; - if (char?.dress) { - const dress = char.dress.toUpperCase(); - const off = char.dress !== (topRole(char, stat) ?? char.dress); - const cats = (stat?.roles.map((r) => r[0]) || []).filter( - (c) => c !== 'Silicon', - ); - // Past the last category the preview goes back to automatic (the top role). - const at = cats.indexOf(char.dress); - const next = !cats.length - ? null - : at === cats.length - 1 - ? '' - : cats[at + 1]; - const lab = pad(dress, Math.max(1, w - 12)).trimEnd(); - out.push( - act('char_dress', { category: next }) - : undefined - } - > - {lab} - , - ); + const toFile = () => { + setSub(null); + setFrom(null); + if (section) { + setFocusSec(section); } - return out; + setSection(null); }; - - // ---- crumbs and [ BACK ] on the tab row - const crumbs = (label: string) => { - const seg: [string, (() => void) | null][] = [ - ['CHARACTER', () => setSection(null)], - [NAME || 'FILE', () => setSection(null)], - [label, null], - ]; - const room = cols - 1 - 42 - 12; - const width = () => seg.map((s) => s[0]).join(' / ').length; - while (seg.length > 1 && width() > room) { - seg.shift(); - } - const fits = width() <= room; - let x = cols - 1 - (fits ? width() : 0); - const out: ReactNode[] = [ - setSection(null)} - />, - ]; - if (fits) { - seg.forEach(([lab, go], i) => { - const last = i === seg.length - 1; - out.push( - - {lab} - , - ); - x += lab.length; - if (!last) { - out.push( - - {' / '} - , - ); - x += 3; - } - }); - } - return out; + const openSection = (s: Section) => { + setSub(null); + setFrom(null); + setSection(s); }; - - // ---- a section open - if (section && char) { - const label = SECTIONS.find((s) => s[0] === section)![1]; - const full = section === 'traits' || narrow; - const pw = full ? 0 : Math.min(40, Math.floor(cols * 0.3)); - const ex = full ? 0 : pw + 1; - const ew = cols - ex; - const box: CellBox = { x: ex, y: TOP + 1, w: ew, h: h - 1 }; - let editor: ReactNode = null; - if (section === 'body') { - editor = ; - } else if (section === 'roles') { - editor = ; - } else if (section === 'traits') { - editor = ; - } else { - editor = ; - } - return ( - <> - {crumbs(label)} - {!full && ( - - {preview(2, TOP + 1.5, pw - 4, h - 5.5)} - - )} - - {editor} - - ); - } - - // ---- the file - const slots = char?.slots || []; - const pw = Math.min(40, Math.floor(cols * 0.3)); - const files = ( - - {slots.map((s, i) => { - const cur = i + 1 === char?.slot; - const shown = cur ? name : s; - const yy = TOP + 1 + i; - return ( - - {!!cur && ( - - {' '.repeat(pw - 2)} - - )} - - {String(i + 1)} - - - {pad(shown ? shown.toUpperCase() : '-- EMPTY --', pw - 6)} - - {!cur && ( - act('char_slot', { slot: i + 1 })} - /> - )} - - ); - })} - - ); - const n = Math.max(3, slots.length); - const py = TOP + 2 + n; - const ph = h - 6.5 - n; - - const x = pw + 1; - const w = cols - x; - const gx = x + 2; - const gw = Math.floor((w - 5) / 2); - const gy = TOP + 4; - const gh = Math.floor((h - 5) / 2); - const compact = gh < 6; - // Tall cells leave a blank row under the title, as the mockup does. - const inset = gh >= 9 ? 2 : 1; - - const body = char ? identity(char) : null; - const cell = ( - i: number, - title: string, - sec: CharSection, - fill: (cx: number, cy: number, cw: number, rh: number) => ReactNode, - ) => { - const cx = gx + (i % 2) * (gw + 1); - const cy = gy + Math.floor(i / 2) * gh; - return ( - - - setSection(sec)} - /> - {fill(cx + 3, cy + inset, gw - 6, gh - 1 - inset)} - - ); + const closeSub = () => { + setFrom(sub?.from ?? null); + setSub(null); }; - function identity(c: CharData) { - const p = c.prefs; - const voice = nameOf(cat, 'voice_pack', p.voice_pack); - const lines: [string, string][] = [ - ['SPECIES', nameOf(cat, 'species', p.species)], - ['AGE', String(p.age ?? '')], - ['PRONOUNS', nameOf(cat, 'gender', p.gender)], - ['VOICE', voice.includes(': ') ? voice.split(': ').pop()! : voice], - ]; - const chips: [string, string][] = []; - const add = (lab: string, hex: string | null) => { - if (hex) { - chips.push([lab, hex]); - } - }; - if ('skin_tone' in p) { - add('SKIN', namedHex(cat, 'skin_tone', p.skin_tone)); - } - if ('hairstyle_name' in p && 'hair_color' in p) { - add('HAIR', parseHex(p.hair_color)); - } - if ('feature_mcolor' in p) { - add('SCALES', parseHex(p.feature_mcolor)); - } - if ('feature_ethcolor' in p) { - add('GLOW', namedHex(cat, 'feature_ethcolor', p.feature_ethcolor)); - } - if ('eye_color' in p) { - add('EYES', parseHex(p.eye_color)); - } - return { lines, chips }; - } + useEffect(() => { + setSub(null); + setFrom(null); + setSection(null); + }, [home]); - const bodyCell = (cx: number, cy: number, cw: number, rh: number) => { - if (!body) { - return null; + // The open file changed (here or in tg's window): back to the file view. + const slot = char?.slot; + const lastSlot = useRef(slot); + useEffect(() => { + if (lastSlot.current !== undefined && slot !== lastSlot.current) { + setSub(null); + setFrom(null); + setSection(null); + setFocusSec('body'); + setSwitchAt(0); } - const out: ReactNode[] = []; - body.lines.slice(0, Math.max(0, rh - 1)).forEach(([k, v], i) => { - out.push( - - {k} - , - - {pad(v, cw - 11)} - , - ); - }); - let sx = cx; - const sy = cy + Math.min(body.lines.length, Math.max(0, rh - 1)); - for (const [k, hex] of body.chips) { - if (sx + k.length + 3 > cx + cw) { - break; - } - out.push( - - {k} - , - , - ); - sx += k.length + 5; + lastSlot.current = slot; + }, [slot]); + useEffect(() => { + if (!switchAt) { + return; } - return out; - }; + const t = window.setTimeout(() => setSwitchAt(0), SWITCH_MS); + return () => window.clearTimeout(t); + }, [switchAt]); - const rolesCell = (cx: number, cy: number, cw: number, rh: number) => { - if (!char) { - return null; + // Stale: char_rev (every tick) ahead of the last push for 2 s asks again, once per 5 s. + const behind = !!char && (data.char_rev ?? 0) > char.rev; + const lastAsk = useRef(0); + useEffect(() => { + if (!behind) { + return; } - const order = stat?.roles.map((r) => r[0]) || Object.keys(char.roles); - const out: ReactNode[] = []; - let yy = cy; - for (let lvl = 3; lvl >= 1 && yy < cy + rh; lvl--) { - const names = order.filter((r) => char.roles[r] === lvl); - if (!names.length) { - continue; - } - out.push( - - {PRIO[lvl]} - , - ); - for (const l of wrap(names.join(', '), cw - 7).slice(0, cy + rh - yy)) { - out.push( - - {l} - , - ); - yy++; + const t = window.setTimeout(() => { + if (Date.now() - lastAsk.current >= STALE_EVERY) { + lastAsk.current = Date.now(); + act('char_open'); } - } - if (yy === cy) { - out.push( - - {'ANY BERTH'} - , - ); - } - return out; - }; + }, STALE_MS); + return () => window.clearTimeout(t); + }, [behind, data.char_rev]); - const points = () => - -(char?.quirks || []).reduce( - (sum, q) => sum + (quirkOf(cat, q)?.value || 0), - 0, - ); + // Escape: up one level; at the file view, back to the tab before. + useBack(sub ? closeSub : section ? toFile : onLeave || null); - const traitsCell = (cx: number, cy: number, cw: number, rh: number) => { - if (!char) { - return null; - } - const pts = points(); - const out: ReactNode[] = char.quirks - .slice(0, Math.max(0, rh - 2)) - .map((q, i) => { - const info = quirkOf(cat, q); - const v = info?.value || 0; - return ( - - - {pad(info?.name || q, cw - 5)} - - 0 ? 'amb' : 'dim'}> - {String(v)} - - - ); - }); - if (!char.quirks.length) { - out.push( - - {'NONE'} - , - ); - } - if (cat?.quirks?.points_enabled !== false) { - out.push( - - {'POINTS'} - , - - {String(pts)} - , - ); - } - return out; - }; + // An editor opens with the wipe and closes with it run back. Opened by the shell before the + // round, CHARACTER comes up without either. + useScreen(`character/${section || 'file'}`, section ? 1 : 0, '', 0, !!auto); - const kitCell = (cx: number, cy: number, cw: number, rh: number) => { - const items = Object.keys(char?.kit || {}); - if (!items.length) { - return ( - - {'NOTHING PACKED'} - - ); - } - return items.slice(0, rh).map((p, i) => ( - - {pad(kitName(cat, p), cw)} - - )); + const nav: CharNav = { + dir, + turn: (by) => setDir((d) => nextDir(d, by)), + sub: (node, crumb, at) => { + setFrom(null); + setSub({ node, crumb, from: at ?? null }); + }, + closeSub, + subOpen: !!sub, + from, + quiet, }; - /** One line per section when the cells don't fit (short screens). */ - const compactList = () => { - if (!char) { - return null; + const NAME = safe(String(char?.prefs.real_name ?? '')).toUpperCase(); + const caption = section ? NAME || 'PERSONNEL FILE' : 'PERSONNEL FILE'; + const crumbs: Crumb[] = [['CHARACTER', toFile]]; + if (section) { + crumbs.push([TITLES[section], sub ? closeSub : null]); + if (sub) { + crumbs.push([sub.crumb, null]); } - const top = topRole(char, stat); - const lines: [CharSection, string, string][] = [ - [ - 'body', - 'BODY', - body - ? body.lines - .slice(0, 3) - .map((l) => l[1]) - .join(', ') - : '', - ], - ['roles', 'ROLES', top ? `${top}` : 'Any berth'], - [ - 'traits', - 'TRAITS', - char.quirks.map((q) => quirkOf(cat, q)?.name || q).join(', ') || 'None', - ], - [ - 'kit', - 'KIT', - Object.keys(char.kit) - .map((p) => kitName(cat, p)) - .join(', ') || 'Nothing packed', - ], - ]; - const step = h - 4 >= 8 ? 2 : 1; - return lines.map(([sec, lab, sum], i) => { - const yy = TOP + 3 + i * step; - return ( - - - {lab} - - - {pad(sum, Math.max(1, w - 25))} - - setSection(sec)} - /> - - ); - }); - }; + } + + let screen: ReactNode; + if (!char) { + screen = ( + <> + + + + ); + } else if (!section) { + screen = ( + { + setSwitchAt(Date.now()); + act('char_slot', { slot: n }); + }} + ghost={ + failed ? ( + { + act('char_open'); + retry(); + }} + /> + ) : undefined + } + /> + ); + } else if (section === 'body') { + screen = ; + } else if (section === 'roles') { + // Each of these draws its own ID column (or none, TRAITS) and its work column. + screen = ; + } else if (section === 'traits') { + screen = ; + } else { + screen = ; + } return ( - <> - {files} - - {ph >= 3 && preview(2, py, pw - 4, ph)} - - {!!char && ( - <> - - {pad(NAME, Math.max(1, w - 20))} - - - {`FILE ${char.slot} OF ${char.slots.length}`} - - {compact - ? compactList() - : [ - cell(0, 'BODY', 'body', bodyCell), - cell(1, 'ROLES', 'roles', rolesCell), - cell(2, 'TRAITS', 'traits', traitsCell), - cell(3, 'KIT', 'kit', kitCell), - ]} - + + + {!!section && } + {screen} + {!!sub && sub.node} + {/* A picker or a colour panel wipes its own column only (TRAITS: the list column). */} + {!!section && ( + )} - + + ); } diff --git a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/ColorEntry.tsx b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/ColorEntry.tsx index 89c4ee45927..02d06338895 100644 --- a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/ColorEntry.tsx +++ b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/ColorEntry.tsx @@ -1,41 +1,11 @@ /** - * Free colour entry for BODY and KIT (CHARACTER-PLAN 2.9). The row reads - * `LABEL [##] #RRGGBB`; clicking the chip or the hex opens the H/S/V panel. Only SET sends. - * Owner: C3. The props are the contract C4's KitEditor builds against; keep them. - * - * An empty label draws just the chip and hex (for a colour that sits after a cycler on the - * same row, as HAIR does); the panel is then titled COLOUR. The panel places itself under the - * row and stays on the screen. Dragging on a bar only changes local state: nothing is sent - * until SET, so the server never renders a colour that was dragged past. + * Colour helpers shared by CHARACTER's colour panel (CharPickers ColourPanel) and SETTINGS: + * hex parsing, H/S/V conversion, the bar gradients and the viewer's last colours. */ -import { type PointerEvent as ReactPointerEvent, useState } from 'react'; - -import { useBack } from './nav'; -import { Btn, Field, lpad, Panel, Put, Swatch, TOP, useGrid } from './term'; - -export type ColorEntryProps = { - /** Column and row of the label. */ - x: number; - y: number; - /** Cells the row may use. */ - w: number; - label: string; - /** Current colour, "#rrggbb". */ - value: string; - /** Colours offered in the recent row (already on this file, plus the viewer's last ones). */ - recent: string[]; - /** Show [ PICKER ] (BYOND's native dialog). BODY colours only. */ - native?: boolean; - /** SET pressed with a valid colour. */ - onSet: (hex: string) => void; - /** [ PICKER ] pressed. */ - onPicker?: () => void; -}; - // --------------------------------------------------------------------------- // Colour maths -type HSV = { h: number; s: number; v: number }; +export type HSV = { h: number; s: number; v: number }; /** "#rrggbb", "rrggbb", "#rgb" or "rgb" to "#rrggbb" (lower case), else null. */ export function parseHex(text: string): string | null { @@ -54,7 +24,7 @@ export function parseHex(text: string): string | null { return /^[0-9a-f]{6}$/.test(t) ? `#${t}` : null; } -function hexToHsv(hex: string): HSV { +export function hexToHsv(hex: string): HSV { const n = parseInt(hex.slice(1), 16); const r = ((n >> 16) & 255) / 255; const g = ((n >> 8) & 255) / 255; @@ -78,7 +48,7 @@ function hexToHsv(hex: string): HSV { return { h, s: max ? d / max : 0, v: max }; } -function hsvToHex({ h, s, v }: HSV): string { +export function hsvToHex({ h, s, v }: HSV): string { const f = (k: number) => { const t = (k + h / 60) % 6; return v - v * s * Math.max(0, Math.min(t, 4 - t, 1)); @@ -96,7 +66,7 @@ function hsvToHex({ h, s, v }: HSV): string { const STORE = 'lt-recent-colours'; const KEEP = 8; -function readStored(): string[] { +export function readStored(): string[] { try { const raw = JSON.parse(window.localStorage.getItem(STORE) || '[]'); return Array.isArray(raw) @@ -107,7 +77,7 @@ function readStored(): string[] { } } -function remember(hex: string) { +export function remember(hex: string) { try { const next = [hex, ...readStored().filter((c) => c !== hex)].slice(0, KEEP); window.localStorage.setItem(STORE, JSON.stringify(next)); @@ -116,19 +86,9 @@ function remember(hex: string) { } } -// --------------------------------------------------------------------------- - -const PANEL_W = 44; -const PANEL_H = 11; -const BAR = 24; -const CHANNELS: ['h' | 's' | 'v', string, number][] = [ - ['h', 'H', 360], - ['s', 'S', 100], - ['v', 'V', 100], -]; /** The CSS gradient a bar shows: its channel swept with the other two held. */ -function barGradient(ch: 'h' | 's' | 'v', hsv: HSV): string { +export function barGradient(ch: 'h' | 's' | 'v', hsv: HSV): string { const stops: string[] = []; for (let i = 0; i <= 12; i++) { const t = i / 12; @@ -142,227 +102,3 @@ function barGradient(ch: 'h' | 's' | 'v', hsv: HSV): string { } return `linear-gradient(to right, ${stops.join(', ')})`; } - -/** One H/S/V bar: BAR cells, click or drag to set. */ -function Bar(props: { - x: number; - y: number; - ch: 'h' | 's' | 'v'; - hsv: HSV; - onChange: (t: number) => void; -}) { - const { x, y, ch, hsv, onChange } = props; - const { cw, ch: rh } = useGrid(); - const t = ch === 'h' ? hsv.h / 360 : ch === 's' ? hsv.s : hsv.v; - const at = (e: ReactPointerEvent) => { - const r = e.currentTarget.getBoundingClientRect(); - onChange(Math.max(0, Math.min(1, (e.clientX - r.left) / r.width))); - }; - return ( -
{ - e.stopPropagation(); - e.currentTarget.setPointerCapture(e.pointerId); - at(e); - }} - onPointerMove={(e) => { - if (e.currentTarget.hasPointerCapture(e.pointerId)) { - at(e); - } - }} - onClick={(e) => e.stopPropagation()} - > -
-
- ); -} - -export function ColorEntry(props: ColorEntryProps) { - const { x, y, w, label, value, recent, native, onSet, onPicker } = props; - const { cols, rows } = useGrid(); - const [open, setOpen] = useState(false); - const [hsv, setHsv] = useState(() => - hexToHsv(parseHex(value) || '#000000'), - ); - const [text, setText] = useState(String(value ?? '')); - - const current = parseHex(value) || '#000000'; - const typed = parseHex(text); - - const show = (hex: string) => { - setHsv(hexToHsv(hex)); - setText(hex.toUpperCase()); - }; - const openPanel = () => { - show(current); - setOpen(true); - }; - const set = (hex: string | null) => { - if (!hex) { - return; - } - remember(hex); - setOpen(false); - if (hex !== current) { - onSet(hex); - } - }; - - useBack(open ? () => setOpen(false) : null); - - const lx = label ? x + label.length + 1 : x; - const row = ( - <> - {!!label && ( - - {label} - - )} - - {lx - x + 10 <= w && ( - - {current.toUpperCase()} - - )} - - ); - if (!open) { - return row; - } - - // Under the row, kept on the screen. - const px = Math.max(0, Math.min(x, cols - PANEL_W - 1)); - const py = - y + 1 + PANEL_H <= rows - 1 - ? y + 1 - : Math.max(TOP, Math.min(y - PANEL_H, rows - 1 - PANEL_H)); - const draft = typed || hsvToHex(hsv); - const chips = [...recent.map((c) => parseHex(c)), ...readStored()] - .filter((c, i, all): c is string => !!c && all.indexOf(c) === i) - .slice(0, Math.floor((PANEL_W - 6) / 2)); - - return ( - <> - {row} - - - { - setText(v); - const hex = parseHex(v); - if (hex) { - setHsv(hexToHsv(hex)); - } - }} - onEnter={() => set(typed)} - /> - {!typed && ( - <> - - {'['} - - - {']'} - - - )} - {CHANNELS.map(([ch, name, scale], i) => { - const shown = ch === 'h' ? hsv.h : hsv[ch] * 100; - return ( - - - {name} - - { - const next = { ...hsv, [ch]: ch === 'h' ? t * 359.9 : t }; - setHsv(next); - setText(hsvToHex(next).toUpperCase()); - }} - /> - - {lpad(Math.round(Math.min(shown, scale)), 3)} - - - ); - })} - {chips.map((c, i) => ( - show(c)} - /> - ))} - {!!native && !!onPicker && ( - { - setOpen(false); - onPicker(); - }} - /> - )} - setOpen(false)} - /> - set(typed)} - /> - - - ); -} diff --git a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/CrewRecord.tsx b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/CrewRecord.tsx index 73ef2940d4d..132a2db3251 100644 --- a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/CrewRecord.tsx +++ b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/CrewRecord.tsx @@ -1,272 +1,562 @@ /** - * The record pane of one crew: memo, berths with SIGN ON, CODE / NOTE + APPLY for locked - * crews, PING CREW when every berth is taken. Package P2. + * The record of one crew, in place of the CREWS list: class and aboard, the memo, BERTHS + * (one row a job with its SIGN ON key, paged) beside ABOARD (names, captains marked), and + * under the berths the CODE and NOTE rows of a locked crew or PING CREW for a full one. + * `[ BACK ]` and the ship stepper sit in the tab row's right zone. + * + * Main-region rows: box from BOX_Y, body from BODY_Y to rows - 1.25, the notice row at + * rows - 1. Columns: BERTHS 1 to 41, a rule in 43, ABOARD 45 to 61. */ -import { type ReactNode, useState } from 'react'; +import { type ReactNode, useEffect, useRef, useState } from 'react'; import { useBackend } from 'tgui/backend'; -import { useBack } from './nav'; + +import { sfx, useChanged, useChangedNow } from './motion'; +import { useBack, usePager } from './nav'; import { - Blocks, + Band, + BODY_Y, + BOX_Y, + Big, + Box, Btn, + bodyRows, + cut, Field, - Frame, + FlashAt, + HRule, + Key, + NameLine, + Pager, Put, - pad, RPut, - Rule, - TOP, + SEP, + Slab, + safe, + useCellRect, + useGrid, + VRule, + WipeAt, wrapMax, } from './term'; -import type { Crew, LobbyData } from './types'; +import type { Crew, CrewJob, LobbyData } from './types'; /** SHIP_JOIN_PASSWORD_MAX_LEN and SHIP_APPLICATION_MESSAGE_MAX_LEN (voidcrew/_DEFINES/overmap.dm). */ const CODE_MAX = 24; const NOTE_MAX = 200; +const YOUR_CREW = ' YOUR CREW '; +const DOORS = 'DOORS CREW ONLY'; +/** Line 1's left part. */ +const LINE1_W = 43; +/** Memo width: columns 1 to 61. */ +const MEMO_W = 61; +/** + * Berth rows: title columns 3 to 24, count ending at 27, key 29 to 41 (13 wide, so the + * 11-character label has a column clear of the key's edge on each side, as in the stills). + */ +const TITLE_W = 22; +const KEY_X = 29; +const KEY_W = 13; +/** CODE and NOTE fields: columns 6 to 27. */ +const FIELD_W = 22; +const BERTH_PITCH = 1.75; +const BERTH_H = 1.5; +/** The widest pitch berth rows stretch to when they all fit, and the row height from which + * a row may take the larger title and count. */ +const BERTH_PITCH_MAX = 4; +const BERTH_TALL = 2.25; +/** ABOARD: columns 45 to 61. */ +const ABOARD_X = 45; +const NAME_W = 17; +const CAPT_NAME_W = 12; + /** Seconds as m:ss. */ export function clock(seconds: number): string { - const m = Math.floor(seconds / 60); - const s = seconds % 60; + const t = Math.max(0, Math.floor(seconds)); + const m = Math.floor(t / 60); + const s = t % 60; return `${m}:${s < 10 ? '0' : ''}${s}`; } -/** Cuts to n characters without padding; a cut ends in '.'. */ -export function cut(str: string, n: number): string { - return str.length > n ? `${str.slice(0, Math.max(0, n - 1))}.` : str; -} - /** Locked and not yet cleared to board. */ export const isLocked = (c: Crew) => !!c.locked && !c.cleared; +/** ` • aboard`; the class drops out when the name already starts with it. */ +export function classLine(c: Crew, name: string): string { + const cls = safe(c.cls).trim(); + const aboard = `${Math.min(999, Math.max(0, c.crew || 0))} aboard`; + if (!cls || name.toUpperCase().startsWith(cls.toUpperCase())) { + return aboard; + } + return `${cls} ${SEP} ${aboard}`; +} + +/** + * A server countdown in seconds, ticking down once a second in the page from the last value + * the server sent. + */ +function useCountdown(value: number): number { + const base = useRef({ value, at: Date.now() }); + if (base.current.value !== value) { + base.current = { value, at: Date.now() }; + } + const [, tick] = useState(0); + const live = value > 0; + useEffect(() => { + if (!live) { + return; + } + const id = setInterval(() => tick((n) => n + 1), 1000); + return () => clearInterval(id); + }, [live]); + if (!live) { + return 0; + } + const gone = Math.floor((Date.now() - base.current.at) / 1000); + return Math.max(0, base.current.value - gone); +} + +/** A berth row coming alive after the code was accepted: its dead look lifts 40 ms after `delay`. */ +function Light(props: { y: number; h: number; delay: number }) { + const style = useCellRect(1, props.y, 41, props.h); + return ( +
+ ); +} + +/** Berth rows light this far apart, top to bottom, when a code is accepted. */ +const LIGHT_GAP = 40; + type Props = { crew: Crew; - x: number; - w: number; - h: number; - /** Narrow layout: the record has the whole screen and closes with BACK. */ - narrow: boolean; + /** 1-based place of this ship in the list order, and the list's length. */ + index: number; + total: number; + /** Open the ship at this 1-based place in the list order. */ + onStep: (to: number) => void; onClose: () => void; }; export function CrewRecord(props: Props) { - const { crew: c, x, w, h, narrow, onClose } = props; - const { act } = useBackend(); + const { crew: c, index, total, onStep, onClose } = props; + const { data, act } = useBackend(); + const { rows } = useGrid(); const [code, setCode] = useState(''); const [note, setNote] = useState(''); - const bottom = TOP + h - 1; - const out: ReactNode[] = []; - let y = TOP + 2; + const [berthPage, setBerthPage] = useState(1); + /** The job whose SIGN ON takes the focus when it mounts (paging). */ + const [claimJob, setClaimJob] = useState(null); + /** The berth last pressed, lit while the join is under way. */ + const [pressed, setPressed] = useState(null); + const lastWheel = useRef(0); useBack(onClose); - const closeLabel = narrow ? ' BACK ' : ' X '; - out.push( - - {closeLabel} - , - ); + const pingWait = useCountdown(c.ping_wait || 0); + const rejoinWait = useCountdown(c.rejoin_wait || 0); + const codeWait = useCountdown(c.code_wait || 0); + + // PageUp and PageDown step to the previous and next ship. + usePager((step) => { + const to = index + step; + if (to >= 1 && to <= total) { + onStep(to); + } + }); + + const name = safe(c.name).toUpperCase(); + const playing = data.phase === 'playing'; + const joining = !!data.joining; + const locked = isLocked(c); + const applied = locked && !!c.applied; + // The code was accepted: the berth rows light top to bottom. + const [lights, setLights] = useState(0); + useChangedNow(locked, (was, now) => { + if (was && !now && !!c.cleared) { + setLights((n) => n + 1); + sfx('ok', { own: true }); + } + }); + useEffect(() => { + if (!lights) { + return; + } + const id = setTimeout(() => setLights(0), 1500); + return () => clearTimeout(id); + }, [lights]); + // An application or a ping went through: its row flashes once. + useChanged(applied, (_, now) => { + if (now) { + sfx('ok', { own: true }); + } + }); + const pinged = (c.ping_wait || 0) > 0; + useChanged(pinged, (_, now) => { + if (now) { + sfx('ok', { own: true }); + } + }); + const jobs = c.jobs || []; + const full = !jobs.length; + const end = BODY_Y + bodyRows(rows); + const out: ReactNode[] = []; + + // Tab row, right zone: [ BACK ], three spaces, the stepper; right-aligned to column 62. + const stepText = + total > 1 ? `< ${Math.min(99, index)}/${Math.min(99, total)} >` : ''; + const backEnd = 63 - (stepText ? stepText.length + 3 : 0); + let firstFocus: 'sign' | 'code' | 'ping' | 'back' = 'back'; + + // Line 1: class and aboard, YOUR CREW, DOORS CREW ONLY. Half a row under the caption, as + // in the stills; flush under it the line crowds the ship's name. + let y = BODY_Y + 0.5; + const tag = c.mine ? YOUR_CREW.length + 2 : 0; + const line1 = cut(classLine(c, name), LINE1_W - tag); out.push( - - {pad(c.cls.toUpperCase(), Math.max(1, w - 9 - `${c.crew} ABOARD`.length))} + + {line1} , - - {`${c.crew} ABOARD`} - , ); - y += 1; - if (c.doors) { + if (c.mine) { out.push( - - DOORS - , - - CREW ONLY + + {YOUR_CREW} , ); } - y += 2; - - const locked = isLocked(c) && !c.applied; - // Rows the lower block needs: the code and note rows for a locked crew, one row otherwise. - const tail = locked ? 7 : c.applied ? 3 : 1; + if (c.doors) { + out.push( + + {DOORS} + , + ); + } + y += 1.5; - if (c.memo) { - const room = Math.max(1, bottom - y - tail - 6); - const lines = wrapMax(`"${c.memo}"`, w - 6, Math.min(4, room)); - for (const line of lines) { + // The memo, in quotes. + const memo = safe(c.memo).replace(/\s+/g, ' ').trim(); + if (memo) { + const lines = wrapMax(`"${memo}"`, MEMO_W, bodyRows(rows) >= 20 ? 4 : 2); + lines.forEach((text, i) => { out.push( - - {line} + + {text} , ); - y++; - } - y += 1; + }); + y += lines.length + 0.5; } - // Who is aboard, the captain first, in what room the berths below leave. - const aboard = c.aboard || []; - if (aboard.length) { - const below = - 1 + - (c.jobs.length ? Math.min(2, c.jobs.length) * 2 : 4) + - tail + - (c.rejoin_wait > 0 && !locked ? 3 : 0); - const room = Math.min(6, bottom - y - below - 1); - if (room >= 1) { - const shown = aboard.length > room ? room - 1 : aboard.length; - const more = Math.max(c.crew, aboard.length) - shown; - const jobW = Math.min( - 16, - Math.max(6, ...aboard.map(([, job]) => job.length)), + + // Divider, heads, and the rule between the columns. + const ruleY = y + 0.25; + out.push( + , + , + ); + y += 0.75; + out.push( + + BERTHS + , + + ABOARD + , + ); + y += 1.25; + const colTop = y; + + // ABOARD: names only, captains first and marked. + const roster = data.roster && data.roster.ref === c.ref ? data.roster : null; + if (roster) { + const names = roster.names || []; + const room = Math.max(1, Math.floor(end - colTop)); + const known = names.length + Math.max(0, roster.more || 0); + const crewN = Math.max(known, c.crew || 0); + const shown = + crewN > names.length || names.length > room + ? Math.min(names.length, room - 1) + : names.length; + names.slice(0, shown).forEach(([who, capt], i) => { + const text = safe(who).toUpperCase(); + out.push( + + {cut(text, capt ? CAPT_NAME_W : NAME_W)} + , ); - const nameX = x + 8; - const nameW = Math.max(4, x + w - 3 - jobW - 2 - nameX); - aboard.slice(0, shown).forEach(([name, job, capt], i) => { + if (capt) { out.push( - - {pad(name.toUpperCase(), nameW)} - , - - {cut(job.toUpperCase(), jobW)} + + CAPT , ); - if (capt) { - out.push( - - CAPT - , - ); - } - y++; - }); - if (more > 0) { - out.push( - - {`+${more} MORE`} - , - ); - y++; } - y += 1; - } - } - out.push(); - y += 1; - - if (!c.jobs.length) { - out.push( - - NO BERTHS OPEN - , - ); - y += 3; - if (c.ping_wait > 0) { + }); + if (crewN > shown) { out.push( - - [ PING CREW ] - , - - {clock(c.ping_wait)} + + {`+${Math.min(999, crewN - shown)} MORE`} , ); - } else { - out.push( - act('crew_ping', { ship: c.ref })} - />, - ); } - return <>{out}; } - if (c.rejoin_wait > 0 && !locked) { - y += 1; + // BERTHS. + let by = colTop; + if (rejoinWait > 0 && !locked && !full) { out.push( - - {`BACK ABOARD IN ${clock(c.rejoin_wait)}`} + + {`BACK ABOARD IN ${clock(rejoinWait)}`} , ); - y += 2; + by += 1.25; } + const tail = !locked ? 0 : applied ? 3 : 3.5; + let t0 = by; - const grey = locked || !!c.applied; - const sign = '[ SIGN ON ]'; - // The job name gets the whole width up to SIGN ON; the open berths sit on the line under it. - const nameW = Math.max(8, w - 3 - sign.length - 5); - const maxBlocks = Math.max(1, Math.floor((nameW - 1) / 2)); - // Name, berths and a spacer per job; drop the spacer when that would not fit. - const step = y + c.jobs.length * 3 + tail <= bottom ? 3 : 2; - let jobRoom = Math.max(1, Math.floor((bottom - y - tail) / step)); - // Berths that don't fit leave a row saying how many more there are. - const jobsCut = c.jobs.length > jobRoom; - if (jobsCut) { - jobRoom = Math.max(1, Math.floor((bottom - y - tail - 1) / step)); - } - let autoGiven = false; - for (const job of c.jobs.slice(0, jobRoom)) { - const usable = !grey && !!job.ok && c.rejoin_wait <= 0; - const first = usable && !autoGiven; - autoGiven = autoGiven || usable; + if (full) { out.push( - - {pad(job.title.toUpperCase(), nameW)} + , + + NO BERTHS OPEN. , ); - const shown = Math.min(job.open, maxBlocks); - for (let i = 0; i < shown; i++) { + const pingLive = pingWait <= 0; + out.push( + act('crew_ping', { ship: c.ref })} + />, + ); + if (!pingLive) { out.push( - , + + {clock(pingWait)} + , ); + } else if (!locked) { + firstFocus = 'ping'; + } + out.push(); + t0 = by + 3.5; + } else { + const A = end - by - tail; + const fit = Math.max(1, Math.floor((A + 0.25) / BERTH_PITCH)); + const paged = jobs.length > fit; + const per = paged + ? Math.max(1, Math.floor((A - 1) / BERTH_PITCH)) + : jobs.length; + // When every berth fits on one page, the rows share the column: a pitch up to + // BERTH_PITCH_MAX in quarter rows, with the CREWS list's row rule (a half-row gap once the + // pitch reaches 3). + const pitch = paged + ? BERTH_PITCH + : Math.max( + BERTH_PITCH, + Math.min( + BERTH_PITCH_MAX, + Math.floor(((A + 0.25) / Math.max(1, jobs.length)) * 4) / 4, + ), + ); + const gap = pitch >= 3 ? 0.5 : 0.25; + const rowH = pitch - gap; + const tall = rowH >= BERTH_TALL; + const pages = Math.max(1, Math.ceil(jobs.length / per)); + const pg = Math.min(pages, Math.max(1, berthPage)); + const first = (pg - 1) * per; + const shown = jobs.slice(first, first + per); + const turn = (to: number, last = false) => { + if (to < 1 || to > pages || to === pg) { + return false; + } + const at = (to - 1) * per; + const target = last + ? jobs[Math.min(jobs.length - 1, at + per - 1)] + : jobs[at]; + setClaimJob(target ? target.ref : null); + setBerthPage(to); + return true; + }; + const canSign = (job: CrewJob) => + playing && !locked && !!job.ok && rejoinWait <= 0 && !joining; + const firstLive = shown.find(canSign); + if (firstLive) { + firstFocus = 'sign'; } + // The berth rows go in their own layer so the mouse wheel over them turns their page. + const rowsOut: ReactNode[] = []; + shown.forEach((job, i) => { + const yy = by + i * pitch; + const live = canSign(job); + const lit = joining && pressed === job.ref; + const titleCls = locked ? 'faint' : job.ok ? '' : 'dim'; + const claim = claimJob ? claimJob === job.ref : job === firstLive; + // The title stops two cells short of the open count as the count is drawn. On a tall row + // the two go 1.25x together when the whole title fits that large; a title that does not + // keeps both at normal size, so a long title never runs up to a big count. + const openN = String(Math.min(99, Math.max(0, job.open || 0))); + const fullTitle = safe(job.title).toUpperCase(); + const big = + tall && + fullTitle.length * 1.25 <= Math.floor(28 - openN.length * 1.25 - 4.75); + const titleW = Math.min( + TITLE_W, + Math.floor(28 - openN.length * (big ? 1.25 : 1) - 4.75), + ); + const title = cut(fullTitle, titleW); + // The key fills the row, however far the rows stretch. + const keyH = rowH; + rowsOut.push( + , + big ? ( + + ) : ( + + {title} + + ), + // The open count stays in accent on every row, a locked crew's too. Beside a 1.25x title + // it is 1.25x too, still ending at column 28. + big ? ( + + {String(Math.min(99, Math.max(0, job.open || 0)))} + + ) : ( + + {String(Math.min(99, Math.max(0, job.open || 0)))} + + ), + turn(pg + 1) : undefined, + up: i === 0 && paged ? () => turn(pg - 1, true) : undefined, + }} + onClick={() => { + setPressed(job.ref); + act('crew_sign_on', { ship: c.ref, job: job.ref }); + }} + />, + ); + if (lights > 0) { + rowsOut.push( + , + ); + } + }); out.push( - act('crew_sign_on', { ship: c.ref, job: job.ref })} - />, +
{ + if (!paged || !e.deltaY) { + return; + } + const now = Date.now(); + if (now - lastWheel.current < 150) { + return; + } + lastWheel.current = now; + turn(pg + (e.deltaY > 0 ? 1 : -1)); + }} + > + {rowsOut} +
, ); - y += step; - } - if (jobsCut) { + // A page of berths turning wipes the rows only. out.push( - - {`+${c.jobs.length - jobRoom} MORE`} - , + , ); - y += 1; + if (paged) { + out.push( + turn(to)} + />, + ); + t0 = by + per * BERTH_PITCH + 1; + } else { + t0 = by + shown.length * pitch - gap; + } } + // Locked: CODE (and NOTE, or APPLICATION SENT). if (locked) { - out.push(); - y += 2; - const waiting = c.code_wait > 0; + const cy = t0 + 0.25; + const waiting = codeWait > 0; const sendCode = () => { if (!code.trim() || waiting) { return; @@ -275,96 +565,107 @@ export function CrewRecord(props: Props) { setCode(''); }; out.push( - + CODE , - , - , ); - if (waiting && w >= 42) { + if (waiting) { out.push( - - {clock(c.code_wait)} + , + + {`WAIT ${clock(codeWait)}`} , ); + } else { + out.push( + , + ); + if (firstFocus === 'back') { + firstFocus = 'code'; + } } - y += 2; - const sendNote = () => { - act('crew_apply', { ship: c.ref, note }); - setNote(''); - }; out.push( - - NOTE - , - , - ); - y += 2; - out.push( - , ); - } else if (c.applied) { - out.push(); - y += 2; - out.push( - - [ APPLIED ] - , - ); + const ny = cy + 1.75; + out.push(); + if (applied) { + out.push( + + APPLICATION SENT. + , + ); + } else { + const sendNote = () => act('crew_apply', { ship: c.ref, note }); + out.push( + + NOTE + , + , + , + ); + } } - return <>{out}; -} - -/** The record pane with its frame. */ -export function CrewRecordPane(props: Props) { - const { crew, x, w, h } = props; return ( - - - + <> + + {!!stepText && ( + + )} + + {out} + ); } diff --git a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/CrewsTab.tsx b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/CrewsTab.tsx index 9d59fe7c343..208246ac5a6 100644 --- a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/CrewsTab.tsx +++ b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/CrewsTab.tsx @@ -1,254 +1,517 @@ /** - * CREWS tab: one line per crew, and the record of the selected one beside it (or in its - * place on a narrow screen). Package P2. Draws only with the term.tsx primitives; content - * lives between rows TOP and rows - 2 (rows - 1 is the shell's notice line). + * CREWS: every crew signing on, as full blocks when they all fit the box and as two-line + * compact rows otherwise (paged when they overflow). Opening a ship shows its record in place + * of the list. + * + * Main-region rows: box from BOX_Y, body from BODY_Y (columns 1 to 61, bodyRows(M) rows), + * the shell's notice row at M - 1. */ -import { type ReactNode, useState } from 'react'; +import { type ReactNode, useEffect, useMemo, useRef, useState } from 'react'; import { useBackend } from 'tgui/backend'; -import { CrewRecordPane, isLocked } from './CrewRecord'; -import { useBack } from './nav'; -import { Frame, Hit, lpad, Put, pad, TOP, useGrid } from './term'; -import type { Crew, LobbyData } from './types'; +import { CrewRecord, classLine, isLocked } from './CrewRecord'; +import { useScreen } from './motion'; +import { usePager } from './nav'; +import { + Big, + BODY_Y, + BOX_Y, + Box, + bodyRows, + cut, + Key, + NameLine, + Pager, + Put, + RPut, + SEP, + Slab, + safe, + useGrid, + WipeAt, + wrapMax, +} from './term'; +import type { Crew, LobbyData, TabId } from './types'; + +type Status = 'OPEN' | 'LOCKED' | 'APPLIED' | 'FULL'; + +const STATUS_CLS: Record = { + OPEN: '', + LOCKED: 'amb', + APPLIED: 'amb', + FULL: 'dim', +}; + +/** Order groups: own crew, then open, then locked or applied, then full. */ +const STATUS_RANK: Record = { + OPEN: 1, + LOCKED: 2, + APPLIED: 2, + FULL: 3, +}; + +const YOUR_CREW = ' YOUR CREW '; +/** Block text columns 3 to 49; compact line 2 columns 3 to 60. */ +const BLOCK_TEXT_W = 47; +const ROW_TEXT_W = 58; +/** Compact line 1: the name to 46, and always two columns clear of the count and word. */ +const ROW_NAME_W = 46; function openSlots(c: Crew): number { - return c.jobs.reduce((sum, job) => sum + job.open, 0); + return (c.jobs || []).reduce((sum, job) => sum + (job.open || 0), 0); } -/** Status word and its colour, as in the mockup. Open crews show nothing. */ -function status(c: Crew): [string, string] | null { - if (!c.jobs.length) { - return ['FULL', 'red']; - } - if (c.applied) { - return ['APPLIED', 'amb']; +function statusOf(c: Crew): Status { + if (openSlots(c) <= 0) { + return 'FULL'; } if (isLocked(c)) { - return ['LOCKED', 'amb']; + return c.applied ? 'APPLIED' : 'LOCKED'; } - return null; + return 'OPEN'; } -export function CrewsTab() { - const { data } = useBackend(); - const { cols, rows, narrow } = useGrid(); +const count = (n: number) => String(Math.min(999, Math.max(0, n))); + +type Shown = { + c: Crew; + name: string; + status: Status; + open: number; + mine: boolean; +}; + +export function CrewsTab(props: { setTab?: (tab: TabId) => void }) { + const { setTab } = props; + const { data, act } = useBackend(); + const { cols, rows } = useGrid(); const crews = data.crews || []; const [selRef, setSelRef] = useState(null); const [page, setPage] = useState(1); - /** Which row of a new page takes the focus: the last when paging up with the arrow keys. */ - const [enterLast, setEnterLast] = useState(false); + /** The ship that last held the focus; the page follows it when it changes group. */ + const [focRef, setFocRef] = useState(null); + /** The ship whose slab takes the focus when it mounts (paging, following). */ + const [claimRef, setClaimRef] = useState(null); + const lastWheel = useRef(0); + + const sorted: Shown[] = useMemo(() => { + const list = crews.map((c, i) => { + const status = statusOf(c); + const mine = !!c.mine; + return { + c, + i, + name: safe(c.name).toUpperCase(), + status, + open: openSlots(c), + mine, + rank: mine ? 0 : STATUS_RANK[status], + }; + }); + list.sort((a, b) => a.rank - b.rank || a.i - b.i); + return list; + }, [crews]); const selected = crews.find((c) => c.ref === selRef) || null; - const h = rows - 1 - TOP; - // The record's own BACK (CrewRecord) wins while it is open; this only covers a stale selection. - useBack(selected ? () => setSelRef(null) : null); + // The record opens with the wipe and closes with it run back; the ship stepper turns a page. + const selAt = selected + ? sorted.findIndex((x) => x.c.ref === selected.ref) + : -1; + useScreen( + selected ? 'crews/record' : 'crews', + selected ? 1 : 0, + selected ? selected.ref : '', + selAt, + ); + + // The server sends the roster only for the open record: tell it which one, and when it closes. + const openSent = useRef(null); + useEffect(() => { + if (selRef && selRef !== openSent.current) { + act('crew_open', { ship: selRef }); + openSent.current = selRef; + } else if (!selRef && openSent.current) { + act('crew_close'); + openSent.current = null; + } + }, [selRef]); + useEffect( + () => () => { + if (openSent.current) { + act('crew_close'); + } + }, + [], + ); + // A ship that has left closes its record. + useEffect(() => { + if (selRef && !selected) { + setSelRef(null); + } + }, [selRef, !!selected]); + + const n = sorted.length; + const B = bodyRows(rows); + const fullFit = Math.floor((B + 0.25) / 4.75); + const rowFit = Math.floor((B + 0.25) / 2.5); + const form: 'block' | 'row' = n <= fullFit ? 'block' : 'row'; + const per = + form === 'block' + ? Math.max(1, n) + : n <= rowFit + ? rowFit + : Math.max(1, Math.floor((B - 1) / 2.5)); + const pages = Math.max(1, Math.ceil(n / per)); + const pg = Math.min(pages, Math.max(1, page)); + const first = (pg - 1) * per; + const shown = sorted.slice(first, first + per); - if (selected && narrow) { + // The page follows the focused ship when the order moves it to another page. + const focIdx = focRef ? sorted.findIndex((x) => x.c.ref === focRef) : -1; + const lastIdx = useRef(focIdx); + useEffect(() => { + if (focIdx !== lastIdx.current) { + lastIdx.current = focIdx; + if (focIdx >= 0) { + const want = Math.floor(focIdx / per) + 1; + if (want !== pg) { + setClaimRef(focRef); + setPage(want); + } + } + } + }, [focIdx, per]); + + const turn = (to: number, last = false) => { + if (to < 1 || to > pages || to === pg) { + return false; + } + const at = (to - 1) * per; + const target = last ? sorted[Math.min(n - 1, at + per - 1)] : sorted[at]; + setClaimRef(target ? target.c.ref : null); + setPage(to); + return true; + }; + + // PageDown and PageUp turn the page from anywhere in the list. + const listOpen = !selected && pages > 1; + usePager(listOpen ? (step) => turn(pg + step) : null); + + if (selected) { + const at = sorted.findIndex((x) => x.c.ref === selected.ref); + const close = () => { + // Back to the list with that ship focused, on its page. + setClaimRef(selected.ref); + setFocRef(selected.ref); + lastIdx.current = at; + setPage(Math.floor(Math.max(0, at) / per) + 1); + setSelRef(null); + }; return ( - setSelRef(null)} + index={at + 1} + total={n} + onStep={(to) => { + const next = sorted[to - 1]; + if (next) { + setSelRef(next.c.ref); + } + }} + onClose={close} /> ); } - const split = !!selected; - // The mockup splits 64 | 46 at 110 columns. - const lw = split ? Math.round((cols * 64) / 110) : cols; - const showMemo = !split && !narrow; - // Fixed-width columns are placed from the right; the class column takes a share of the rest. - // With the memo column it starts at the mockup's share of the width (column 70 of 126). - const memo = Math.round((cols * 70) / 126); - const st = showMemo ? memo - 10 : lw - 11; - const open = st - (showMemo ? 7 : 6); - const crewCol = open - (showMemo ? 7 : 6); - const name = 3; - const cls = name + Math.min(26, Math.round((crewCol - name) * 0.58)); - - const hy = TOP + 1; - const fit = Math.max(1, h - 3); - const pages = Math.max(1, Math.ceil(crews.length / fit)); - const pg = Math.min(pages, Math.max(1, page)); - const shown = crews.slice((pg - 1) * fit, pg * fit); + // First focus in a running round: the first open ship the player can take a berth on. + const firstPick = + data.phase === 'playing' + ? sorted.find( + (x) => + x.status === 'OPEN' && + !x.c.rejoin_wait && + (x.c.jobs || []).some((j) => !!j.ok), + ) || sorted[0] + : sorted[0]; + const claim = claimRef ?? (firstPick ? firstPick.c.ref : null); const out: ReactNode[] = []; - out.push( - - SHIP - , - - CLASS - , - - CREW - , - - OPEN - , + const box = ( + ); - if (showMemo) { - out.push( - - MEMO - , - ); - } - if (!crews.length) { - out.push( - - {data.phase === 'playing' - ? 'NO CREWS ARE SIGNING ON.' - : 'CREWS SIGN ON ONCE THE PORT OPENS.'} - , + if (!n) { + out.push(); + } else if (form === 'block') { + // Blocks stretch to share the body; any rows left over go between them. + const h = Math.max( + 4.75, + Math.floor(Math.min(7, (B - 0.25 * (n - 1)) / n) * 4) / 4, ); - } - - shown.forEach((c, i) => { - const y = hy + 1 + i; - const isSel = c.ref === selRef; - const k = isSel ? 'inv' : ''; - const slots = openSlots(c); - const stat = status(c); - if (isSel) { + const gap = + n > 1 ? Math.max(0.25, Math.min(0.5, (B - n * h) / (n - 1))) : 0; + shown.forEach((x, i) => { out.push( - - {' '.repeat(Math.max(0, lw - 3))} - , + setSelRef(x.c.ref)} + onFocus={() => setFocRef(x.c.ref)} + />, ); - } - out.push( - - {isSel ? '>' : ' '} - , - - {pad(c.name.toUpperCase(), cls - name - 1)} - , - - {pad(c.cls, crewCol - cls - 1)} - , - - {lpad(c.crew, 3)} - , - - {lpad(slots || '-', 3)} - , + }); + } else { + // Spare rows go into the gaps between rows (quarter steps, 0.25 to 0.75), so the page + // fills down to the pager, or to the body's end on a single page. + const bottom = pages > 1 ? rows - 2.25 - 0.25 : BODY_Y + B; + const slots = Math.max(1, per - 1); + let gap = Math.max( + 0.25, + Math.min( + 0.75, + Math.floor(((bottom - BODY_Y - per * 2.25) / slots) * 4) / 4, + ), ); - if (stat) { - out.push( - - {stat[0]} - , + let rowH = 2.25; + // Fewer ships than a page holds: the rows share the body, as the berth rows do, to a + // pitch of 4 at most (rows 3.5 tall) so a row never looks bloated. + if (pages === 1 && n < per) { + const pitch = Math.max( + 2.5, + Math.min(4, Math.floor(((B + 0.25) / n) * 4) / 4), ); + gap = pitch >= 3 ? 0.5 : 0.25; + rowH = pitch - gap; } - if (showMemo) { + shown.forEach((x, i) => { + const firstRow = i === 0; + const lastRow = i === shown.length - 1; out.push( - - {pad(c.memo, cols - memo - 2)} - , + setSelRef(x.c.ref)} + onFocus={() => setFocRef(x.c.ref)} + edge={{ + down: lastRow ? () => turn(pg + 1) : undefined, + up: firstRow ? () => turn(pg - 1, true) : undefined, + }} + />, ); - } - const firstRow = i === 0; - const lastRow = i === shown.length - 1; + }); out.push( - turn(to)} + />, + // A page turn wipes the rows only. + setSelRef(isSel ? null : c.ref)} - auto={(enterLast ? lastRow : firstRow) ? 1 : undefined} - edge={{ - down: - lastRow && pg < pages - ? () => { - setEnterLast(false); - setPage(pg + 1); - return true; - } - : undefined, - up: - firstRow && pg > 1 - ? () => { - setEnterLast(true); - setPage(pg - 1); - return true; - } - : undefined, - }} + y={BODY_Y} + w={61} + h={bottom - BODY_Y} + k={pg} />, ); - }); + } - if (pages > 1) { - const py = TOP + h - 1; - const label = ` ${pg}/${pages} `; - out.push( - 1 ? 'inv' : 'faint'} - bg={pg <= 1} - onClick={ - pg > 1 - ? () => { - setEnterLast(false); - setPage(pg - 1); - } - : undefined + return ( +
{ + if (pages <= 1 || !e.deltaY) { + return; } - > - {' < '} - , - - {label} - , - = pages} - onClick={ - pg < pages - ? () => { - setEnterLast(false); - setPage(pg + 1); - } - : undefined + const now = Date.now(); + if (now - lastWheel.current < 150) { + return; } + lastWheel.current = now; + turn(pg + (e.deltaY > 0 ? 1 : -1)); + }} + > + {box} + {out} +
+ ); +} + +function CrewBlock(props: { + x: Shown; + y0: number; + h: number; + auto?: number; + onOpen: () => void; + onFocus: () => void; +}) { + const { x, y0, h, auto, onOpen, onFocus } = props; + const { c, name, status, open, mine } = x; + const p = h >= 4.75 ? 0.25 : 0.125; + const line = classLine(c, name); + const lines = Math.max(2, Math.min(4, Math.floor(h - 2.25 - 2 * p))); + const memo = wrapMax(safe(c.memo).trim(), BLOCK_TEXT_W, lines); + const tag = mine ? YOUR_CREW.length + 2 : 0; + const shownLine = cut(line, BLOCK_TEXT_W - tag); + return ( + on && onFocus()} + > + + + {shownLine} + + {!!mine && ( + + {YOUR_CREW} + + )} + {memo.map((text, i) => ( + + {text} + + ))} + {status === 'FULL' ? ( + + FULL + + ) : ( + <> + + {count(open)} + + + {status} + + + )} + + ); +} + +function CrewRow(props: { + x: Shown; + y0: number; + /** Row height, 2.25 unless the rows spread; the two lines stay centred. */ + h?: number; + alt: boolean; + auto?: number; + onOpen: () => void; + onFocus: () => void; + edge: { down?: () => boolean; up?: () => boolean }; +}) { + const { x, y0: top, h = 2.25, alt, auto, onOpen, onFocus, edge } = props; + const y0 = top + (h - 2.25) / 2; + const { c, name, status, open, mine } = x; + const right = status === 'FULL' ? 'FULL' : `${count(open)} ${status}`; + const memo = safe(c.memo).replace(/\s+/g, ' ').trim(); + const tail = [classLine(c, name), memo].filter(Boolean).join(` ${SEP} `); + const tag = mine ? YOUR_CREW.length + 2 : 0; + return ( + on && onFocus()} + > + + {cut(name, Math.min(ROW_NAME_W, 56 - right.length))} + + - {' > '} -
, - ); - } + {right} +
+ {!!mine && ( + + {YOUR_CREW} + + )} + + {cut(tail, ROW_TEXT_W - tag)} + + + ); +} + +const EMPTY_LINE: Record = { + playing: 'NO CREWS ARE SIGNING ON.', + ended: 'PORT CLOSED.', +}; +function EmptyState(props: { phase: string; setTab?: (tab: TabId) => void }) { + const { phase, setTab } = props; + const y0 = BODY_Y; + const line = EMPTY_LINE[phase] || 'CREWS SIGN ON ONCE THE PORT OPENS.'; return ( - <> - - {out} - - {!!selected && ( - setSelRef(null)} + + + {phase === 'playing' && !!setTab && ( + setTab('shipyard')} /> )} - + ); } diff --git a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/Emblem.tsx b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/Emblem.tsx new file mode 100644 index 00000000000..9734fd8b8d1 --- /dev/null +++ b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/Emblem.tsx @@ -0,0 +1,102 @@ +/** + * The Voidcrew symbol at rest: the finished mark with its orbit ring slowly turning. + * + * 64 art pixels square, drawn 128 CSS px square + * one frame, no animation + * + * Props: + * size canvas side in art pixels (default 64; the design is scaled to fit it) + * px CSS pixels per art pixel. Use a whole number of device pixels (the bezel scale + * `layout.s`, or a multiple of it) so the pixels stay square and sharp. Default 1. + * speed how fast the ring's highlight travels, in radians per second (default 0.5) + * fps redraws per second (default 12). It only redraws while the page is showing. + * still draw once and stop + * style merged onto the canvas; position it from the caller (it is a plain inline block) + * + * It takes no input and has no focus. The drawing itself is emblemDraw.ts. + */ +import { type CSSProperties, useEffect, useRef } from 'react'; + +import { renderEmblem } from './emblemDraw'; + +/** Redraws per second at rest. */ +export const EMBLEM_FPS = 12; +/** Design scale that fits the whole symbol (ring, moon and glint) in a `size` px canvas. */ +export const emblemScale = (size: number) => (size * 0.62) / 64; + +export function Emblem(props: { + size?: number; + px?: number; + speed?: number; + fps?: number; + still?: boolean; + className?: string; + style?: CSSProperties; +}) { + const { + size = 64, + px = 1, + speed = 0.5, + fps = EMBLEM_FPS, + still, + className, + style, + } = props; + const ref = useRef(null); + + useEffect(() => { + const canvas = ref.current; + if (!canvas) { + return; + } + const k = emblemScale(size); + const draw = (t: number) => { + try { + renderEmblem(canvas, { + t, + k, + grow: 1, + yaw: 0, + v: true, + ring: t * speed, + hud: 0, + }); + } catch { + // A canvas the browser won't draw is left blank; the lobby works without the symbol. + } + }; + if (still) { + draw(1); + return; + } + let raf = 0; + let last = -1; + const frame = (now: number) => { + const step = Math.floor((now / 1000) * fps); + if (step !== last) { + last = step; + draw(step / fps); + } + raf = requestAnimationFrame(frame); + }; + raf = requestAnimationFrame(frame); + return () => cancelAnimationFrame(raf); + }, [size, speed, fps, still]); + + return ( + + ); +} diff --git a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/Fit.tsx b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/Fit.tsx index b3326e9f996..9daab5975ab 100644 --- a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/Fit.tsx +++ b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/Fit.tsx @@ -1,450 +1,720 @@ /** - * FIT: the finish, then each module slot. Wide: the step list with the running total and - * crew on the left, the viewscreen and this step's options on the right. Narrow: the - * viewscreen above the options, PREV/NEXT between steps. + * FIT (spec 02, 3.5): one step a page. FINISH when the hull has finishes, then one step a room + * the taken finish offers. Each page: the picture with the current room marked and the steps + * column beside it, this step's options as slab rows, the shown option's description, the + * total strip in the class columns, PREV and NEXT. + * + * Shown is not taken. Each step has one option TAKEN (in the store: `[#]`, the slab `on`). The + * option SHOWN is the focused one while the focus is on an option row, else the taken one; it + * is local here. The picture and the description read the shown option; the total, the `[#]` + * and the commission read the taken one (ctx.fit and ctx.bill). Enter or a click takes an + * option; on the option already taken it goes to the next step (the bill after the last). + * + * Three regimes by body height B = M - 4.25: normal (B >= 18), small (14.75 <= B < 18, a 6-row + * picture) and tight (B < 14.75, no picture, the steps in two columns). The layout is worked out + * once a hull from its largest step and longest text, so nothing moves between steps. */ -import { type ReactNode, useEffect, useState } from 'react'; +import { type ReactNode, useMemo, useRef, useState } from 'react'; +import { sfxInstead } from './motion'; +import { usePager } from './nav'; import { ShipPic } from './ShipPic'; import { + bodyRows, + BODY_Y, + Box, + BOX_Y, + ClassFigures, + ClassHeads, cut, - Frame, - Hit, - lpad, + Key, + Pager, Put, - pad, RPut, - Rule, - TOP, + Slab, + safe, useGrid, + WipeAt, wrap, + wrapMax, } from './term'; -import type { CrewLine, Finish, Hull, Module } from './types'; +import type { Hull, Parts } from './types'; import { billOf, - costOf, - crewOf, + crewCount, + crewText, finishOwned, fitOf, - Key, moduleOwned, + PART_ORDER, partsOf, + priceText, type ShipFit, + slotOptions, + stockFit, usePreview, type YardCtx, } from './YardTab'; +/** Rounds down to a quarter row. */ +const f4 = (v: number) => Math.floor(v * 4) / 4; +const clamp = (v: number, lo: number, hi: number) => + Math.max(lo, Math.min(hi, v)); + +/** Body columns 1 to 61. */ +const W = 61; +/** An option's name: columns 7 to 32. */ +const NAME_W = 26; +/** An option's tag ends on column 60; at most 26 cells. */ +const TAG_END = 61; +const TAG_W = 26; + +type Opt = { + id: string; + name: string; + desc: string; + tag: string; + tagCls: 'dim' | 'amb'; +}; + type Step = { label: string; - /** Finish step, or the slot key. */ + /** The room's slot key, or null for FINISH. */ slot: string | null; - opts: (Finish | Module)[]; - pick: number; + opts: Opt[]; + /** The option taken on this step. */ + taken: string | null; }; -function jobsText(jobs: CrewLine[]): string { - return jobs.map(([t, n]) => (n > 1 ? `${t} x${n}` : t)).join(', '); +/** `STOCK`, `OWNED` (dim) or the price (amber), as the option row shows it. */ +function tagOf( + stock: boolean, + owned: boolean, + cost: Parts | null | undefined, +): [string, 'dim' | 'amb'] { + if (stock || !partsOf(cost)) { + return ['STOCK', 'dim']; + } + if (owned) { + return ['OWNED', 'dim']; + } + return [priceText(cost, TAG_W), 'amb']; } -function stepsOf(fit: ShipFit): Step[] { +function stepsOfFit(ctx: YardCtx, hull: Hull, taken: ShipFit): Step[] { const steps: Step[] = []; - const { hull, finish } = fit; if (hull.finishes.length) { steps.push({ label: 'FINISH', slot: null, - opts: hull.finishes, - pick: Math.max( - 0, - hull.finishes.findIndex((f) => f.id === finish?.id), - ), + taken: taken.finish?.id ?? null, + opts: hull.finishes.map((f) => { + const [tag, tagCls] = tagOf( + !!f.def, + finishOwned(ctx.own, hull, f), + f.cost, + ); + return { + id: f.id, + name: safe(f.name).toUpperCase(), + desc: safe(f.desc), + tag, + tagCls, + }; + }), }); } - for (const s of fit.slots) { + for (const sl of taken.slots) { steps.push({ - label: s.label, - slot: s.key, - opts: s.options, - pick: Math.max( - 0, - s.options.findIndex((m) => m.id === s.pick?.id), - ), + label: safe(sl.label), + slot: sl.key, + taken: sl.pick?.id ?? null, + opts: sl.options.map((m) => { + const [tag, tagCls] = tagOf( + !!m.def, + moduleOwned(ctx.own, hull, m), + m.cost, + ); + return { + id: m.id, + name: safe(m.name).toUpperCase(), + desc: safe(m.desc), + tag, + tagCls, + }; + }), }); } return steps; } +/** ` BERTHS` in white, two spaces, the jobs dim, wrapped to at most `max` lines of 61. */ +function crewLines(fit: ShipFit, max: number) { + const head = `${crewCount(fit)} BERTHS`; + const jobs = safe(crewText(fit)); + // A stand-in word as wide as the head plus one, so the first line keeps two spaces after it. + const lead = 'x'.repeat(head.length + 1); + const text = jobs ? `${lead} ${jobs}` : lead; + return { + head, + lead, + need: wrap(text, W).length, + lines: max > 0 ? wrapMax(text, W, max) : [], + }; +} + +/** The most options on any step of a hull, every finish counted, and the longest text. */ +function measure(hull: Hull) { + let nOpt = hull.finishes.length; + let lines = 0; + const finishes = hull.finishes.length ? hull.finishes : [null]; + for (const f of finishes) { + const keys = f ? f.slots : hull.slots.map((s) => s.key); + for (const key of keys) { + nOpt = Math.max(nOpt, slotOptions(hull, key, f).length); + } + } + for (const m of hull.modules) { + lines = Math.max(lines, wrap(safe(m.desc), W).length); + } + for (const f of hull.finishes) { + const crew = crewLines(fitOf(hull, f.id, {}), 2).need; + lines = Math.max( + lines, + wrap(safe(f.desc), W).length + Math.min(2, crew), + ); + } + return { nOpt: Math.max(1, nOpt), Dwant: Math.min(8, lines) }; +} + +type Regime = { + kind: 'normal' | 'small' | 'tight'; + /** Picture rows (0 when tight). */ + T: number; + /** Steps rows when tight. */ + S: number; + /** Option pitch. */ + po: number; + /** Option rows on a page. */ + rowsO: number; + /** The options page (a Pager row under them). */ + paged: boolean; + /** Description lines. */ + D: number; +}; + +/** + * The body ends a quarter row above the other screens' (LIFT): the total strip sits that much + * higher, so its figure row keeps half a row clear of the box bottom. The regime is still + * chosen on the whole body; the quarter row comes out of the picture. + */ +const LIFT = 0.25; + +function regimeOf( + Bfull: number, + nOpt: number, + Dwant: number, + steps: number, +): Regime { + const B = Bfull - LIFT; + if (Bfull >= 18) { + let po = 1.75; + let D = Dwant; + let T = B - 3 - nOpt * po - D; + let rowsO = nOpt; + let paged = false; + if (T < 8.5) { + po = 1; + T = B - 3 - nOpt - D; + } + if (T < 8.5) { + D = Math.max(2, D - Math.ceil(8.5 - T)); + T = B - 3 - nOpt - D; + } + if (T < 8.5) { + T = 8.5; + rowsO = Math.floor(B - 12.5 - D); + paged = true; + } + return { kind: 'normal', T: f4(T), S: 0, po, rowsO, paged, D }; + } + let kind: Regime['kind']; + let T = 0; + let S = 0; + let rowsO: number; + let D: number; + if (Bfull >= 14.75) { + kind = 'small'; + T = 6 - LIFT; + rowsO = Math.min(nOpt, Math.floor(Bfull - 10.75)); + D = Math.floor(Bfull - 8.75 - rowsO); + } else { + kind = 'tight'; + S = Math.ceil(steps / 2); + rowsO = Math.min(nOpt, Math.floor(B - 3.75 - S)); + D = Math.floor(B - 2.75 - S - rowsO); + } + const paged = nOpt > rowsO; + if (paged) { + // The pager takes one of the description's rows; keep two lines of description. + D -= 1; + if (D < 2) { + rowsO = Math.max(1, rowsO - (2 - D)); + D = 2; + } + } + return { kind, T, S, po: 1, rowsO, paged, D }; +} + export function Fit(props: { ctx: YardCtx; hull: Hull }) { const { ctx, hull } = props; - const { view, set, own } = ctx; - const { cols, rows, narrow } = useGrid(); + const { rows } = useGrid(); usePreview(hull.id); - const h = rows - 1 - TOP; - const fit = fitOf(hull, view.finish, view.picks); - const steps = stepsOf(fit); - /** First option row shown when a step has more options than rows, and the row to focus. */ - const [win, setWin] = useState<{ st: number; top: number; want: number }>({ - st: -1, - top: 0, - want: -1, + const M = rows; + const B = bodyRows(M); + + // Taken: the store's fit of this hull. + const taken: ShipFit = + ctx.fit && ctx.fit.hull.id === hull.id ? ctx.fit : stockFit(hull); + const bill = + ctx.bill && ctx.fit && ctx.fit.hull.id === hull.id + ? ctx.bill + : billOf(ctx.own, taken, ctx.account); + const steps = stepsOfFit(ctx, hull, taken); + const n = steps.length; + const at = clamp(ctx.view.step, 0, Math.max(0, n - 1)); + const step: Step | undefined = steps[at]; + const last = at >= n - 1; + + const { nOpt, Dwant } = useMemo(() => measure(hull), [hull]); + const rg = regimeOf(B, nOpt, Dwant, n); + /** Options taken so far on this screen: each one is shown being fitted in the picture. */ + const [took, setTook] = useState(0); + const lastWheel = useRef(0); + + // Local: the option focused (shown), the options page, and focus claims. Reset a step. + const stepKey = `${hull.id}:${at}`; + const [loc, setLoc] = useState({ + key: stepKey, + focus: null as string | null, + page: 0, + claim: null as string | null, + toSteps: 0, + toNext: 0, }); - // Nothing to fit (no finishes, no rooms): show the bill instead of a blank screen. - useEffect(() => { - if (!steps.length) { - set({ screen: 'bill' }); + let cur = loc; + if (loc.key !== stepKey) { + cur = { + key: stepKey, + focus: null, + page: 0, + claim: null, + toSteps: 0, + toNext: 0, + }; + setLoc(cur); + } + + const opts = step ? step.opts : []; + const per = Math.max(1, rg.rowsO); + const pages = Math.max(1, Math.ceil(opts.length / per)); + const takenAt = Math.max( + 0, + opts.findIndex((o) => o.id === step?.taken), + ); + // Entering a step: the page holding the option taken. + const page = clamp(cur.page || Math.floor(takenAt / per) + 1, 1, pages); + const pageOpts = opts.slice((page - 1) * per, page * per); + const claim = cur.claim ?? step?.taken ?? null; + + const shownId = + cur.focus && opts.some((o) => o.id === cur.focus) + ? cur.focus + : step?.taken ?? null; + const shownOpt = opts.find((o) => o.id === shownId) || null; + const takenFinish = taken.finish?.id ?? null; + const picks: Record = {}; + for (const sl of taken.slots) { + if (sl.pick) { + picks[sl.key] = sl.pick.id; } - }, [steps.length]); - if (!steps.length) { - return null; } - const st = Math.min(steps.length - 1, Math.max(0, view.step)); - const S = steps[st]; - const bill = billOf(own, fit, ctx.account); - const crew = crewOf(fit); - const crewN = crew.reduce((a, l) => a + l[1], 0); - const out: ReactNode[] = []; + let shownFit: ShipFit = taken; + if (step && shownId && shownId !== step.taken) { + shownFit = + step.slot === null + ? fitOf(hull, shownId, picks) + : fitOf(hull, takenFinish, { ...picks, [step.slot]: shownId }); + } - const ownedOpt = (o: Finish | Module) => - S.slot === null - ? finishOwned(own, hull, o as Finish) - : moduleOwned(own, hull, o as Module); - const choose = (j: number) => { - const o = S.opts[j]; - if (S.slot === null) { - set({ finish: o.id }); - } else { - set({ picks: { ...view.picks, [S.slot]: o.id } }); + const goStep = (i: number) => { + if (i >= n) { + ctx.go.bill(); + } else if (i >= 0) { + ctx.go.fit(i); } }; - const last = st === steps.length - 1; - const next = () => (last ? set({ screen: 'bill' }) : set({ step: st + 1 })); + const take = (o: Opt) => { + if (!step) { + return; + } + if (o.id === step.taken) { + goStep(at + 1); + return; + } + // The part seating, in place of the key press; the picture shows it going in. + sfxInstead('slot'); + setTook((t) => t + 1); + const slot = step.slot; + ctx.set((v) => { + const mine = v.fitHull === hull.id; + const base = mine ? v.picks : {}; + return slot === null + ? { fitHull: hull.id, finish: o.id, picks: base } + : { + fitHull: hull.id, + finish: mine ? v.finish : takenFinish, + picks: { ...base, [slot]: o.id }, + }; + }); + }; + const turn = (to: number, claimId: string | null) => { + setLoc((l) => ({ ...l, page: to, claim: claimId })); + return true; + }; - const x = narrow - ? 0 - : Math.min(48, Math.max(34, Math.floor(cols * 0.36))) + 1; - const w = cols - x; - const lw = x - 1; + // PageDown / PageUp: NEXT / PREV. + usePager((d) => { + if (!ctx.view.leave) { + goStep(d > 0 ? at + 1 : at > 0 ? at - 1 : -1); + } + }); - // The viewscreen takes what the busiest step's options leave, so it doesn't jump. - const descRows = (o: Finish | Module) => - Math.min(2, wrap(o.desc, w - 6).length); - const need = - Math.max( - ...steps.map((s) => { - let n = s.opts.length + Math.max(0, ...s.opts.map(descRows)); - if (s.slot === null) { - n += Math.max( - 0, - ...s.opts.map( - (o) => - Math.min(2, wrap(jobsText((o as Finish).jobs), w - 12).length) + - 1, - ), - ); - } - return n; - }), - ) + (narrow ? 7 : 6); - const ph = Math.max(narrow ? 6 : 9, Math.min(Math.floor(h * 0.62), h - need)); + const out: ReactNode[] = []; + out.push( + , + ); - if (!narrow) { - // Step list, total and crew. - out.push( - { + const on = i === at; + return ( + , + alt={alt} + on={on} + auto={on && cur.toSteps > 0 ? 3 : undefined} + onClick={() => goStep(i)} + > + + {cut(s.label.toUpperCase(), w - 3)} + + ); - // Two rows a step when there is room, one when not; past that, a window round this step. - const pitch = TOP + 2 + steps.length * 2 + 8 <= TOP + h ? 2 : 1; - const stepRoom = Math.max(1, Math.floor((h - 10) / pitch)); - const from = Math.max( - 0, - Math.min(steps.length - stepRoom, st - Math.floor(stepRoom / 2)), + }; + + // The picture and the steps. + if (rg.kind !== 'tight') { + out.push( + , ); - let y = TOP + 2; - steps.slice(from, from + stepRoom).forEach((s, n) => { - const i = from + n; - const o = s.opts[s.pick]; - const cur = i === st; - const paid = - !!o && - !(s.slot === null - ? finishOwned(own, hull, o as Finish) - : moduleOwned(own, hull, o as Module)); - if (cur) { - out.push( - - {' '.repeat(lw - 3)} - , - ); - } + // Spec 3.5 caps the pitch at 1.75; a tall picture left the column half empty, so it + // runs to 2.25 (the slab 2 rows, its label centred). + const ps = rg.kind === 'small' ? 1 : clamp(f4(rg.T / n), 1, 2.25); + const sh = ps < 1.25 ? 1 : ps - 0.25; + const vis = Math.min(n, Math.max(1, Math.floor((rg.T + 0.25) / ps))); + const first = clamp(at - Math.floor(vis / 2), 0, n - vis); + for (let j = 0; j < vis; j++) { + const i = first + j; out.push( - - {cur ? '>' : ' '} - , - - {pad(s.label, 14)} - , - - {pad(o ? o.name : '-', lw - 21)} - , - set({ step: i })} - />, + stepRow( + steps[i], + i, + 40, + BODY_Y + j * ps, + 22, + sh, + ps < 1.25 && j % 2 === 1, + ), ); - y += pitch; - }); - if (pitch === 1) { - y++; } - out.push(); - const tot = costOf(bill.total) || 'NOTHING DUE'; - const totLines = wrap(tot, lw - 13); - const short = Object.keys(bill.short).length > 0; - out.push( - - TOTAL - , + } else { + for (let i = 0; i < n; i++) { + const col = i < rg.S ? 0 : 1; + const row = col ? i - rg.S : i; + out.push( + stepRow( + steps[i], + i, + col ? 32 : 1, + BODY_Y + row, + 30, + 1, + row % 2 === 1, + ), + ); + } + } + + // The options. + const yO = BODY_Y + 0.25 + (rg.kind === 'tight' ? rg.S : rg.T); + const oh = rg.po === 1.75 ? 1.5 : 1; + const optRows: ReactNode[] = []; + pageOpts.forEach((o, j) => { + const y = yO + j * rg.po; + const isTaken = o.id === step?.taken; + const first = j === 0; + const lastRow = j === pageOpts.length - 1; + const ty = y + (oh - 1) / 2; + optRows.push( + take(o)} + onFocus={(f) => + setLoc((l) => + f + ? { ...l, focus: o.id } + : l.focus === o.id + ? { ...l, focus: null } + : l, + ) + } + edge={{ + // Up from the first row: the page before, or on the first page the step being + // fitted (not whichever step row happens to sit nearest above). + up: () => { + if (!first) { + return false; + } + if (page > 1) { + return turn(page - 1, opts[(page - 1) * per - 1].id); + } + setLoc((l) => ({ ...l, toSteps: l.toSteps + 1 })); + return true; + }, + down: () => { + if (!lastRow) { + return false; + } + if (page < pages) { + return turn(page + 1, opts[page * per].id); + } + setLoc((l) => ({ ...l, toNext: l.toNext + 1 })); + return true; + }, + right: () => { + setLoc((l) => ({ ...l, toSteps: l.toSteps + 1 })); + return true; + }, + }} + > + + {isTaken ? '[#]' : '[ ]'} + + + {cut( + o.name, + // The row's free width: up to two cells before the tag. + Math.max(NAME_W, TAG_END - Math.min(TAG_W, o.tag.length) - 9), + )} + + + {cut(o.tag, TAG_W)} + + , ); - totLines.forEach((l, i) => { + }); + // The mouse wheel over the options turns their page, as the pager does. + out.push( +
{ + if (pages <= 1 || !e.deltaY) { + return; + } + const now = Date.now(); + if (now - lastWheel.current < 150) { + return; + } + lastWheel.current = now; + const to = page + (e.deltaY > 0 ? 1 : -1); + if (to >= 1 && to <= pages) { + turn(to, opts[(to - 1) * per].id); + } + }} + > + {optRows} +
, + ); + let yD = yO + rg.rowsO * rg.po + 0.25; + if (rg.paged) { + if (pages > 1) { out.push( - - {l} - , + turn(p, opts[(p - 1) * per].id)} + />, ); - }); - let cy = y + 3 + Math.max(0, totLines.length - 1); - const stop = TOP + h - 4; - if (cy + 2 < stop) { + } + yD += 1; + } + + // The description of the shown option; on FINISH, the crew it brings under it. + if (shownOpt) { + let lines: string[] = []; + let crew: ReturnType | null = null; + if (step?.slot === null) { + const need = crewLines(shownFit, 2).need; + const c = Math.max(0, Math.min(2, need, rg.D - 1)); + crew = crewLines(shownFit, c); + lines = shownOpt.desc ? wrapMax(shownOpt.desc, W, rg.D - c) : []; + } else { + lines = shownOpt.desc ? wrapMax(shownOpt.desc, W, rg.D) : []; + } + let y = yD; + lines.forEach((line, i) => { out.push( - - CREW - , - - {String(crewN)} + + {line} , ); - cy += 2; - if (cy + crew.length <= stop) { - crew.forEach(([job, n], i) => { + y += 1; + }); + if (crew) { + crew.lines.forEach((line, i) => { + if (i === 0) { out.push( - - {pad(job, lw - 10)} + + {crew.head} , - - {lpad(n, 2)} + + {line.slice(crew.lead.length).trimStart()} , ); - }); - } + } else { + out.push( + + {line} + , + ); + } + y += 1; + }); } - out.push( - set({ screen: 'bill' })} - />, - ); } - // Viewscreen. + // A step change, and a page of options turning, wipe the options and the description only: + // the picture and the steps stay, with the marker on the new room. + const yK = M - 3.25; out.push( - , - , ); - // This step's options. - const oy = TOP + ph; - const oh = h - ph; - const title = narrow ? `${S.label} ${st + 1}/${steps.length}` : S.label; - out.push(); - let y = oy + 2; - const tagW = 18; - const by = oy + oh - 2; - // Options get the rows above the keys less two for the description; more scroll. - const optRows = Math.max(1, by - (narrow ? 2 : 1) - y - 2); - const many = S.opts.length > optRows; - let top = 0; - if (many) { - top = - win.st === st - ? win.top - : Math.max(0, Math.min(S.pick, S.opts.length - optRows)); - top = Math.max(0, Math.min(S.opts.length - optRows, top)); - out.push( - - {` ${top + 1}-${top + optRows}/${S.opts.length} `} - , - ); - } - const scroll = (to: number, want: number) => { - setWin({ st, top: to, want }); - return true; - }; - const shownOpts = S.opts.slice(top, top + optRows); - shownOpts.forEach((o, n) => { - const j = top + n; - const sel = j === S.pick; - const firstRow = n === 0; - const lastRow = n === shownOpts.length - 1; - const focusHere = win.st === st && win.want >= 0 ? win.want === j : sel; - const owned = ownedOpt(o); - if (sel) { - out.push( - - {' '.repeat(w - 3)} - , - ); + // The total strip: what the fit as taken costs now, in set F. + const yT = yK - LIFT; + const due = partsOf(bill.total) > 0; + if (due) { + const short = ctx.ledger === 'ok' ? bill.short : {}; + const cls: Record = {}; + for (const k of PART_ORDER) { + cls[k] = (short[k] || 0) > 0 ? 'inva' : 'amb'; } - const tag = cut(o.def ? 'STOCK' : owned ? 'OWNED' : costOf(o.cost), tagW); out.push( - - {sel ? '>' : ' '} - , - - {pad(o.name, w - 6 - Math.min(tagW, tag.length + 2))} + + TOTAL , - - {tag} - , - choose(j)} - auto={focusHere ? 1 : undefined} - edge={{ - down: - lastRow && j < S.opts.length - 1 - ? () => scroll(top + 1, j + 1) - : undefined, - up: firstRow && j > 0 ? () => scroll(top - 1, j - 1) : undefined, - }} + , + , ); - y++; - }); - y++; - const o = S.opts[S.pick]; - if (o) { - const jl = - S.slot === null ? wrap(jobsText((o as Finish).jobs), w - 12) : []; - const rowsFree = - by - (narrow ? 2 : 1) - y - (jl.length ? jl.length + 1 : 0); - wrap(o.desc, w - 6) - .slice(0, Math.max(1, rowsFree)) - .forEach((l, i) => { - out.push( - - {l} - , - ); - }); - if (jl.length) { - y++; - out.push( - - CREW - , - ); - jl.slice(0, Math.max(1, by - (narrow ? 2 : 1) - y)).forEach((l, i) => { - out.push( - - {l} - , - ); - }); - } - } - if (narrow) { - const tot = costOf(bill.total); - const short = Object.keys(bill.short).length > 0; + } else { out.push( - - {`CREW ${crewN}`} + + NOTHING DUE , - ); - if (tot) { - out.push( - - {tot.slice(0, w - 15)} - , - ); - } - if (!last) { - out.push( - set({ screen: 'bill' })} - />, - ); - } - } - if (st > 0) { - out.push( - set({ step: st - 1 })} - />, + // Kept mounted (empty), so the first figure due flashes as it appears. + , ); } out.push( 0 ? 'idle' : 'dead'} + onClick={() => goStep(at - 1)} + />, + 0 ? 3 : undefined} + onClick={() => goStep(at + 1)} />, ); diff --git a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/Header.tsx b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/Header.tsx index d5ee44996ed..e7f158ea5a8 100644 --- a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/Header.tsx +++ b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/Header.tsx @@ -1,9 +1,14 @@ -import { useEffect, useState } from 'react'; +import { Fragment, useEffect, useState } from 'react'; import { useBackend } from 'tgui/backend'; -import { cut, Put, pad, RPut, Rule, useGrid } from './term'; +import { sfx, useChanged } from './motion'; +import { Band, cut, Hit, HRule, Put, RPut, useGrid } from './term'; import type { LobbyData, TabId } from './types'; +/** + * The screens in keyboard order: 1 to 4 and Tab step through them. Only the first three are + * tabs; CHARACTER is opened from the menu and lights no tab. + */ export const TABS: [TabId, string][] = [ ['crews', 'CREWS'], ['shipyard', 'SHIPYARD'], @@ -56,65 +61,129 @@ function clockText(data: LobbyData, elapsed: number): string { } } -/** Title bar (row 0), tab bar (row 2) and its rule (row 3). */ -export function Header(props: { tab: TabId; setTab: (tab: TabId) => void }) { - const { tab, setTab } = props; +/** The departure clock's last seconds: the clock ticks and turns amber every other second. */ +const LAST_SECONDS = 10; + +/** + * Header band (its own region, 1.5 rows): BERTH OFFICE at column 2, the counts and the clock + * ending at column cols - 3. The clock and the admin counts always draw; the title gives way + * whole, then the online count. + * + * In the last ten seconds before departure the clock is amber and white in turn, with a tick + * a second that rises in pitch; DEPARTING blinks three times when it appears. + */ +export function HeaderBand() { const { data } = useBackend(); - const { cols, narrow } = useGrid(); + const { cols } = useGrid(); const elapsed = useElapsed(data.clock); - - const title = data.port - ? ` ${data.port.toUpperCase()} : BERTH OFFICE` - : ' BERTH OFFICE'; - let right = clockText(data, elapsed); - if (data.phase !== 'playing' || !narrow) { - right = `${data.online} ONLINE ${right}`; - } - if (data.admin_ready) { - const [ready, admins, adminTotal] = data.admin_ready; - right = `${ready} READY ${admins}/${adminTotal} ADM ${right}`; + const clock = clockText(data, elapsed); + const counting = + (data.phase === 'loading' || data.phase === 'pregame') && data.clock > 0; + const left = counting ? Math.max(0, Math.floor(data.clock - elapsed)) : -1; + const last = left > 0 && left <= LAST_SECONDS ? left : 0; + useChanged(last, (_, now) => { + if (now > 0) { + sfx('clock', { rate: 1 + (LAST_SECONDS - now) * 0.05 }); + } + }); + const departing = data.phase === 'setup'; + const clockCls = `lt-clock ${last % 2 === 1 ? 'amb' : 'wht'} nog${departing ? ' lt-blink3' : ''}`; + const admin = data.admin_ready + ? `${data.admin_ready[0]} READY ${data.admin_ready[1]}/${data.admin_ready[2]} ADM` + : ''; + const online = `${data.online} ONLINE`; + const room = cols - 4; + const join = (parts: string[]) => parts.filter(Boolean).join(' '); + let right = join([admin, online, clock]); + let title = 'BERTH OFFICE'; + if (title.length + 3 + right.length > room) { + title = ''; } - - if (right.length > cols - 2) { - right = right.slice(right.length - Math.max(0, cols - 2)); + if (right.length > room) { + right = join([admin, clock]); } - // The port name gives way to the clock: cut it, never run it under the right-hand text. - const titleText = cut(title, Math.max(0, cols - right.length - 3)); - - let x = 1; - const tabs = TABS.map(([id, label]) => { - const text = ` ${label} `; - const at = x; - x += text.length + 3; - return ( - setTab(id)} - tab + // The clock is its own piece of text, so it can change colour and blink by itself. + const whole = right.length <= room && right.endsWith(clock); + const before = whole ? right.slice(0, right.length - clock.length) : ''; + return ( + <> + + {!!title && ( + + {title} + + )} + {!!before && ( + + {before} + + )} + - {text} - - ); - }); + {whole ? clock : cut(right, room)} + + + ); +} + +/** Tab blocks in main-region columns: [first column, width]. */ +const TAB_BLOCKS: Partial> = { + crews: [0, 7], + shipyard: [8, 10], + housing: [19, 9], +}; +/** + * Tab row at the top of the main region (rows 0 to 1.5) and the rule under it. While the + * CHARACTER screen is open no tab is lit. `claim`: the open tab claims the first focus at that + * priority (nav.tsx FocusOpts.auto). + */ +export function TabRow(props: { + tab: TabId; + setTab: (tab: TabId) => void; + claim?: number; +}) { + const { tab, setTab, claim } = props; + const { cols } = useGrid(); + /** The tab under the focus, drawn in the body colour. */ + const [lit, setLit] = useState(null); return ( <> - {/* One lit bar in three pieces that meet but never overlap: title, clock, end cell. */} - - {pad(titleText, Math.max(0, cols - 1 - right.length))} - - - {right} - - - {' '} - - {tabs} - + {TABS.map(([id, label]) => { + const block = TAB_BLOCKS[id]; + if (!block) { + return null; + } + const [bx, bw] = block; + const open = id === tab; + return ( + + {!!open && } + + {label} + + {/* The whole block is the click target, and the focus ring frames the block. */} + setTab(id)} + onHover={(over) => + setLit((was) => (over ? id : was === id ? null : was)) + } + auto={open ? claim : undefined} + entry={open} + tab + /> + + ); + })} + ); } diff --git a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/HousingTab.tsx b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/HousingTab.tsx index 116313162cc..593bc51b7fc 100644 --- a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/HousingTab.tsx +++ b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/HousingTab.tsx @@ -1,231 +1,444 @@ /** - * HOUSING tab: player outposts taking residents (DM: lobby_housing.dm). - * Draws only with the term.tsx primitives. + * HOUSING: player outposts taking residents (DM: lobby_housing.dm), as blocks like the CREWS + * list. Everything a player can do is on the outpost's block: the word says how it admits, the + * key moves in or asks, a code outpost has its field beside the key. Paged when the blocks + * would get shorter than 3.75 rows. + * + * Main-region rows: box from BOX_Y, body from BODY_Y (columns 1 to 61, bodyRows(M) rows), the + * shell's notice row at M - 1. */ -import { Fragment, type ReactNode, useState } from 'react'; +import { type ReactNode, useEffect, useRef, useState } from 'react'; import { useBackend } from 'tgui/backend'; +import { sfx, useChanged, useScreen } from './motion'; +import { usePager } from './nav'; import { - Blocks, - Btn, - type Cls, + BODY_Y, + BOX_Y, + Band, + Big, + Box, + bodyRows, + cut, Field, - Frame, + FlashAt, + Key, + NameLine, + Pager, Put, - Rule, - TOP, + Slab, + safe, useGrid, + WipeAt, + wrapMax, } from './term'; import type { LobbyData, Outpost, OutpostMode } from './types'; -const MODES: Record = { - open: ['OPEN', ''], +/** Name: 1.25x to 36 characters, normal size to 45, two lines past that on a tall block. */ +const NAME_W = 45; +/** Every key on a block: `[ MOVE IN ]` or `[ REQUEST ]`, centred in 12 columns. */ +const KEY_X = 49; +const KEY_W = 12; +/** The code field, columns 24 to 46. */ +const FIELD_X = 24; +const FIELD_W = 23; +const CODE_MAX = 64; +/** A sent move-in keeps the key dead this long, or until the notice changes. */ +const SENT_MS = 4000; + +const f4 = (v: number) => Math.floor(v * 4) / 4; + +const WORD: Record = { + open: ['OPEN', 'acc'], password: ['CODE', 'amb'], approved: ['INVITE', 'amb'], - closed: ['CLOSED', 'red'], + closed: ['CLOSED', 'dim'], +}; + +type Act = 'move' | 'code' | 'request' | 'none'; + +type View = { + word: string; + wordCls: string; + act: Act; + /** The reason drawn on the block, amber. */ + why: string; }; -/** Cuts a name to n cells, ending a cut in '.'. */ -function cutName(name: string, n: number): string { - return name.length <= n ? name : `${name.slice(0, n - 1).trimEnd()}.`; +/** The block's word, its key and its reason (design 02, 4.3). */ +function viewOf(o: Outpost): View { + const why = o.blocked ? safe(o.why).trim().toUpperCase() : ''; + if (o.mode === 'closed') { + return { word: 'CLOSED', wordCls: 'dim', act: 'none', why: '' }; + } + const mode: OutpostMode = o.cleared ? 'open' : o.mode; + const [word, wordCls] = WORD[mode] || WORD.closed; + if (why) { + return { word, wordCls: 'dim', act: 'none', why }; + } + if (mode === 'approved' && o.asked) { + return { word: 'ASKED', wordCls: 'amb', act: 'none', why: '' }; + } + const act: Act = + mode === 'password' ? 'code' : mode === 'approved' ? 'request' : 'move'; + return { word, wordCls, act, why: '' }; } -/** Width of the code field between its brackets. */ -const FIELD = 10; -const MOVE_IN = '[ MOVE IN ]'; -/** Widest key group at the right of a row: CODE [field] [ MOVE IN ]. */ -const KEYS_W = 5 + FIELD + 3 + MOVE_IN.length; +const wait = (s: number) => + `WAIT ${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`; + +const residents = (n: number) => { + const v = Math.min(999, Math.max(0, Math.floor(n || 0))); + return v === 1 ? '1 resident' : `${v} residents`; +}; + +const EMPTY_LINE: Record = { + playing: 'NO ROOMS TO LET.', + ended: 'PORT CLOSED.', +}; +const PREGAME_LINE = 'ROOMS LET ONCE THE PORT OPENS.'; + +/** + * Keypad lockouts count down in the page from the last value the server sent, as CREWS does + * for cryo. Returns the seconds left for an outpost. + */ +function useCountdown(outposts: Outpost[]) { + const seen = useRef>({}); + const [now, setNow] = useState(Date.now()); + const any = outposts.some((o) => (o.code_wait || 0) > 0); + for (const o of outposts) { + const v = o.code_wait || 0; + const was = seen.current[o.ref]; + if (!was || was.v !== v) { + seen.current[o.ref] = { v, t: Date.now() }; + } + } + useEffect(() => { + if (!any) { + return; + } + const id = setInterval(() => setNow(Date.now()), 1000); + return () => clearInterval(id); + }, [any]); + return (ref: string) => { + const was = seen.current[ref]; + if (!was || was.v <= 0) { + return 0; + } + return Math.max(0, was.v - Math.floor((now - was.t) / 1000)); + }; +} export function HousingTab() { const { act, data } = useBackend(); - const { cols, rows, narrow } = useGrid(); - const [codes, setCodes] = useState>({}); - const [page, setPage] = useState(0); + const { rows } = useGrid(); const outposts = data.outposts || []; + const phase = data.phase; + const open = phase === 'playing'; + const noticeAt = data.notice ? data.notice.at : null; - const h = rows - 1 - TOP; - const bottom = TOP + h - 1; - const hy = TOP + 1; - const right = cols - 4; - // The mockup's columns on a wide screen; tighter on a narrow one, with the keys on a second line. - const colA = narrow ? Math.min(22, Math.floor(cols * 0.42)) : 30; - const colR = narrow ? colA + 9 : 44; - const nameW = colA - 5; - const step = narrow ? 4 : 3; - const perPage = Math.max(1, Math.floor((bottom - 1 - (hy + 2)) / step)); - const pages = Math.max(1, Math.ceil(outposts.length / perPage)); - const shownPage = Math.min(page, pages - 1); - const shown = outposts.slice( - shownPage * perPage, - shownPage * perPage + perPage, - ); - const blockEnd = narrow ? cols - 3 : right - KEYS_W - 2; - const blockRoom = Math.max(0, Math.floor((blockEnd - (colR + 5)) / 2)); + const [codes, setCodes] = useState>({}); + const [page, setPage] = useState(1); + const [claimRef, setClaimRef] = useState(null); + const [sent, setSent] = useState<{ at: number | null } | null>(null); + const lastWheel = useRef(0); + const left = useCountdown(outposts); + useScreen('housing', 0); + + // A sent move-in: every key is dead until the notice changes or 4 seconds pass. + useEffect(() => { + if (!sent) { + return; + } + const id = setTimeout(() => setSent(null), SENT_MS); + return () => clearTimeout(id); + }, [sent]); + const busy = !!sent && sent.at === noticeAt; + + const n = outposts.length; + const M = rows; + const B = bodyRows(M); + const foot = !open && phase !== 'ended' && n > 0 ? 1.25 : 0; + const R = B - foot; + const onePage = n <= Math.floor((R + 0.25) / 3.75); + const per = onePage + ? Math.max(1, n) + : Math.max(1, Math.floor((B - 1.25 + 0.25) / 3.75)); + const h = onePage + ? Math.min(5.75, f4((R - 0.25 * (n - 1)) / Math.max(1, n))) + : Math.min(5.75, f4((B - 1.25 - 0.25 * (per - 1)) / per)); + const pages = Math.max(1, Math.ceil(n / per)); + const pg = Math.min(pages, Math.max(1, page)); + const first = (pg - 1) * per; + const shown = outposts.slice(first, first + per); + + const turn = (to: number, last = false) => { + if (to < 1 || to > pages || to === pg) { + return false; + } + const at = (to - 1) * per; + const target = last ? outposts[Math.min(n - 1, at + per - 1)] : outposts[at]; + setClaimRef(target ? target.ref : null); + setPage(to); + return true; + }; + + // PageDown and PageUp turn the page from anywhere in the list. + usePager(pages > 1 ? (step) => turn(pg + step) : null); const moveIn = (o: Outpost) => { act('home_move_in', { outpost: o.ref, code: codes[o.ref] || '' }); setCodes({ ...codes, [o.ref]: '' }); + setSent({ at: noticeAt }); }; - const codeKeys = (o: Outpost, y: number) => { - const locked = (o.code_wait || 0) > 0; - const code = codes[o.ref] || ''; - const fx = right - MOVE_IN.length - 2 - FIELD; - const cls = locked ? 'faint' : 'amb'; - return ( - <> - - CODE - - setCodes({ ...codes, [o.ref]: value })} - onEnter={() => moveIn(o)} - /> - 0} - disabled={locked} - onClick={() => moveIn(o)} - /> - - ); + const live = (o: Outpost) => { + const v = viewOf(o); + if (!open || busy || v.act === 'none') { + return false; + } + return v.act !== 'code' || left(o.ref) <= 0; }; + // First focus: the first live key or field from the top; a page turn claims the block it lands on. + const claim = + claimRef && shown.some((o) => o.ref === claimRef && live(o)) + ? claimRef + : (shown.find(live) || { ref: null }).ref; - const keys = (o: Outpost, y: number) => { - if (o.mode === 'password' && !o.cleared && !o.denial) { - return codeKeys(o, y); - } - const ax = right - MOVE_IN.length - 2; - let ask: ReactNode = null; - if (o.can_ask) { - ask = o.asked ? ( - - ) : ( - act('home_request', { outpost: o.ref })} + const box = ( + + ); + + const out: ReactNode[] = []; + if (!n) { + const y0 = BODY_Y; + out.push( + + + , + ); + } else { + shown.forEach((o, i) => { + const lastRow = i === shown.length - 1; + out.push( + turn(pg + 1) : undefined, + up: i === 0 ? () => turn(pg - 1, true) : undefined, + }} + onCode={(value) => setCodes({ ...codes, [o.ref]: value })} + onMove={() => moveIn(o)} + onRequest={() => act('home_request', { outpost: o.ref })} + />, + ); + }); + if (foot) { + out.push( + + {PREGAME_LINE} + , ); } - return ( + out.push( + turn(to)} + />, + // A page turn wipes the blocks only. + , + ); + } + + return ( +
{ + if (pages <= 1 || !e.deltaY) { + return; + } + const now = Date.now(); + if (now - lastWheel.current < 150) { + return; + } + lastWheel.current = now; + turn(pg + (e.deltaY > 0 ? 1 : -1)); + }} + > + {box} + {out} +
+ ); +} + +function OutpostBlock(props: { + o: Outpost; + y0: number; + h: number; + open: boolean; + busy: boolean; + /** Seconds left on this outpost's keypad lockout. */ + wait: number; + code: string; + auto?: number; + edge: { down?: () => boolean; up?: () => boolean }; + onCode: (value: string) => void; + onMove: () => void; + onRequest: () => void; +}) { + const { o, y0, h, open, busy, wait: lock, code, auto, edge } = props; + const p = h >= 4.75 ? 0.25 : 0.125; + const v = viewOf(o); + const name = safe(o.name).trim().toUpperCase(); + const twoLines = name.length > NAME_W && h >= 4.75; + const nameLines = twoLines ? wrapMax(name, NAME_W, 2) : []; + const resY = y0 + p + (twoLines ? 2.25 : 1.25); + const keyY = y0 + h - p - 1.5; + const dead = !open || busy; + const locked = v.act === 'code' && lock > 0; + // A request went out: the block's bar flashes once. + const asked = !!o.asked; + useChanged(asked, (_, now) => { + if (now) { + sfx('ok', { own: true }); + } + }); + + let keys: ReactNode = null; + if (v.act === 'move') { + keys = ( + + ); + } else if (v.act === 'request') { + keys = ( + + ); + } else if (v.act === 'code') { + keys = ( <> - {ask} - {o.denial ? ( - // Faint, but a press still answers with the reason as a notice. - act('home_move_in', { outpost: o.ref })} - > - {MOVE_IN} - + {locked ? ( + <> + + + {wait(lock)} + + ) : ( - moveIn(o)} + { + if (!dead && code.length > 0) { + props.onMove(); + } + }} /> )} + ); - }; + } return ( - - {outposts.length === 0 ? ( - - NO ROOMS TO LET. - - ) : ( - <> - - OUTPOST - - - ADMITS - - - {narrow ? 'RES' : 'RESIDENTS'} + + {twoLines ? ( + nameLines.map((line, i) => ( + + {line} - + )) + ) : ( + )} - {shown.map((o, i) => { - const y = hy + 2 + i * step; - const [mode, modeCls] = MODES[o.mode] || MODES.closed; - const blocks = Math.max(0, Math.min(o.residents, blockRoom)); - return ( - - - {cutName(o.name.toUpperCase(), nameW)} - - - {mode} - - - {String(o.residents).padStart(3, ' ')} - - {Array.from({ length: blocks }, (_, k) => ( - - ))} - {keys(o, narrow ? y + 1 : y)} - {i < shown.length - 1 && ( - - )} - - ); - })} - {pages > 1 && ( - <> - setPage(shownPage - 1)} - /> - - {`${shownPage + 1}/${pages}`} - - = pages - 1} - onClick={() => setPage(shownPage + 1)} - /> - + + {residents(o.residents)} + + + {!!v.why && ( + + {cut(v.why, NAME_W)} + )} - + + {v.word} + + {keys} + ); } diff --git a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/HullRecord.tsx b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/HullRecord.tsx index a3cc8b51c65..3b6357a1995 100644 --- a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/HullRecord.tsx +++ b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/HullRecord.tsx @@ -1,132 +1,261 @@ /** - * One hull's record: the stock fit on the viewscreen, model name, description, crew, - * rooms, finishes, price and [ FIT OUT ]. + * HULL RECORD (spec 02, 3.4). It replaces the list in the same box, captioned with the hull's + * full name. Left: the hull in its stock fit over its description. Right, past a rule: the + * berths as the big figure, the rooms and finishes (by name when the column has the rows, else + * counts), the price by class, and the big FIT OUT key (BILL for a hull with nothing to fit). + * + * The tab row's right zone ([ BACK ] and the hull stepper) is drawn by YardTab. PageUp and + * PageDown step through the catalog in list order here. + * + * FIT OUT keeps a fit that already belongs to this hull (YardTab's go.fitOut); only another + * hull starts from stock. */ import type { ReactNode } from 'react'; +import { usePager } from './nav'; import { ShipPic } from './ShipPic'; -import { cut, Frame, Put, TOP, useGrid, wrapMax } from './term'; -import type { Hull } from './types'; import { - costOf, + Big, + bodyRows, + BODY_Y, + Box, + BOX_Y, + cut, + Key, + Put, + RPut, + safe, + useGrid, + VRule, + wrap, + wrapMax, +} from './term'; +import type { Hull, PartClass } from './types'; +import { crewCount, + fittable, hullOwned, - Key, + PART_ORDER, stockFit, usePreview, type YardCtx, } from './YardTab'; -export function HullRecord(props: { - ctx: YardCtx; - hull: Hull; - x: number; - w: number; -}) { - const { ctx, hull, x, w } = props; - const { rows, narrow } = useGrid(); +/** Left column: columns 1 to 39. */ +const LW = 39; +/** Right column: columns 43 to 61. */ +const RX = 43; +const RW = 19; +/** Right-aligned figures end on column 61. */ +const R_END = 62; + +/** The figure a parts count draws as: 9999+ above 9999. */ +const figure = (n: number) => (n > 9999 ? '9999+' : String(n)); + +/** PageUp / PageDown step through the catalog while the record is open. */ +function useHullKeys(ctx: YardCtx, hull: Hull) { + usePager((d) => { + const { catalog } = ctx; + const at = catalog.findIndex((h) => h.id === hull.id); + const to = at + d; + if (at >= 0 && to >= 0 && to < catalog.length && !ctx.view.leave) { + ctx.go.record(catalog[to].id); + } + }); +} + +/** The record always takes the whole main box. */ +export function HullRecord(props: { ctx: YardCtx; hull: Hull }) { + const { ctx, hull } = props; + const { rows } = useGrid(); usePreview(hull.id); - const h = rows - 1 - TOP; + useHullKeys(ctx, hull); + const M = rows; + const B = bodyRows(M); const fit = stockFit(hull); - const picH = Math.max(6, Math.floor(h * 0.42)); const out: ReactNode[] = []; out.push( - , + , + , ); - let y = TOP + 2 + picH; + + // Left: the picture takes every row the description leaves, never under 7. + const desc = safe(hull.desc); + const lines = desc ? wrap(desc, LW).length : 0; + const L = Math.min(lines, Math.max(0, Math.floor(B - 0.5 - 7))); + const P = L > 0 ? B - L - 0.5 : B; + out.push(); + if (L > 0) { + wrapMax(desc, LW, L).forEach((line, i) => { + out.push( + + {line} + , + ); + }); + } + + // Right: names when the column has the rows, else counts. + const rooms = fit.slots.map((sl) => sl.label); + const finishes = hull.finishes.map((f) => safe(f.name).toUpperCase()); + const owned = hullOwned(ctx.own, hull); + const priced: PartClass[] = owned + ? [] + : PART_ORDER.filter((k) => (hull.cost?.[k] || 0) > 0); + const priceRows = Math.max(1, priced.length); + const need = + 3.75 + + (rooms.length ? rooms.length + 1.5 : 0) + + (finishes.length ? finishes.length + 1.5 : 0) + + 1 + + priceRows + + 2.5; + const names = need <= B; + // Spare rows spread the name and price rows apart (pitch up to 1.5), so a tall pane's + // column does not end in a large empty block above the key. + const listed = rooms.length + finishes.length + priceRows; + const lp = names + ? Math.min(1.5, 1 + Math.floor(((B - need) / Math.max(1, listed)) * 4) / 4) + : 1; + + let y = BODY_Y; + const berths = Math.min(999, crewCount(fit)); out.push( - - {cut(hull.name.toUpperCase(), w - 6)} + + {String(berths)} + , + + BERTHS , ); - y++; - const by = TOP + h - 3; - const owned = hullOwned(ctx.own, hull); - // Leave room for the stats line and the price above the key. - const descRows = Math.max(1, by - (owned ? 1 : 3) - 2 - y); - wrapMax(hull.desc, w - 6, descRows).forEach((l, i) => { - out.push( - - {l} - , - ); - }); - y++; - if (y < by - (owned ? 0 : 2)) { - out.push( - - CREW - , - - {String(crewCount(fit))} - , - - ROOMS - , - - {String(hull.slots.length)} - , - ); - if (hull.finishes.length && w >= 44) { + y += 3.25 + (names ? 0.5 : 0.25); + + if (names) { + if (rooms.length) { out.push( - + + ROOMS + , + ); + y += 1; + rooms.forEach((label, i) => { + out.push( + + {cut(label, RW)} + , + ); + y += lp; + }); + // A section ends half a row past its last line, so it reads apart from the next head + // even when spare rows widen the line pitch. + y += 0.5; + } + if (finishes.length) { + out.push( + FINISHES , - - {String(hull.finishes.length)} + ); + y += 1; + finishes.forEach((name, i) => { + out.push( + + {cut(name, RW)} + , + ); + y += lp; + }); + y += 0.5; + } + } else { + const counts: [string, number][] = []; + if (rooms.length) { + counts.push(['ROOMS', rooms.length]); + } + if (finishes.length) { + counts.push(['FINISHES', finishes.length]); + } + counts.forEach(([word, n], i) => { + out.push( + + {word} , + + {String(Math.min(99, n))} + , ); + y += 1; + }); + if (counts.length) { + y += 0.25; } } - if (!owned) { + + out.push( + + PRICE + , + ); + y += 1; + if (owned || !priced.length) { out.push( - - PRICE - , - - {cut(costOf(hull.cost), w - 13)} + + {hullWord(ctx, hull)} , ); + } else { + priced.forEach((k) => { + out.push( + + {k.toUpperCase()} + , + + {figure(hull.cost?.[k] || 0)} + , + ); + y += lp; + }); } + + const canFit = fittable(hull); out.push( - ctx.set({ - // A hull with no finishes and no rooms has nothing to fit: straight to the bill. - screen: hull.finishes.length || hull.slots.length ? 'fit' : 'bill', - finish: null, - picks: {}, - step: 0, - }) - } + onClick={() => ctx.go.fitOut(hull)} />, ); - if (!narrow) { - out.push( - ctx.set({ hull: null })} - > - {' X '} - , - ); - } - return ( - - {out} - - ); + return <>{out}; +} + +/** FREE for a hull that costs nothing (or under free ships), OWNED for one bought earlier. */ +function hullWord(ctx: YardCtx, hull: Hull): 'FREE' | 'OWNED' { + if (ctx.own.free || !!hull.free) { + return 'FREE'; + } + const anyCost = PART_ORDER.some((k) => (hull.cost?.[k] || 0) > 0); + return anyCost ? 'OWNED' : 'FREE'; } diff --git a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/Hulls.tsx b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/Hulls.tsx index 5144a1ad795..908a3b1ea48 100644 --- a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/Hulls.tsx +++ b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/Hulls.tsx @@ -1,212 +1,316 @@ /** - * HULLS registry. Wide: the list, and the selected hull's record beside it. Narrow: the - * list, or the record on its own screen ([ BACK ] returns to the list). + * HULLS (spec 02, 3.3): the shelf as blocks in the CREWS language (design 01, 6.3), paged, + * with compact rows only when fewer than three blocks fit. A block opens the hull's record, + * which is drawn in place of the list (HullRecord.tsx). */ -import { type ReactNode, useMemo, useState } from 'react'; +import { type ReactNode, useEffect, useMemo, useRef, useState } from 'react'; import { HullRecord } from './HullRecord'; -import { Frame, Hit, lpad, Put, pad, TOP, useGrid } from './term'; +import { usePager } from './nav'; +import { + BODY_Y, + BOX_Y, + Big, + Box, + bodyRows, + cut, + NameLine, + Pager, + Put, + RPut, + SEP, + Slab, + safe, + useGrid, + WipeAt, + wrapMax, +} from './term'; +import type { Hull } from './types'; import { crewCount, hullOwned, + type Ownership, partsOf, stockFit, type YardCtx, } from './YardTab'; -export function Hulls(props: { ctx: YardCtx }) { - const { ctx } = props; - const { catalog, hull, own } = ctx; - const { cols, rows, narrow } = useGrid(); - const h = rows - 1 - TOP; - const crews = useMemo( - () => catalog.map((hl) => crewCount(stockFit(hl))), - [catalog], - ); - const [page, setPage] = useState(1); - const [enterLast, setEnterLast] = useState(false); +/** Rounded down to a quarter row. */ +const f4 = (v: number) => Math.floor(v * 4) / 4; - if (narrow && hull) { - return ; - } +/** Block text: columns 3 to 49. Compact line 2: columns 3 to 60. */ +const BLOCK_W = 47; +const ROW_W = 58; - const split = !!hull && !narrow; - const lw = split ? Math.max(40, Math.floor(cols * 0.41)) : cols; - // Columns, right to left from the price. - const price = lw - 14; - const rooms = price - 8; - const crew = rooms - 6; - const fin = split ? 0 : price - 9; - const showModel = !split && crew - 28 >= 20; - const showFin = !split && !narrow; - const roomsAt = showFin ? fin - 8 : rooms; - const crewAt = showFin ? roomsAt - 7 : crew; - const nameEnd = showModel ? 27 : crewAt - 1; +type Shown = { + hull: Hull; + name: string; + /** The full name without the short name, or ''. */ + type: string; + price: string; + /** Amber when it costs parts. */ + due: boolean; + berths: number; +}; - const out: ReactNode[] = []; - const hy = TOP + 1; - out.push( - - HULL - , - - CREW - , - - ROOMS - , - - PRICE - , - ); - if (showModel) { - out.push( - - MODEL - , - ); +function priceOf(own: Ownership, hl: Hull): [string, boolean] { + if (own.free || !!hl.free || !partsOf(hl.cost)) { + return ['FREE', false]; } - if (showFin) { - out.push( - - FINISH - , - ); + if (hullOwned(own, hl)) { + return ['OWNED', false]; } - // Rows below the header, less one for the pager when the list runs over. - let maxRows = Math.max(1, TOP + h - 2 - hy); - if (catalog.length > maxRows) { - maxRows = Math.max(1, maxRows - 1); + return [`${partsOf(hl.cost)} PARTS`, true]; +} + +function typeOf(hl: Hull): string { + const name = safe(hl.name).trim(); + const short = safe(hl.short).trim(); + if (short && name.toUpperCase().startsWith(short.toUpperCase())) { + return name.slice(short.length).trim(); } - const pages = Math.max(1, Math.ceil(catalog.length / maxRows)); - const pg = Math.min(pages, Math.max(1, page)); - const goPage = (to: number, last: boolean) => { - setEnterLast(last); - setPage(to); - }; - const shown = catalog.slice((pg - 1) * maxRows, pg * maxRows); - shown.forEach((hl, n) => { - const i = (pg - 1) * maxRows + n; - const y = hy + 1 + n; - const firstRow = n === 0; - const lastRow = n === shown.length - 1; - const sel = hull?.id === hl.id; - const k = sel ? 'inv' : ''; - const owned = hullOwned(own, hl); - const cost = partsOf(hl.cost); - const priceText = owned - ? cost && !hl.free && !own.free - ? 'OWNED' - : 'FREE' - : `${cost} PARTS`; - if (sel) { - out.push( - - {' '.repeat(lw - 3)} - , - ); - } - out.push( - - {sel ? '>' : ' '} - , - - {pad(hl.short.toUpperCase(), nameEnd - 3)} - , - - {lpad(crews[i], 3)} - , - - {lpad(hl.slots.length, 3)} - , + return short && name.toUpperCase() === short.toUpperCase() ? '' : name; +} + +/** The type line's parts in `w` cells: the price is kept, the type is cut. */ +function TypeLine(props: { x: number; y: number; s: Shown; w: number }) { + const { x, y, s, w } = props; + const tail = s.type ? ` ${SEP} ` : ''; + const type = s.type ? cut(s.type, w - s.price.length - tail.length) : ''; + return ( + <> + {!!type && ( + + {type + tail} + + )} - {pad(priceText, lw - 3 - price)} - , - ); - if (showModel) { - out.push( - - {pad(hl.name, crewAt - 29)} - , - ); + {s.price} + + + ); +} + +export function Hulls(props: { ctx: YardCtx }) { + const { ctx } = props; + const { catalog, hull, own, view } = ctx; + const { rows } = useGrid(); + const lastWheel = useRef(0); + + const list: Shown[] = useMemo( + () => + catalog.map((hl) => { + const [price, due] = priceOf(own, hl); + return { + hull: hl, + name: safe(hl.short).toUpperCase(), + type: typeOf(hl), + price, + due, + berths: Math.max(0, Math.min(999, crewCount(stockFit(hl)))), + }; + }), + [catalog, own.owned, own.free], + ); + + const N = list.length; + const B = bodyRows(rows); + let form: 'block' | 'row'; + let per: number; + let h: number; + if (N <= Math.floor((B + 0.25) / 5)) { + form = 'block'; + per = Math.max(1, N); + h = Math.min(7, f4((B - 0.25 * (N - 1)) / Math.max(1, N))); + } else if (Math.floor((B - 1) / 5) >= 3) { + form = 'block'; + per = Math.floor((B - 1) / 5); + h = Math.min(7, f4((B - 1.25 - 0.25 * (per - 1)) / per)); + } else { + form = 'row'; + per = Math.max(1, Math.floor((B - 1) / 2.5)); + h = 2.25; + } + const pitch = form === 'block' ? h + 0.25 : 2.5; + const pages = Math.max(1, Math.ceil(N / per)); + + // Opens on the page of the hull last opened, with that hull focused. + const lastAt = list.findIndex((s) => s.hull.id === view.lastHull); + const [page, setPage] = useState(() => + lastAt >= 0 ? Math.floor(lastAt / per) + 1 : 1, + ); + const [claimId, setClaimId] = useState( + lastAt >= 0 ? view.lastHull : null, + ); + const pg = Math.min(pages, Math.max(1, page)); + const first = (pg - 1) * per; + const shown = list.slice(first, first + per); + + // A pane resize changes `per`: keep the focused hull's page. + const focId = useRef(claimId); + const lastPer = useRef(per); + useEffect(() => { + if (lastPer.current === per) { + return; } - if (showFin) { - out.push( - - {lpad(hl.finishes.length || '-', 3)} - , - ); + lastPer.current = per; + const at = list.findIndex((s) => s.hull.id === focId.current); + if (at >= 0) { + setClaimId(focId.current); + setPage(Math.floor(at / per) + 1); } + }, [per]); + + const turn = (to: number, last = false) => { + if (to < 1 || to > pages || to === pg) { + return false; + } + const at = (to - 1) * per; + const target = last ? list[Math.min(N - 1, at + per - 1)] : list[at]; + setClaimId(target ? target.hull.id : null); + setPage(to); + return true; + }; + + // PageDown and PageUp turn the page from anywhere in the list. + const listOpen = !hull && pages > 1; + usePager(listOpen ? (step) => turn(pg + step) : null); + + if (hull) { + return ; + } + + const claim = claimId ?? (shown[0] ? shown[0].hull.id : null); + const out: ReactNode[] = []; + shown.forEach((s, i) => { + const y0 = BODY_Y + i * pitch; + const edge = { + down: i === shown.length - 1 ? () => turn(pg + 1) : undefined, + up: i === 0 ? () => turn(pg - 1, true) : undefined, + }; + const common = { + s, + y0, + auto: s.hull.id === claim ? 1 : undefined, + edge, + onOpen: () => ctx.go.record(s.hull.id), + onFocus: () => { + focId.current = s.hull.id; + }, + }; out.push( - ctx.set({ hull: sel ? null : hl.id })} - auto={(enterLast ? lastRow : firstRow) && !hull ? 1 : undefined} - edge={{ - down: - lastRow && pg < pages - ? () => { - goPage(pg + 1, false); - return true; - } - : undefined, - up: - firstRow && pg > 1 - ? () => { - goPage(pg - 1, true); - return true; - } - : undefined, - }} - />, + form === 'block' ? ( + + ) : ( + + ), ); }); - if (pages > 1) { - const py = TOP + h - 1; - const label = ` ${pg}/${pages} `; - out.push( - 1 ? 'inv' : 'faint'} - bg={pg <= 1} - onClick={pg > 1 ? () => goPage(pg - 1, false) : undefined} - > - {' < '} - , - - {label} - , - = pages} - onClick={pg < pages ? () => goPage(pg + 1, false) : undefined} - > - {' > '} - , - ); - } return ( - <> - +
{ + if (pages <= 1 || !e.deltaY) { + return; + } + const now = Date.now(); + if (now - lastWheel.current < 150) { + return; + } + lastWheel.current = now; + turn(pg + (e.deltaY > 0 ? 1 : -1)); + }} + > + {out} - {split && !!hull && ( - - )} - + turn(to)} + /> + {/* A page turn wipes the blocks only. */} + +
+ ); +} + +type ItemProps = { + s: Shown; + y0: number; + auto?: number; + edge: { down?: () => boolean; up?: () => boolean }; + onOpen: () => void; + onFocus: () => void; +}; + +function HullBlock(props: ItemProps & { h: number }) { + const { s, y0, h, auto, edge, onOpen, onFocus } = props; + const p = h >= 4.75 ? 0.25 : 0.125; + const lines = Math.max(2, Math.min(4, Math.floor(h - 2.25 - 2 * p))); + const desc = wrapMax( + safe(s.hull.desc).replace(/\s+/g, ' ').trim(), + BLOCK_W, + lines, + ); + return ( + on && onFocus()} + > + + + {desc.map((t, i) => ( + + {t} + + ))} + + {String(s.berths)} + + + BERTHS + + + ); +} + +function HullRow(props: ItemProps & { alt: boolean }) { + const { s, y0, alt, auto, edge, onOpen, onFocus } = props; + return ( + on && onFocus()} + > + + {cut(s.name, 46)} + + + {`${s.berths} BERTHS`} + + + ); } diff --git a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/ItemPic.tsx b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/ItemPic.tsx new file mode 100644 index 00000000000..772545fa50e --- /dev/null +++ b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/ItemPic.tsx @@ -0,0 +1,48 @@ +/** + * ItemPic (design 03b section 3.2): a loadout item's own sprite in a cell block, as tg's + * loadout page draws it (DmIcon from the catalog's icon and icon_state), at a whole scale, + * pixelated and centred. Draws nothing when the icon does not resolve (no Byond.iconRefMap + * entry, as in the render harness). + */ +import { DmIcon } from 'tgui-core/components'; + +import { useGrid } from './term'; + +export function ItemPic(props: { + x: number; + y: number; + w: number; + h: number; + icon: string; + icon_state: string; + /** Whole multiple of 32 px. */ + scale: number; +}) { + const { x, y, w, h, icon, icon_state, scale } = props; + const { cw, ch } = useGrid(); + const size = 32 * Math.max(1, Math.floor(scale)); + const left = Math.round(x * cw + (w * cw - size) / 2); + const top = Math.round(y * ch + (h * ch - size) / 2); + return ( +
+ +
+ ); +} diff --git a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/KitEditor.tsx b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/KitEditor.tsx index fe4b10fc659..f71b2a3e7cc 100644 --- a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/KitEditor.tsx +++ b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/KitEditor.tsx @@ -1,55 +1,73 @@ /** - * KIT (CHARACTER-PLAN 2.8): tg's loadout categories and items, char_kit. A packed item - * shows its options under it: one ColorEntry per GAGS colour slot (char_kit_color), a - * STYLE cycler for reskins (char_kit_skin) and a NAME field where tg allows renaming - * (char_kit_name). Nothing here has a price. Owner: C4. + * KIT (design 03b section 3): tg's stock loadout. The ID column lists PACKED and tg's + * categories under the preview; the work column lists the open one's items, each with its own + * picture. A packed item has one row an option under it: COLOUR (one a slot, through the shared + * colour panel), STYLE (reskins), NAME (renaming), WORN (an accessory over or under the suit) + * and LIPS (where the lipstick sits). Nothing here has a price. * - * Box: x and w are the editor frame's outer columns, y the row under its top line, - * y + h - 1 its bottom line. + * A press packs or unpacks at once from a local copy with tg's rule (one item a category, two + * in Other, the oldest pick goes); the next push replaces the copy. */ -import { useEffect, useState } from 'react'; +import { type ReactNode, useEffect, useState } from 'react'; import { useBackend } from 'tgui/backend'; import type { LoadoutCategory, LoadoutItem, } from 'tgui/interfaces/PreferencesMenu/CharacterPreferences/loadout/base'; -import { ColorEntry } from './ColorEntry'; -import { fileColors } from './TraitsEditor'; +import { fileColours } from './BodyEditor'; import { - Btn, - Cycler, + clamp, + ID_W, + ID_X, + IdColumn, + perPage, + planId, + q, + StepKeys, + useChar, + useLatePager, + useWheel, + WORK_W, + WORK_X, +} from './CharFrame'; +import { ColourPanel, ListPicker } from './CharPickers'; +import { ItemPic } from './ItemPic'; +import { sfxInstead } from './motion'; +import { FocusGroup } from './nav'; +import { + FlashAt, + BODY_Y, + bodyRows, + Check, + cut, Field, - Frame, - Hit, + NameLine, + Pager, Put, - pad, + RPut, + Slab, Swatch, + safe, useGrid, + wrapMax, + WipeAt, } from './term'; import { - type CellBox, type CharKitItem, KIT_NAME_MAX, type LobbyData, } from './types'; -import { usePrefsCatalog } from './usePrefsCatalog'; +import { decodeName, usePrefsCatalog } from './usePrefsCatalog'; type Kit = Record; -/** Category column width. */ -const CAT_W = 13; -/** PACKED box width on wide screens. */ -const PACK_W = 30; -/** Label column of the option rows under a packed item. */ -const OPT_W = 9; -/** Names the server takes for a kit item (empty clears). */ -const NAME_OK = /^[\x20-\x7e]*$/; -const NAME_BAD = /[<>/\\]/; /** The category whose items stay at two (tg: /datum/loadout_category/pocket). */ const TWO_ALLOWED = 'Other'; +const LIPS = ['Upper', 'Middle', 'Lower'] as const; +type Lip = (typeof LIPS)[number]; -/** The colours of a packed item, one per slot, "#rrggbb". */ +/** The colours of a packed item, one a slot, "#rrggbb". */ function slotColors(item: CharKitItem | undefined, slots: number): string[] { const found = (item?.greyscale || '').match(/#[0-9a-f]{6}/gi) || []; const out: string[] = []; @@ -59,67 +77,205 @@ function slotColors(item: CharKitItem | undefined, slots: number): string[] { return out; } -/** The server stores names html-escaped; show them as typed. */ -function unescapeName(text: string): string { - return text - .replace(/&#(\d+);/g, (_, n) => String.fromCharCode(Number(n))) - .replace(/&#x([0-9a-f]+);/gi, (_, n) => - String.fromCharCode(parseInt(n, 16)), - ) - .replace(/"/g, '"') - .replace(/</g, '<') - .replace(/>/g, '>') - .replace(/&/g, '&'); +/** One option row under a packed item. */ +type Opt = + | { kind: 'colour'; slot: number; slots: number } + | { kind: 'style' } + | { kind: 'name' } + | { kind: 'worn' } + | { kind: 'lips' }; + +function optionsOf(item: LoadoutItem, slots: number): Opt[] { + const out: Opt[] = []; + for (let s = 0; s < slots; s++) { + out.push({ kind: 'colour', slot: s, slots }); + } + if (item.reskins?.length) { + out.push({ kind: 'style' }); + } + const acts = (item.buttons || []).map((b) => b.act_key); + if (acts.includes('set_name')) { + out.push({ kind: 'name' }); + } + if (acts.includes('set_layer')) { + out.push({ kind: 'worn' }); + } + if (acts.includes('select_lipstick_style')) { + out.push({ kind: 'lips' }); + } + return out; +} + +const optKey = (path: string, o: Opt) => + `${path}#${o.kind}${o.kind === 'colour' ? o.slot : ''}`; + +/** The skin shown for an item: the stored one, else the one matching its icon, else the first. */ +function skinOf(item: LoadoutItem, stored?: string) { + const skins = item.reskins || []; + return ( + skins.find((s) => s.name === stored) || + skins.find((s) => s.skin_icon_state === item.icon_state) || + skins[0] + ); +} + +// --------------------------------------------------------------------------- +// Level 2 screens. Each reads live data, so the frame can keep the element as it was opened. + +/** Closes the level-2 screen when its item is unpacked (here or in tg's window). */ +function useGoneClose(path: string) { + const { data } = useBackend(); + const { closeSub } = useChar(); + const gone = !(path in (data.char?.kit || {})); + useEffect(() => { + if (gone) { + closeSub(); + } + }, [gone]); } -/** One drawn line of the item list. */ +function KitColour(props: { path: string; slot: number; slots: number; label: string }) { + const { path, slot, slots, label } = props; + const { act, data } = useBackend(); + const { closeSub } = useChar(); + useGoneClose(path); + const char = data.char; + const kit = char?.kit || {}; + const kitColors = data.char_static?.kit_colors || {}; + const recent = [ + ...fileColours(char), + ...Object.keys(kit).flatMap((p) => slotColors(kit[p], kitColors[p] || 0)), + ].filter((c, i, all) => all.indexOf(c) === i); + return ( + act('char_kit_color', { path, slot, color })} + onClose={closeSub} + /> + ); +} + +function KitStyle(props: { item: LoadoutItem }) { + const { item } = props; + const { act, data } = useBackend(); + const { closeSub } = useChar(); + useGoneClose(item.path); + const skins = item.reskins || []; + const current = skinOf(item, data.char?.kit?.[item.path]?.reskin); + return ( + s.name)} + value={current?.name || ''} + nameOf={(v) => v} + onPick={(skin) => act('char_kit_skin', { path: item.path, skin })} + onClose={closeSub} + /> + ); +} + +/** NAME: typing; Enter or leaving the field submits; empty clears. */ +function NameField(props: { path: string; y: number; h: number; auto?: number }) { + const { path, y, h } = props; + const { act, data } = useBackend(); + const stored = decodeName(data.char?.kit?.[path]?.name || ''); + const [text, setText] = useState(stored); + const [typing, setTyping] = useState(false); + useEffect(() => { + if (!typing) { + setText(stored); + } + }, [stored]); + const commit = () => { + const next = text.trim(); + if (next !== stored) { + // The server decides: a refused name comes back as a notice and the old name. + act('char_kit_name', { path, name: next }); + } else { + setText(stored); + } + }; + return ( +
setTyping(true)} + onBlur={() => { + setTyping(false); + commit(); + }} + > + +
+ ); +} + +// --------------------------------------------------------------------------- + +/** One drawn piece of the item list. */ type Line = - | { kind: 'group'; text: string } - | { kind: 'item'; item: LoadoutItem } - | { kind: 'color'; item: LoadoutItem; slot: number; slots: number } - | { kind: 'skin'; item: LoadoutItem } - | { kind: 'name'; item: LoadoutItem } - | { kind: 'gap' }; + | { kind: 'group'; text: string; first: boolean } + | { kind: 'item'; item: LoadoutItem; opts: Opt[] }; -export function KitEditor(props: CellBox) { - const { x, y, w, h } = props; +export function KitEditor() { const { act, data } = useBackend(); - const { narrow } = useGrid(); const catalog = usePrefsCatalog(); + const { sub, subOpen, closeSub, from, quiet } = useChar(); + const { rows: M, ch } = useGrid(); const char = data.char; const kitColors = data.char_static?.kit_colors || {}; - const [cat, setCat] = useState(0); - const [page, setPage] = useState(1); - // Local copy after a click, dropped on the next push (a refused edit pushes too). + // Local copy after a press, dropped on the next push (a refused edit pushes too). const [local, setLocal] = useState(null); useEffect(() => setLocal(null), [char]); + const kit: Kit = local || char?.kit || {}; + const packedAtOpen = Object.keys(char?.kit || {}).length > 0; + /** -1 is PACKED, else a tab index. */ + const [open, setOpen] = useState(packedAtOpen ? -1 : 0); + const [page, setPage] = useState(0); + const [catPage, setCatPage] = useState(null); + const [fresh, setFresh] = useState(true); + const pager = useLatePager(); + const wheel = useWheel(); - if (!char || !catalog) { - return null; - } - const tabs: LoadoutCategory[] = catalog.loadout?.loadout_tabs || []; - if (!tabs.length) { + const tabs: LoadoutCategory[] = catalog?.loadout?.loadout_tabs || []; + if (!char || !tabs.length) { + pager.current = null; return null; } - const kit: Kit = local || char.kit || {}; - const ci = Math.min(cat, tabs.length - 1); - const tab = tabs[ci]; const tabOf = (path: string) => - tabs.findIndex((t) => t.contents.some((it) => it.path === path)); + tabs.find((t) => t.contents.some((it) => it.path === path)); + const itemOf = (path: string) => + tabOf(path)?.contents.find((it) => it.path === path); const toggle = (item: LoadoutItem) => { const on = !(item.path in kit); const next: Kit = { ...kit }; if (on) { - // Show tg's duplicate rule at once: one per category, two in Other (oldest goes). + const tab = tabOf(item.path); const same = Object.keys(next).filter( - (p) => tab.contents.some((it) => it.path === p) && p !== item.path, + (p) => p !== item.path && !!tab?.contents.some((it) => it.path === p), ); - const limit = tab.name === TWO_ALLOWED ? 2 : 1; + const limit = tab?.name === TWO_ALLOWED ? 2 : 1; while (same.length >= limit) { delete next[same.shift() as string]; } next[item.path] = {}; + // Packed: the accepted sound, in place of the key press. + sfxInstead('ok'); } else { delete next[item.path]; } @@ -127,442 +283,429 @@ export function KitEditor(props: CellBox) { act('char_kit', { path: item.path, on: on ? 1 : 0 }); }; - const wide = !narrow && w >= 70; - const packW = wide ? PACK_W : 0; - const ix = x + CAT_W + 3; - const iw = w - CAT_W - 5 - packW; - const top = y + 1; - const bottom = y + h - 3; - const catStep = h - 2 >= tabs.length * 2 ? 2 : 1; - - // ---- the item lines of this category ---- - const multiGroup = - new Set(tab.contents.map((it) => it.group || tab.name)).size > 1; - // Items grouped as tg's menu groups them, groups in order of first appearance. - const groupOrder: string[] = []; - for (const it of tab.contents) { - const g = it.group || tab.name; - if (!groupOrder.includes(g)) { - groupOrder.push(g); + // ---- ID column: PACKED and the categories, bottom-anchored (paged when short). + const entries: [label: string, count: number][] = [ + ['PACKED', Object.keys(kit).length], + ...tabs.map( + (t) => + [ + t.name, + Object.keys(kit).filter((p) => t.contents.some((it) => it.path === p)) + .length, + ] as [string, number], + ), + ]; + const c = entries.length; + let gh = 1.25; + let paged = false; + let per = c; + const plan = planId(M, 1.5 * c - 0.25, (la) => { + const h = clamp(q((la + 0.25) / c - 0.25), 1.25, 2); + const used = c * (h + 0.25) - 0.25; + if (used > la + 1e-6) { + paged = true; + per = perPage(la, 0); + return la; } + gh = h; + return used; + }); + const catPages = paged ? Math.ceil(c / per) : 1; + const openPage = Math.floor((open + 1) / per); + const cpg = Math.min(catPage ?? openPage, catPages - 1); + const catTop = paged ? BODY_Y + plan.pv + 2.25 : plan.top; + const idList: ReactNode[] = entries + .map((e, i) => [e, i] as [[string, number], number]) + .slice(cpg * per, cpg * per + per) + .map(([[label, count], i], k) => { + const y = catTop + k * (gh + 0.25); + const idx = i - 1; + return ( + { + // A category press leaves an open COLOUR, STYLE or NAME panel for that category. + if (subOpen) { + closeSub(); + } + if (idx !== open) { + setFresh(false); + setOpen(idx); + setPage(0); + } + }} + > + + {cut(safe(label).toUpperCase(), 15)} + + {count > 0 && ( + + {String(count)} + + )} + + ); + }); + if (paged) { + idList.push( + setCatPage(p - 1)} + right + />, + // A page of categories turning wipes the list only. + , + ); } - const items = [...tab.contents].sort( - (a, b) => - groupOrder.indexOf(a.group || tab.name) - - groupOrder.indexOf(b.group || tab.name), + + // PageUp and PageDown turn the categories here; the item list below takes them when it pages. + const catTurn = paged + ? (step: number) => setCatPage(clamp(cpg + step, 0, catPages - 1)) + : null; + pager.current = subOpen ? null : catTurn; + // The mouse wheel over the categories turns their pages, one a notch. + const idColumn = ( + +
+ {idList} +
+
); - const blocksOf: Line[][] = []; - let group: string | null = null; - for (const item of items) { - const block: Line[] = []; - const g = item.group || tab.name; - if (multiGroup && g !== group) { - block.push({ kind: 'group', text: g }); - } - group = g; - block.push({ kind: 'item', item }); - if (item.path in kit) { - const slots = kitColors[item.path] || 0; - for (let s = 0; s < slots; s++) { - block.push({ kind: 'color', item, slot: s, slots }); - } - if (item.reskins?.length) { - block.push({ kind: 'skin', item }); - } - if (item.buttons?.some((b) => b.act_key === 'set_name')) { - block.push({ kind: 'name', item }); + if (subOpen) { + return idColumn; + } + + // ---- work column: the items + const B = bodyRows(M); + const roomy = B >= 20; + const ih = roomy ? 2.25 : 1.25; + const oh = roomy ? 1.5 : 1.25; + const gap = roomy ? 0.25 : 0; + + let items: LoadoutItem[]; + let multi = false; + if (open < 0) { + items = Object.keys(kit) + .map((p) => itemOf(p)) + .filter((it): it is LoadoutItem => !!it); + } else { + const tab = tabs[Math.min(open, tabs.length - 1)]; + const order: string[] = []; + for (const it of tab.contents) { + const g = it.group || tab.name; + if (!order.includes(g)) { + order.push(g); } } - blocksOf.push(block); + multi = order.length > 1; + items = [...tab.contents].sort( + (a, b) => + order.indexOf(a.group || tab.name) - order.indexOf(b.group || tab.name), + ); } - // Double spacing when the whole category fits that way, as the mockup. - const room = bottom - top + 1; - const total = blocksOf.reduce((n, b) => n + b.length, 0); - const spaced = total + blocksOf.length - 1 <= room; - // Pages hold whole items. - const pages: Line[][] = [[]]; - for (const block of blocksOf) { - const cur = pages[pages.length - 1]; - const need = block.length + (spaced && cur.length ? 1 : 0); - if (cur.length && cur.length + need > room - 1) { - // A page that opens mid-group repeats the group's name. - const g = block[0].kind === 'item' && block[0].item.group; - const head: Line[] = - multiGroup && block[0].kind !== 'group' - ? [{ kind: 'group', text: g || tab.name }] - : []; - pages.push([...head, ...block]); - } else { - if (spaced && cur.length) { - cur.push({ kind: 'gap' }); + const groupOf = (it: LoadoutItem) => it.group || ''; + const blockSize = (it: LoadoutItem) => + ih + (it.path in kit ? optionsOf(it, kitColors[it.path] || 0).length : 0) * oh; + + // Pages hold whole items with their option rows; a page that opens inside a group repeats its head. + const layout = (room: number) => { + const pages: Line[][] = [[]]; + let used = 0; + let group: string | null = null; + for (const it of items) { + const opts = it.path in kit ? optionsOf(it, kitColors[it.path] || 0) : []; + const cur = pages[pages.length - 1]; + const g = groupOf(it); + const newGroup = multi && g !== group; + // A group head is one row with 0.25 above it unless it starts the page; items are `gap` apart. + const need = + (newGroup ? (cur.length ? 1.25 : 1) : cur.length ? gap : 0) + + blockSize(it); + if (cur.length && used + need > room + 1e-6) { + const next: Line[] = []; + if (multi) { + next.push({ kind: 'group', text: g, first: true }); + } + next.push({ kind: 'item', item: it, opts }); + pages.push(next); + used = (multi ? 1 : 0) + blockSize(it); + } else { + if (newGroup) { + cur.push({ kind: 'group', text: g, first: !cur.length }); + } + cur.push({ kind: 'item', item: it, opts }); + used += need; } - cur.push(...block); + group = g; } + return pages; + }; + let pages = layout(B); + if (pages.length > 1) { + pages = layout(B - 1.25); + } + const pg = Math.min(page, pages.length - 1); + const lines = pages[pg] || []; + const turn = + pages.length > 1 + ? (step: number) => { + setFresh(false); + setPage(clamp(pg + step, 0, pages.length - 1)); + } + : null; + if (turn) { + pager.current = turn; } - const pg = Math.min(pages.length, page); - const lines = pages[pg - 1]; - const recent = fileColors( - char.prefs, - Object.keys(kit).flatMap((p) => slotColors(kit[p], kitColors[p] || 0)), - ); - return ( - <> - {tabs.map((t, i) => { - const n = Object.keys(kit).filter((p) => - t.contents.some((it) => it.path === p), - ).length; - return ( - { - setCat(i); - setPage(1); - }} + const rows: ReactNode[] = []; + let y = BODY_Y; + let firstItem = true; + lines.forEach((line, i) => { + if (line.kind === 'group') { + if (!line.first) { + y += 0.25; + } + rows.push( + + {cut(safe(line.text).toUpperCase(), WORK_W)} + , + ); + y += 1; + return; + } + const { item, opts } = line; + if (i > 0 && lines[i - 1].kind === 'item') { + y += gap; + } + const packed = item.path in kit; + const iy = y; + const name = safe(item.name); + const nameLines = roomy ? wrapMax(name, 26, 2) : [cut(name, 32)]; + const ty = iy + (ih - nameLines.length) / 2; + rows.push( + toggle(item)} + > + {!!roomy && !!item.icon && !!item.icon_state && ( + - ); - })} - {lines.map((line, i) => { - const ly = top + i; - if (line.kind === 'gap') { - return null; - } - if (line.kind === 'group') { - return ( - - {pad(line.text.toUpperCase(), iw)} - + )} + {nameLines.map((l, j) => ( + + {l} + + ))} + {/* Centred over the last column of keys (STYLE's `>`): a box about 1.5 cells wide. */} + + , + // The row flashes when it is packed, unpacked, or gives its place to another item. + , + ); + firstItem = false; + y += ih; + opts.forEach((o) => { + const oy = y; + const k = optKey(item.path, o); + const ty2 = oy + (oh - 1) / 2; + const auto = !quiet && from === k ? 5 : undefined; + let label = ''; + let onPress: (() => void) | undefined; + let value: ReactNode = null; + const entry = kit[item.path] || {}; + switch (o.kind) { + case 'colour': { + label = o.slots > 1 ? `COLOUR ${o.slot + 1}` : 'COLOUR'; + const hex = slotColors(entry, o.slots)[o.slot]; + const lbl = label; + onPress = () => + sub( + , + lbl, + k, + ); + value = ( + <> + + + {hex.toUpperCase()} + + ); + break; } - const item = line.item; - if (line.kind === 'item') { - return ( - toggle(item)} - /> + case 'style': { + label = 'STYLE'; + const skins = item.reskins || []; + const cur = skinOf(item, entry.reskin); + const step = (by: number) => { + const n = skins.length; + const at = Math.max(0, skins.indexOf(cur!)); + act('char_kit_skin', { + path: item.path, + skin: skins[(((at + by) % n) + n) % n].name, + }); + }; + onPress = () => sub(, 'STYLE', k); + value = ( + <> + + {cut(safe(cur?.name || ''), 14)} + + {skins.length > 1 && ( + + )} + ); + break; } - if (line.kind === 'color') { - const cols = slotColors(kit[item.path], line.slots); - return ( - 1 ? `COLOUR ${line.slot + 1}` : 'COLOUR', - OPT_W, - )} - value={cols[line.slot]} - recent={recent} - onSet={(color) => - act('char_kit_color', { - path: item.path, - slot: line.slot, - color, - }) - } - /> + case 'name': + label = 'NAME'; + value = ; + break; + case 'worn': { + label = 'WORN'; + const over = entry.layer === 1 || (entry.layer as unknown) === true; + const flip = () => act('char_kit_layer', { path: item.path }); + onPress = flip; + value = ( + <> + + {over ? 'OVER SUIT' : 'UNDER SUIT'} + + + ); + break; } - if (line.kind === 'skin') { - return ( - act('char_kit_skin', { path: item.path, skin })} - /> + case 'lips': { + label = 'LIPS'; + const curLip: Lip = (LIPS as readonly string[]).includes(String(entry.layer)) + ? (entry.layer as Lip) + : 'Middle'; + const lip = (by: number) => + act('char_kit_lip', { + path: item.path, + style: + LIPS[(LIPS.indexOf(curLip) + by + LIPS.length) % LIPS.length], + }); + onPress = () => lip(1); + value = ( + <> + + {curLip.toUpperCase()} + + + ); + break; } - return ( - act('char_kit_name', { path: item.path, name })} - /> - ); - })} - {pages.length > 1 && ( - - )} - {!!wide && ( - { - const t = tabOf(path); - if (t >= 0) { - setCat(t); - setPage(1); - } - }} - /> - )} - - ); -} + } + rows.push( + + + {label} + + {value} + , + ); + y += oh; + }); + }); -function CatRow(props: { - x: number; - y: number; - name: string; - count: number; - cur: boolean; - onClick: () => void; -}) { - const { x, y, name, count, cur, onClick } = props; + const empty = open < 0 && !items.length; return ( <> - {!!cur && ( - - {' '.repeat(CAT_W)} - - )} - - {pad(name.toUpperCase(), CAT_W - 3)} - - {count > 0 && ( - - {String(count)} - + {idColumn} + {empty ? ( + <> + + + + ) : ( + // The mouse wheel over the items turns their pages, one a notch. +
+ {rows} +
)} - - - ); -} - -function ItemRow(props: { - x: number; - y: number; - w: number; - name: string; - on: boolean; - onClick: () => void; -}) { - const { x, y, w, name, on, onClick } = props; - const [hover, setHover] = useState(false); - const label = pad(name, Math.max(4, w - 4)); - return ( - <> - - {on ? '[*]' : '[ ]'} - - - {label} - - { + setFresh(false); + setPage(p - 1); + }} + right /> - - ); -} - -function SkinRow(props: { - x: number; - y: number; - w: number; - item: LoadoutItem; - current?: string; - onSkin: (skin: string) => void; -}) { - const { x, y, w, item, current, onSkin } = props; - const skins = item.reskins || []; - let i = skins.findIndex((s) => s.name === current); - if (i < 0) { - i = Math.max( - 0, - skins.findIndex((s) => s.skin_icon_state === item.icon_state), - ); - } - const step = (d: number) => - onSkin(skins[(i + d + skins.length) % skins.length].name); - return ( - <> - - {'STYLE'} - - step(-1)} - onNext={() => step(1)} - /> - - ); -} - -function NameRow(props: { - x: number; - y: number; - w: number; - current: string; - onName: (name: string) => void; -}) { - const { x, y, w, current, onName } = props; - const [text, setText] = useState(current); - useEffect(() => setText(current), [current]); - const dirty = text.trim() !== current; - // The field takes the row; SET (9 cells) takes its end while there is an edit. - const fw = Math.max(8, Math.min(KIT_NAME_MAX, w - 7 - (dirty ? 9 : 0))); - // The server refuses markup characters, slashes and anything outside printable ASCII. - const ok = - text.trim().length <= KIT_NAME_MAX && - NAME_OK.test(text) && - !NAME_BAD.test(text); - const send = () => { - if (ok) { - onName(text.trim()); - } - }; - return ( - <> - - {'NAME'} - - 1 ? 1.25 : 0)} + k={`${open}:${pg}`} + n={(open + 1) * 1000 + pg} /> - {!!dirty && ( - - )} - - ); -} - -function KitPager(props: { - x: number; - y: number; - page: number; - pages: number; - onPage: (page: number) => void; -}) { - const { x, y, page, pages, onPage } = props; - return ( - <> - {page > 1 ? ( - onPage(page - 1)}> - {' < '} - - ) : ( - - {' < '} - - )} - - {`${page}/${pages}`} - - {page < pages ? ( - onPage(page + 1)}> - {' > '} - - ) : ( - - {' > '} - - )} - - ); -} - -function Packed(props: { - x: number; - y: number; - w: number; - h: number; - tabs: LoadoutCategory[]; - kit: Kit; - kitColors: Record; - onJump: (path: string) => void; -}) { - const { x, y, w, h, tabs, kit, kitColors, onJump } = props; - const names: Record = {}; - for (const t of tabs) { - for (const it of t.contents) { - names[it.path] = it.name; - } - } - const packed = Object.keys(kit).filter((p) => !!names[p]); - const max = Math.max(0, h - 3); - return ( - <> - - {packed.slice(0, max).map((path, i) => { - const slots = kitColors[path] || 0; - const own = kit[path]?.name; - return ( - onJump(path)} - /> - ); - })} - - ); -} - -function Packline(props: { - x: number; - y: number; - w: number; - name: string; - color: string | null; - onClick: () => void; -}) { - const { x, y, w, name, color, onClick } = props; - return ( - <> - - {pad(name, w)} - - {!!color && } ); } diff --git a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/LeaveCrew.tsx b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/LeaveCrew.tsx new file mode 100644 index 00000000000..22c4e49554c --- /dev/null +++ b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/LeaveCrew.tsx @@ -0,0 +1,56 @@ +/** + * LEAVE CREW: asked before commission, requisition or load founds a new crew while the player + * belongs to one (spec 02, 2.4). The focus starts on [ STAY ]; Escape is STAY. The right-hand + * key is the only thing on the page that sends leave_crew 1. + */ +import { Back, usePager } from './nav'; +import { BODY_Y, Btn, Dialog, Put, safe, useGrid, wrapMax } from './term'; + +const W = 45; +const TEXT_W = 41; + +export function LeaveCrew(props: { + /** The crew's name (the ship's name, 46 at most). */ + crew: string; + /** The key that opened it: COMMISSION, REQUISITION or LOAD. */ + label: string; + onStay: () => void; + onGo: () => void; +}) { + const { crew, label, onStay, onGo } = props; + const { cols, rows, cw, ch } = useGrid(); + // PageUp / PageDown do nothing while this is open (the fit underneath would change step). + usePager(() => undefined); + const lines = wrapMax(`THIS LEAVES ${safe(crew).toUpperCase()}.`, TEXT_W, 3); + const n = lines.length; + const x = Math.floor((cols - W) / 2); + const y = BODY_Y + 2; + const keyY = y + n + 2; + return ( + <> + {/* The screen under the dialog at 35 %. Clicks stop here. */} +
e.stopPropagation()} + /> + + + {lines.map((line, i) => ( + + {line} + + ))} + + + + + ); +} diff --git a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/Menu.tsx b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/Menu.tsx new file mode 100644 index 00000000000..32c90f7c287 --- /dev/null +++ b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/Menu.tsx @@ -0,0 +1,419 @@ +/** + * The side menu (side mode) and the key bar with its MENU list (bar mode). + * + * Side menu, rows of the menu region: the symbol, the wordmark, READY (or IN LINE), OBSERVE, + * CHARACTER with the character's name under it, a rule, the five utility items, START for a + * local admin, and the credit line at the foot. Its box ends level with the main box. + * + * Bar mode keeps READY (or IN LINE), OBSERVE, CHARACTER and START as keys along the bottom and + * folds the utility items into MENU. The symbol, wordmark, credit and character name are cut. + */ +import { useEffect, useState } from 'react'; +import { useBackend } from 'tgui/backend'; + +import { Emblem } from './Emblem'; +import { sfx, useBlink, useChanged, useChangedNow } from './motion'; +import { Back, FocusScope } from './nav'; +import { + Box, + type Cls, + HRule, + Key, + type KeyKind, + type KeyState, + Put, + safe, + useGrid, + WipeAt, + wrapMax, +} from './term'; +import type { LobbyData } from './types'; + +/** How long READY's fill takes to sweep in, and to retract, in ms. */ +const READY_ON_MS = 180; +const READY_OFF_MS = 120; + +/** + * The top key shows before the round (READY) and, once it runs, only while the player is in + * the popcap line. Joining itself is SIGN ON, COMMISSION or MOVE IN on the tabs. + */ +const hasTop = (data: LobbyData) => + data.phase === 'loading' || + data.phase === 'pregame' || + data.phase === 'setup' || + (data.phase === 'playing' && (data.queue > 0 || !!data.queue_go)); + +/** READY before the round; IN LINE / YOUR TURN while waiting for a place. */ +function topKey(data: LobbyData, sweep: 'on' | 'off' | null, now: boolean) { + const { phase } = data; + const ready = !!data.ready; + if (phase === 'loading' || phase === 'pregame' || phase === 'setup') { + // While the fill sweeps in the key keeps its rest look under it; [#] shows when it lands. + const on = ready && sweep !== 'on'; + return { + label: 'READY', + right: on ? '[#]' : '[ ]', + rightCls: undefined as Cls | undefined, + state: (phase === 'setup' ? 'dead' : on ? 'on' : 'idle') as KeyState, + action: 'ready', + }; + } + const go = !!data.queue_go; + return { + label: go ? 'YOUR TURN' : 'IN LINE', + right: go ? '' : String(Math.min(999, data.queue)), + rightCls: 'amb' as Cls, + // First in line with a place free: the key takes the accent fill every other half second. + state: (phase !== 'playing' ? 'dead' : now ? 'on' : 'idle') as KeyState, + action: 'join', + }; +} + +/** + * The READY / JOIN key of the side menu and of the key bar. + * + * READY's fill follows what the server says, not the press: it sweeps in left to right when + * the player becomes ready and retracts when they stop. In line, the place flashes when it + * changes, and the key blinks when the player is first and a place is free. + */ +function TopKey(props: { + x: number; + y: number; + w: number; + h?: number; + kind: KeyKind; +}) { + const { data, act } = useBackend(); + const { phase } = data; + const before = phase === 'loading' || phase === 'pregame'; + const [sweep, setSweep] = useState<'on' | 'off' | null>(null); + // Before the paint, so the key is never drawn already filled ahead of its sweep. + useChangedNow(!!data.ready, (_, ready) => { + if (before) { + setSweep(ready ? 'on' : 'off'); + sfx(ready ? 'ready_on' : 'ready_off'); + } + }); + useEffect(() => { + if (!sweep) { + return; + } + const id = setTimeout( + () => setSweep(null), + sweep === 'on' ? READY_ON_MS : READY_OFF_MS, + ); + return () => clearTimeout(id); + }, [sweep]); + const queue = phase === 'playing' ? data.queue : 0; + useChanged(queue, (_, place) => { + if (place > 0) { + sfx('queue'); + } + }); + const now = useBlink(phase === 'playing' && !!data.queue_go, 500); + const top = topKey(data, before ? sweep : null, now); + return ( + act(top.action)} + /> + ); +} + +type Util = { + label: string; + action: string; + state: KeyState; + /** Instead of sending `action`: SETTINGS opens the terminal's own screen. */ + onClick?: () => void; +}; + +/** + * WIKI, RULES, POLLS, MANIFEST, SETTINGS, CHANGELOG. SETTINGS opens the terminal's SETTINGS + * screen (lit while it is open); WIKI and RULES open the server's pages in the player's + * browser. POLLS, MANIFEST and CHANGELOG are switched off for now and draw dead. + */ +function utilities( + data: LobbyData, + settings?: Pick, +): Util[] { + return [ + { label: 'WIKI', action: 'wiki', state: data.wiki ? 'idle' : 'dead' }, + { label: 'RULES', action: 'rules', state: data.rules ? 'idle' : 'dead' }, + { label: 'POLLS', action: 'polls', state: 'dead' }, + { label: 'MANIFEST', action: 'manifest', state: 'dead' }, + { + label: 'SETTINGS', + action: 'settings', + state: !data.prefs_ready + ? 'dead' + : settings?.settingsOpen + ? 'lit' + : 'idle', + onClick: settings?.onSettings, + }, + { label: 'CHANGELOG', action: 'changelog', state: 'dead' }, + ]; +} + +const canStart = (data: LobbyData) => + !!data.localhost_admin && + (data.phase === 'loading' || data.phase === 'pregame'); + +/** The credit line at the foot of the side menu. */ +const CREDIT = 'AN ORIGINAL SERVER MADE BY JACKRIP'; + +const beforeRound = (data: LobbyData) => + data.phase === 'loading' || data.phase === 'pregame'; + +type MenuProps = { + /** The CHARACTER screen is open. */ + charOpen: boolean; + onCharacter: () => void; + /** The SETTINGS screen is open. */ + settingsOpen: boolean; + onSettings: () => void; + onObserve: () => void; +}; + +/** The side menu, drawn in the 19-column menu region. */ +export function SideMenu(props: MenuProps) { + const { charOpen, onCharacter, onObserve } = props; + const { data, act } = useBackend(); + const { rows, cw, ch } = useGrid(); + const prefs = !!data.prefs_ready; + // The box ends level with the main box (one row above the region's foot). + const boxH = rows - 1; + const k = Math.max(1, Math.floor((15 * cw) / 64)); + const fullName = safe(data.char_name).toUpperCase(); + // Up to two lines under CHARACTER; a second line pushes the rule and the list down a row. + const name = fullName ? wrapMax(fullName, 15, 2) : []; + // Without the top key, everything under it moves up into its place. + const top = hasTop(data); + const dy = top ? 0 : -2.25; + // The rule sits a quarter row under the name, as the name sits a quarter row under CHARACTER. + const ruleY = 15.25 + dy + Math.max(0, name.length - 1); + // Utility rows: 1.25 rows each when the menu has room (as in the approved stills), else 1. + const start = canStart(data); + const utils = utilities(data, props); + const items = utils.length + (start ? 1 : 0); + // The foot of the menu carries the server's credit line, with half a row free above it. On a + // short menu where the list would run into it, the credit gives way. + const credit = wrapMax(CREDIT, 17, 3); + const roomWith = boxH - (credit.length + 0.5) - 0.5 - (ruleY + 0.5); + const port = roomWith >= items ? credit : []; + const room = port.length ? roomWith : boxH - 0.5 - (ruleY + 0.5); + // The credit's last line sits half a row above the box's foot. + const portY = boxH - 0.5 - port.length; + const step = room >= items * 1.25 ? 1.25 : 1; + return ( + <> + + + + V O I D C R E W + + {!!top && } + + + {name.map((line, i) => ( + + {line} + + ))} + + {utils.map((u, i) => ( + act(u.action))} + /> + ))} + {!!start && ( + act('start_now')} + /> + )} + {port.map((line, i) => ( + + {line} + + ))} + + ); +} + +/** The key bar along the bottom in bar mode (its own 1.5-row region). */ +export function KeyBar( + props: MenuProps & { menuOpen: boolean; onMenu: () => void }, +) { + const { charOpen, onCharacter, onObserve, menuOpen, onMenu } = props; + const { data, act } = useBackend(); + // Without the top key the others move left into its place. + const top = hasTop(data); + const dx = top ? 0 : -16; + return ( + <> + {!!top && } + + + {!!canStart(data) && ( + act('start_now')} + /> + )} + + + ); +} + +/** MENU's list in bar mode, over the bottom right of the main region. */ +export function MenuPopup( + props: Pick & { + onClose: () => void; + }, +) { + const { onClose } = props; + const { data, act } = useBackend(); + const { rows } = useGrid(); + const items = utilities(data, props); + // One row an item and half a row above and below. + const h = items.length + 1; + const y = rows - h; + const first = items.findIndex((u) => u.state !== 'dead'); + return ( + <> +
{ + e.stopPropagation(); + onClose(); + }} + /> +
+ + + + + {items.map((u, i) => ( + { + onClose(); + if (u.onClick) { + u.onClick(); + } else { + act(u.action); + } + }} + /> + ))} + +
+ + ); +} diff --git a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/Notice.tsx b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/Notice.tsx index ac6bbe1d53f..56bc31bd6b4 100644 --- a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/Notice.tsx +++ b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/Notice.tsx @@ -1,60 +1,154 @@ +import { useEffect } from 'react'; import { useBackend } from 'tgui/backend'; -import { useBack } from './nav'; -import { Btn, Frame, Put, pad, TOP, useGrid, wrapMax } from './term'; +import { foundingSent, sfx, useScreen } from './motion'; +import { Back } from './nav'; +import { + Band, + BODY_Y, + Box, + BOX_Y, + Btn, + Dialog, + Put, + safe, + useGrid, + wrapMax, +} from './term'; import type { LobbyData } from './types'; -/** The CONFIRMED box (kind "ok"), drawn instead of the tab content. */ +/** The notice that last sounded: a notice sounds once, however often it is drawn again. */ +let soundedAt: number | null = null; + +/** TRUE the first time it is asked about the notice set at `at`. */ +function firstSound(at: number) { + if (soundedAt === at) { + return false; + } + soundedAt = at; + return true; +} + +/** How long a notice stays before it clears itself, in ms. */ +const NOTICE_LIFE = { warn: 8000, bad: 10000 } as const; + +/** Notice text: column 2 to column 60. */ +const NOTICE_W = 59; + +/** The empty main box, for what draws a dialog instead of a screen. */ +export function EmptyBox() { + const { rows } = useGrid(); + return ; +} + +/** + * The CONFIRMED box (kind "ok"), drawn over the empty main box instead of the screen. It wipes + * in with the stamp; when it answers a commission, a requisition or a load, the long job + * under it starts a moment later. + */ export function Confirmed() { const { data, act } = useBackend(); const { cols } = useGrid(); const notice = data.notice; - useBack(notice ? () => act('dismiss') : null); + const dismiss = () => act('dismiss', notice ? { at: notice.at } : {}); + // The box has its own wipe and sound; the screen that comes back after it wipes as a step back. + useScreen('confirmed', 9, '', 0, true); + const at = notice?.at; + useEffect(() => { + if (at === undefined || !firstSound(at)) { + return; + } + sfx('stamp'); + if (foundingSent()) { + sfx('working', { when: 0.2 }); + } + }, [at]); if (!notice) { return null; } - const w = Math.min(44, cols - 2); - const x = Math.floor(cols / 2) - Math.floor(w / 2); - const lines = wrapMax(notice.text.toUpperCase(), w - 6, 3); - const h = 7 + lines.length; + const lines = wrapMax(safe(notice.text).toUpperCase(), 41, 3); + const n = lines.length; + const x = Math.floor((cols - 45) / 2) + 2; + // The Dialog's top row. + const y = BODY_Y + 2; return ( - - {lines.map((line, i) => ( - - {line} + <> + + + + {lines.map((line, i) => ( + + {line} + + ))} + + STAND BY. + - ))} - - STAND BY. - - act('dismiss')} - /> - + + + ); } -/** One amber or red line on the bottom row. Click to clear it. */ +/** + * The notice row under the main box (kinds warn and bad): amber on a faint band, or ink on a + * red band. Two lines at most; a second line grows the band upward over the box's bottom edge. + * A click clears it, and it clears itself after a few seconds. + */ export function NoticeLine() { const { data, act } = useBackend(); - const { cols, rows } = useGrid(); + const { rows } = useGrid(); const notice = data.notice; + const kind = notice?.kind; + const at = notice?.at; + useEffect(() => { + if (kind !== 'warn' && kind !== 'bad') { + return; + } + if (at !== undefined && firstSound(at)) { + sfx(kind); + } + const id = setTimeout(() => act('dismiss', { at }), NOTICE_LIFE[kind]); + return () => clearTimeout(id); + }, [kind, at]); if (!notice || notice.kind === 'ok') { return null; } + const bad = notice.kind === 'bad'; + const lines = wrapMax(safe(notice.text).toUpperCase(), NOTICE_W, 2); + const top = rows - lines.length; + const clear = () => act('dismiss', { at: notice.at }); + // Its own layer: over everything on the screen (picture wells and keys included), under dialogs. + // Keyed by the notice, so each new one draws its band left to right (a bad one then blinks twice). return ( - act('dismiss')} +
- {pad(notice.text.toUpperCase(), cols - 2)} - + {lines.length > 1 && ( + + )} + + {lines.map((line, i) => ( + + {line} + + ))} +
); } diff --git a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/ObserveConfirm.tsx b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/ObserveConfirm.tsx new file mode 100644 index 00000000000..649c1ff2d63 --- /dev/null +++ b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/ObserveConfirm.tsx @@ -0,0 +1,60 @@ +/** + * OBSERVE, asked in the terminal: a small box over the current screen with STAY focused, so a + * slipped key never takes a player out of the round. Escape is STAY. + */ +import { useBackend } from 'tgui/backend'; + +import { quietDialogClose } from './motion'; +import { Back } from './nav'; +import { BODY_Y, Btn, Dialog, Put, useGrid } from './term'; +import type { LobbyData } from './types'; + +const W = 43; + +const COME_BACK: Record = { + same: ['YOU CAN SIGN ON AGAIN LATER.', 'dim'], + new: ['YOU CAN SIGN ON LATER AS SOMEONE ELSE.', 'dim'], + none: ['YOU WILL SIT THIS ROUND OUT.', 'amb'], +}; + +export function ObserveConfirm(props: { onClose: () => void }) { + const { onClose } = props; + const { data, act } = useBackend(); + const { cols } = useGrid(); + const x = Math.floor((cols - W) / 2); + const y = BODY_Y + 2; + const [line, cls] = COME_BACK[data.respawn || 'same'] || COME_BACK.same; + return ( + <> +
{ + e.stopPropagation(); + onClose(); + }} + /> + + + + LEAVE THE OFFICE AND WATCH THE ROUND? + + + {line} + + + { + // Answered, not backed out of: the box goes without the back sound. + quietDialogClose(); + onClose(); + act('observe_confirm'); + }} + /> + + + ); +} diff --git a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/PlanPic.tsx b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/PlanPic.tsx index 6906b480afe..c972ef72761 100644 --- a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/PlanPic.tsx +++ b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/PlanPic.tsx @@ -1,10 +1,11 @@ /** - * A saved ship as a line drawing from its survey plan string: rows split by '/', each a - * run-length list of cells (`12o` = twelve floor). '#' wall, 'g' window, 'o' floor, + * A saved ship as a line drawing from its survey plan string (spec 02, 5.2): rows split by '/', + * each a run-length list of cells (`12o` = twelve floor). '#' wall, 'g' window, 'o' floor, * 'e' engine, 'w' weapon, 's' sensor, 't' cargo, '.' nothing. Walls are joined centre to - * centre. A tall hull lies on its side when the space is wide. + * centre. The plan is drawn whichever way round gives the larger scale. Drawn in theme + * colours; `faded` for a save that cannot load. */ -import { useMemo } from 'react'; +import { type CSSProperties, useMemo } from 'react'; import { useGrid } from './term'; @@ -12,7 +13,7 @@ function parsePlan(plan: string): string[][] { return plan.split('/').map((row) => { const out: string[] = []; for (const m of row.matchAll(/(\d*)(\D)/g)) { - const n = m[1] ? Number(m[1]) : 1; + const n = m[1] ? Math.min(512, Number(m[1])) : 1; for (let i = 0; i < n; i++) { out.push(m[2]); } @@ -21,7 +22,20 @@ function parsePlan(plan: string): string[][] { }); } +/** Turned a quarter turn clockwise. */ +function turn(rows: string[][], W: number, H: number): string[][] { + const rot: string[][] = []; + for (let cx = 0; cx < W; cx++) { + rot.push([]); + for (let cy = H - 1; cy >= 0; cy--) { + rot[cx].push(rows[cy][cx] || '.'); + } + } + return rot; +} + export function PlanPic(props: { + /** Cells, from the parent's top-left corner (the Well). */ x: number; y: number; w: number; @@ -32,8 +46,8 @@ export function PlanPic(props: { }) { const { x, y, w, h, plan, faded } = props; const { cw, ch } = useGrid(); - const aw = w * cw; - const ah = h * ch; + const aw = Math.max(1, w * cw); + const ah = Math.max(1, h * ch); const drawing = useMemo(() => { let rows = parsePlan(plan); @@ -42,15 +56,9 @@ export function PlanPic(props: { if (!W || !H) { return null; } - if (H > W * 1.15 && aw > ah) { - const rot: string[][] = []; - for (let cx = 0; cx < W; cx++) { - rot.push([]); - for (let cy = H - 1; cy >= 0; cy--) { - rot[cx].push(rows[cy][cx] || '.'); - } - } - rows = rot; + // Whichever way round gives the larger scale. + if (Math.min(aw / H, ah / W) > Math.min(aw / W, ah / H) * 1.001) { + rows = turn(rows, W, H); [W, H] = [H, W]; } const k = Math.min(aw / W, ah / H); @@ -60,7 +68,7 @@ export function PlanPic(props: { let lines = ''; let glass = ''; let eng = ''; - const dots: [number, number, string][] = []; + const dots: [number, number][] = []; for (let cy = 0; cy < H; cy++) { for (let cx = 0; cx < W; cx++) { const c = at(cx, cy); @@ -96,7 +104,7 @@ export function PlanPic(props: { } else if (c === 'e') { eng += `M${cx * k + k * 0.15} ${cy * k + k * 0.15}h${k * 0.7}v${k * 0.7}h-${k * 0.7}z`; } else if (c === 'w' || c === 's' || c === 't') { - dots.push([px, py, c]); + dots.push([px, py]); } } } @@ -107,44 +115,46 @@ export function PlanPic(props: { return null; } const { W, H, k, floor, lines, glass, eng, dots } = drawing; - const ph = faded ? '#2b6450' : '#7effbf'; - const dim = faded ? '#1d4636' : '#3f9a76'; - const amb = faded ? '#5a4a15' : '#ffc41f'; - const red = faded ? '#5a2a30' : '#ff5f6f'; - const sw = Math.max(1.2, k * 0.18); + const small = k < 3; + const wallC = faded ? 'var(--lt-faint)' : 'var(--lt-fg)'; + const markC = faded ? 'var(--lt-edge-dead)' : 'var(--lt-dim)'; + const dotC = faded ? 'var(--lt-edge-dead)' : 'var(--lt-acc)'; + const sw = small ? 1 : Math.max(1.2, k * 0.18); + const stroke = (c: string, extra?: CSSProperties): CSSProperties => ({ + stroke: c, + strokeWidth: sw, + fill: 'none', + ...extra, + }); return (
- - - {dots.map(([cx, cy, c], i) => ( + + + {dots.map(([cx, cy], i) => ( ))} diff --git a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/RolesEditor.tsx b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/RolesEditor.tsx index 995131f3d8f..44ed9ea16f8 100644 --- a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/RolesEditor.tsx +++ b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/RolesEditor.tsx @@ -1,57 +1,121 @@ /** - * ROLES (CHARACTER-PLAN 2.6): one row per ship role category, NEVER/LOW/MED/HIGH, char_role. - * Owner: C4. + * ROLES (design 03b section 1): one row a role with four labelled keys, NEVER, LOW, MED and + * HIGH (char_role). The ID column shows the focused role's uniform on the body and, under it, + * the berths that role covers (char_static.roles titles). * - * The box is the editor's frame as CharacterTab draws it: x and w are the frame's outer - * columns, y is the row under the frame's top line, y + h - 1 the frame's bottom line. - * Only one category may be HIGH; the server demotes the old HIGH to MED (Q3). A click - * shows that at once and the next push overwrites it. + * Only one role may be HIGH: the server drops the old HIGH to MED. A press shows that at once + * from a local copy; the next push replaces it. + * + * The preview follows the focus: 250 ms after the focus rests on a row the page sends + * char_dress for that role, and char_dress '' when ROLES closes. */ -import { Fragment, useEffect, useState } from 'react'; +import { useEffect, useRef, useState } from 'react'; import { useBackend } from 'tgui/backend'; -import { Blocks, Hit, Put, pad, useGrid } from './term'; -import type { CellBox, LobbyData, RoleLevel } from './types'; - -const LEVELS = ['NEVER', 'LOW', 'MED', 'HIGH'] as const; -/** Cells per level column. */ -const COL = 7; +import { + clamp, + ID_W, + ID_X, + IdColumn, + planId, + q, + useChar, + WORK_W, + WORK_X, +} from './CharFrame'; +import { sfxInstead } from './motion'; +import { + BODY_Y, + bodyRows, + cut, + FlashAt, + Key, + Put, + Slab, + safe, + useGrid, +} from './term'; +import type { LobbyData, RoleLevel } from './types'; type Levels = Record; -/** An empty level cell: a faint outline the size of the lit block. */ -function Slot(props: { x: number; y: number }) { - const { x, y } = props; - const { cw, ch, s } = useGrid(); - return ( -
- ); +/** The four keys: label, first column, width. */ +const KEYS: [label: string, x: number, w: number][] = [ + ['NEVER', 39, 7], + ['LOW', 46, 5], + ['MED', 51, 5], + ['HIGH', 56, 6], +]; + +/** How long the focus rests on a row before the preview is dressed in its uniform. */ +const DRESS_MS = 250; + +/** The berth titles of a char_static.roles entry (older servers sent one joined string). */ +function titlesOf(entry: [string, string[] | string]): string[] { + const t = entry[1]; + if (Array.isArray(t)) { + return t; + } + return t ? String(t).split(', ') : []; } -export function RolesEditor(props: CellBox) { - const { x, y, w, h } = props; +export function RolesEditor() { const { act, data } = useBackend(); + const { quiet } = useChar(); + const { rows: M } = useGrid(); const char = data.char; - const roles = data.char_static?.roles || []; - // Local copy after a click, dropped on the next push (a refused edit pushes too). + const roles = (data.char_static?.roles || []).filter( + (r) => titlesOf(r).length > 0, + ); + // Local copy after a press, dropped on the next push (a refused edit pushes too). const [local, setLocal] = useState(null); useEffect(() => setLocal(null), [char]); + const levels: Levels = local || char?.roles || {}; + + // First focus: the lit key of the highest role, else the first row's NEVER. + let top = 0; + let topLevel = 0; + roles.forEach(([cat], i) => { + const lv = levels[cat] || 0; + if (lv > topLevel) { + top = i; + topLevel = lv; + } + }); + const [focusRow, setFocusRow] = useState(top); + const row = Math.min(focusRow, Math.max(0, roles.length - 1)); + const focusCat = roles[row]?.[0] || ''; + + // Dress the preview in the focused row's uniform once the focus rests there. + const dress = char?.dress || ''; + const sent = useRef(false); + useEffect(() => { + if (!focusCat || focusCat === dress) { + return; + } + const t = window.setTimeout(() => { + sent.current = true; + act('char_dress', { category: focusCat }); + }, DRESS_MS); + return () => window.clearTimeout(t); + }, [focusCat, dress]); + useEffect( + () => () => { + if (sent.current) { + act('char_dress', { category: '' }); + } + }, + [], + ); + if (!char) { return null; } - const levels: Levels = local || char.roles || {}; const set = (category: string, level: 0 | RoleLevel) => { + if ((levels[category] || 0) === level) { + return; + } const next: Levels = {}; for (const [cat, lv] of Object.entries(levels)) { next[cat] = level === 3 && lv === 3 ? 2 : lv; @@ -61,99 +125,92 @@ export function RolesEditor(props: CellBox) { } else { delete next[category]; } + if (level === 3) { + // The one role set HIGH: the accepted sound, in place of the key press. + sfxInstead('ok'); + } setLocal(next); act('char_role', { category, level }); }; - const L = x + 3; - const cols = x + w - 3 - 4 * COL; - const nameW = 13; - const exW = cols - L - nameW - 3; - const hy = y + 1; - // Double spacing when the rows fit, as the mockup. - const step = h - 3 >= roles.length * 2 ? 2 : 1; - const first = hy + 1 + (step === 2 ? 1 : 0); - - return ( + // ---- ID column: BERTHS under the picture, top-anchored. + const most = Math.max(1, ...roles.map((r) => titlesOf(r).length)); + const plan = planId( + M, + 4.25, + (la) => 1.25 + Math.min(most, Math.max(1, Math.floor(la - 1.25)), 7), + ); + const listY = BODY_Y + plan.pv + 2.25; + const room = M - 1.25 - listY; + const titles = roles[row] ? titlesOf(roles[row]) : []; + const lines = Math.min(titles.length, Math.max(1, Math.floor(room - 1.25)), 7); + const over = titles.length > lines; + const shown = titles.slice(0, over ? lines - 1 : lines); + const berths = ( <> - {LEVELS.map((label, i) => ( - - {label} + + {'BERTHS'} + + {shown.map((t, i) => ( + + {cut(safe(t), ID_W)} ))} - {roles.map(([category, examples], ri) => ( - set(category, lv)} - /> - ))} + {!!over && ( + + {`+${titles.length - shown.length} MORE`} + + )} ); -} -function RoleRow(props: { - x: number; - y: number; - cols: number; - nameW: number; - exW: number; - category: string; - examples: string; - level: 0 | RoleLevel; - onSet: (level: 0 | RoleLevel) => void; -}) { - const { x, y, cols, nameW, exW, category, examples, level, onSet } = props; + // ---- work column: one row a role. + const B = bodyRows(M); + const r = Math.max(1, roles.length); + const h = clamp(q((B + 0.25) / r - 0.25), 1.25, 4.5); + const pitch = h + 0.25; + return ( <> - - {pad(category.toUpperCase(), nameW)} - - {exW >= 12 && !!examples && ( - - {pad(examples, exW)} - - )} - {LEVELS.map((label, i) => { - const cx = cols + i * COL + 2; - const on = i === level; + + {berths} + + {roles.map(([cat], i) => { + const y = BODY_Y + i * pitch; + const level = levels[cat] || 0; return ( - - {on ? ( - + + {cut(safe(cat).toUpperCase(), 13)} + + {KEYS.map(([label, kx, kw], li) => ( + - ) : ( - - )} - { - if (!on) { - onSet(i as 0 | RoleLevel); + w={kw} + h={h} + kind="cap" + label={label} + state={ + li === 0 || li !== level ? 'idle' : li === 3 ? 'on' : 'lit' } - }} - /> - + auto={!quiet && i === top && li === topLevel ? 5 : undefined} + onClick={() => set(cat, li as 0 | RoleLevel)} + onFocus={(on) => on && setFocusRow(i)} + /> + ))} + {/* The row flashes when its level changes, also when another HIGH takes its place. */} + + ); })} diff --git a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/SaveSlots.tsx b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/SaveSlots.tsx index 75387e21a85..126b2b0c8f7 100644 --- a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/SaveSlots.tsx +++ b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/SaveSlots.tsx @@ -1,335 +1,377 @@ /** - * SAVED SHIPS box on the shipyard home: one card per slot with the ship's floor plan, - * name, class, what it carries and LOAD, a denial line, or UNDER WAY. Too narrow for three - * cards, it becomes a one-line-per-slot list. + * SAVED SHIPS on the shipyard home (spec 02, 3.2): always three slot slabs. Full slots carry + * the saved hull's plan in a well, the name, the class line, what the save carries and + * [ LOAD ]; compact rows (short panes) carry two lines and the key. States: EMPTY, ready, + * ready before the port opens (LOAD dead), UNDER WAY, refused (the reason in amber, the plan + * faded). The box itself: `wait` and `off` draw one ghost block with the state. */ import type { ReactNode } from 'react'; -import { useBackend } from 'tgui/backend'; import { PlanPic } from './PlanPic'; -import { Blocks, cut, Frame, Put, pad, RPut, wrap, wrapMax } from './term'; -import type { LobbyData, SaveCard } from './types'; -import { Key, thousands, type YardCtx } from './YardTab'; +import { + Big, + CUT, + cut, + Key, + NameLine, + Put, + RPut, + SEP, + Slab, + safe, + Well, + wrapMax, +} from './term'; +import type { SaveCard, YardSaves } from './types'; +import type { HomeForm } from './YardHome'; +import type { YardCtx } from './YardTab'; -const MIN_CARD = 26; +/** Carries text: columns 18 to 46. */ +const CARRY_W = 29; +/** Full slot name: columns 18 to 60. */ +const NAME_W = 43; +/** Class line: 35, then the cut mark. */ +const CLASS_W = 35; +/** Compact row text: columns 3 to 46; a refusal runs to 60. */ +const ROW_W = 44; +const ROW_DENIAL_W = 58; -type Props = { - saves: (SaveCard | null)[]; - x: number; - y: number; - w: number; - h: number; - ctx: YardCtx; -}; +type SlotState = 'empty' | 'ready' | 'under' | 'refused'; -/** LOAD, or CONFIRM after the first press when loading leaves a crew. */ -function useLoad(ctx: YardCtx) { - const { act } = useBackend(); - return (sv: SaveCard) => { - const key = `load${sv.slot}`; - if (ctx.crewChange && ctx.view.confirm !== key) { - ctx.set({ confirm: key }); - return; - } - ctx.set({ confirm: null }); - act('yard_load', { slot: sv.slot, leave_crew: ctx.crewChange ? 1 : 0 }); - }; -} - -export function SaveSlots(props: Props) { - const { saves, x, y, w, h, ctx } = props; - const gap = 2; - const n = Math.max(1, saves.length); - const cardW = Math.floor((w - 4 - gap * (n - 1)) / n); - if (cardW < MIN_CARD || h < 14) { - return ; +function stateOf(card: SaveCard | null): SlotState { + if (!card) { + return 'empty'; } - return ( - - {saves.map((sv, i) => ( - - ))} - - ); + if (card.locked) { + return 'under'; + } + return card.denial ? 'refused' : 'ready'; } -function Card(props: { - sv: SaveCard | null; - n: number; - x: number; - y: number; - w: number; - h: number; - ctx: YardCtx; -}) { - const { sv, n, x, y, w, h, ctx } = props; - const load = useLoad(ctx); - const out: ReactNode[] = []; - if (!sv) { - return ( - - - EMPTY - - - ); +/** ` • berths`; the class drops out when the name starts with it. */ +function classLine(card: SaveCard, name: string): string { + const cls = safe(card.class).trim(); + const n = Math.max(0, Math.min(999, Math.floor(card.crew || 0))); + const berths = `${n} ${n === 1 ? 'berth' : 'berths'}`; + if (!cls || name.startsWith(cls.toUpperCase())) { + return berths; } - const ix = x + 2; - const iw = w - 4; - const denied = !!sv.denial; - const fit = sv.fit || []; + return `${cls} ${SEP} ${berths}`; +} - const lines: [string, number | null, string][] = fit.map((f) => [ - f[0], - f[1], - f[2] ?? 'red', - ]); - if (sv.lab) { - lines.push(['Lab machines', sv.lab, '']); - } - if (sv.cargo) { - lines.push(['Cargo machines', sv.cargo, 'amb']); +/** As many whole items as fit `w` from item `i`; an item longer than `w` is cut. */ +function fitItems(items: string[], i: number, w: number): [string, number] { + let text = ''; + let j = i; + while (j < items.length) { + const next = text ? `${text} ${SEP} ${items[j]}` : items[j]; + if (next.length > w) { + break; + } + text = next; + j++; } - if (sv.research) { - lines.push([`Research, ${sv.research} nodes`, null, '']); + if (!text && j < items.length) { + return [cut(items[j], w), j + 1]; } - if (sv.funds) { - lines.push([`Holds ${thousands(sv.funds)} cr`, null, 'amb']); + return [text, j]; +} + +/** + * The carries run in at most `n` lines of `w`: whole items joined by ` • `; when items are + * left over, the last line ends in the cut mark. + */ +export function carryLines(items: string[], n: number, w: number): string[] { + const out: string[] = []; + let i = 0; + for (let l = 0; l < n && i < items.length; l++) { + let [text, next] = fitItems(items, i, w); + if (l === n - 1 && next < items.length) { + [text, next] = fitItems(items, i, w - 1); + if (!text.endsWith(CUT)) { + text += CUT; + } + } + out.push(text); + i = next; } + return out; +} - const nameRows = Math.min(2, wrap(sv.name.toUpperCase(), iw).length); - const hasStats = sv.mass !== undefined || sv.crew !== undefined; - // Rows below the lines: the key, or a two-line denial, or LEAVES + the key. - const foot = denied ? 2 : 1 + (ctx.crewChange ? 1 : 0); - // The plan shrinks (to 3 rows) before the first few fit lines are cut. - // Short cards drop the blank row under the stats. - const statRows = hasStats ? (h < 15 ? 1 : 2) : 1; - const fixed = 4 + nameRows + 1 + statRows + foot; - const prH = Math.max(2, Math.min(11, h - fixed - Math.min(4, lines.length))); - if (sv.plan) { - out.push( - , +function itemsOf(card: SaveCard): string[] { + return (card.carries || []) + .slice(0, 12) + .map((s) => safe(s).replace(/\s+/g, ' ').trim()) + .filter(Boolean); +} + +export function SaveSlots(props: { + ctx: YardCtx; + state: YardSaves['state']; + /** ok: three entries, null for an empty slot. */ + slots: (SaveCard | null)[]; + plans: (string | null)[]; + form: HomeForm; +}) { + const { ctx, state, slots, plans, form } = props; + const { yB } = form; + // Offline, or not read yet: one ghost block with the state, as the other screens draw theirs. + if (state === 'off' || state === 'wait') { + return ( + + + ); } - let yy = y + 1 + prH + 1; - const nameLines = wrap(sv.name.toUpperCase(), iw); - const nm = nameLines.slice(0, 2); - if (nameLines.length > 2) { - nm[1] = `${pad(nm[1], iw - 1)}.`; - } - nm.forEach((l, i) => { - out.push( - - {l} - , - ); - }); - out.push( - - {pad(sv.class, iw)} - , - ); - if (hasStats) { - if (sv.mass !== undefined) { + const live = ctx.open && !ctx.sent; + const load = (card: SaveCard) => + ctx.found({ + action: 'yard_load', + params: { slot: card.slot }, + label: 'LOAD', + restores: !!card.restores, + }); + const out: ReactNode[] = []; + for (let i = 0; i < 3; i++) { + const card = slots[i] || null; + const st = stateOf(card); + const n = card?.slot || i + 1; + if (form.full) { + const h = form.slotH; out.push( - - MASS - , - - {cut(`${thousands(sv.mass)} t`, sv.crew !== undefined ? 10 : iw - 5)} - , + , ); - } - if (sv.crew !== undefined) { - const cx = sv.mass !== undefined ? ix + 16 : ix; + } else { out.push( - - CREW - , - - {String(sv.crew)} - , + , ); } - yy += statRows; - } else { - yy += 1; } + return <>{out}; +} - const room = Math.max(0, y + h - 2 - foot - yy); - const show = - lines.length > room ? lines.slice(0, Math.max(0, room - 1)) : lines; - show.forEach(([label, count, cls], i) => { - out.push( - void; +}) { + const { n, card, st, ys, h, plan, live, onLoad } = props; + const p = h >= 4.75 ? 0.25 : 0.125; + const wellH = h - 2 * p; + const nC = Math.max(1, Math.min(4, Math.floor(h - 2 * p - 2.25))); + const dead = st === 'empty'; + let well: ReactNode; + if (dead) { + well = ; + } else if (plan) { + well = ( + + + + ); + } else { + well = ; + } + const body: ReactNode[] = []; + if (st === 'empty') { + body.push( + , + // On the class line's row, where a saved ship's slot number sits. + + {`SLOT ${n}`} + , + ); + } else if (card) { + const name = safe(card.name).toUpperCase(); + const quiet = st !== 'ready'; + body.push( + , - - {pad(label, iw - 8)} + + {cut(classLine(card, name), CLASS_W)} , + + {`SLOT ${n}`} + , ); - if (count) { - out.push( - - {cut(String(count), 5)} - , + if (st === 'refused') { + wrapMax(safe(card.denial).toUpperCase(), NAME_W, Math.min(2, nC)).forEach((t, j) => + body.push( + + {t} + , + ), + ); + } else { + carryLines(itemsOf(card), nC, CARRY_W).forEach((t, j) => + body.push( + + {t} + , + ), ); } - yy++; - }); - if (room > 0 && show.length < lines.length) { - out.push( - - {`+${lines.length - show.length} more`} - , - ); - } - - const by = y + h - 2; - if (sv.denial) { - const denial = wrapMax(sv.denial, iw, 2); - denial.forEach((l, i) => { - out.push( - - {l} - , + if (st === 'ready') { + body.push( + onLoad(card)} + />, ); - }); - } else if (sv.locked) { - out.push( - - UNDER WAY - , - ); - } else { - const confirming = ctx.view.confirm === `load${sv.slot}`; - if (ctx.crewChange && confirming) { - out.push( - - {pad(`LEAVES ${ctx.crewChange.toUpperCase()}`, iw)} - , + } else if (st === 'under') { + body.push( + + UNDER WAY + , ); } - out.push( - load(sv)} - />, - ); } - return ( - - {out} - + + {well} + {body} + ); } -/** Narrow windows: one line per slot. */ -function SaveList(props: Props) { - const { saves, x, y, w, h, ctx } = props; - const load = useLoad(ctx); - const out: ReactNode[] = []; - let yy = y + 2; - const keyW = 12; - saves.forEach((sv, i) => { - if (yy > y + h - 2) { - return; - } - const n = sv?.slot || i + 1; - out.push( - - {String(n)} +function RowSlot(props: { + n: number; + card: SaveCard | null; + st: SlotState; + ys: number; + alt: boolean; + live: boolean; + onLoad: (card: SaveCard) => void; +}) { + const { n, card, st, ys, alt, live, onLoad } = props; + const dead = st === 'empty'; + const body: ReactNode[] = []; + if (st === 'empty') { + body.push( + + EMPTY , + + {`SLOT ${n}`} + , ); - if (!sv) { - out.push( - - EMPTY - , - ); - yy += 2; - return; - } - const nameW = Math.max(4, w - 6 - keyW - 4); - out.push( - - {pad(sv.name.toUpperCase(), nameW)} + } else if (card) { + const name = safe(card.name).toUpperCase(); + body.push( + + {cut(name, ROW_W)} , ); - if (sv.denial) { - out.push( - - {pad(sv.denial, w - 9)} + if (st === 'refused') { + body.push( + + {cut(safe(card.denial).toUpperCase(), ROW_DENIAL_W)} , ); - } else if (sv.locked) { - out.push( - + } else { + const items = itemsOf(card); + const head = classLine(card, name); + // Whole items only: a figure cut short ("1,85…") would misread. + const room = ROW_W - head.length - 3; + const [run, next] = fitItems(items, 0, room - 1); + const whole = next > 0 && !run.endsWith(CUT); + const text = whole + ? `${head} ${SEP} ${run}${next < items.length ? CUT : ''}` + : head; + body.push( + + {cut(text.trimEnd(), ROW_W)} + , + ); + } + if (st === 'under') { + body.push( + UNDER WAY , ); - } else { - const confirming = ctx.view.confirm === `load${sv.slot}`; - out.push( - - {pad(sv.class, w - 9)} - , + } else if (st === 'ready') { + body.push( load(sv)} + key="l" + kind="cap" + x={49} + y={ys + 0.375} + w={12} + label="[ LOAD ]" + state={live ? 'idle' : 'dead'} + onClick={() => onLoad(card)} />, ); } - yy += 3; - }); - if (ctx.crewChange && ctx.view.confirm?.startsWith('load')) { - out.push( - - {pad(`LEAVES ${ctx.crewChange.toUpperCase()}`, w - 6)} - , - ); } return ( - - {out} - + + {body} + ); } diff --git a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/Settings.tsx b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/Settings.tsx new file mode 100644 index 00000000000..09110f28236 --- /dev/null +++ b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/Settings.tsx @@ -0,0 +1,166 @@ +/** + * SETTINGS: the terminal's own screen for the game preferences (OPTIONS) and the keybindings + * (KEYS). Opened from the menu like CHARACTER, in the same box; the tab row stays. + * + * Columns of the main region: the list column is 1 to 15 (LIST_X, LIST_W) with the group switch + * OPTIONS | KEYS on top, the search field under it and the categories of the open group under + * that; column 16 is a gap; the work column is 17 to 61 (WORK_X, WORK_W): the open category's + * rows (or the search's), the page mark and, at the foot, the description strip (two dim lines + * about the focused or hovered row). + * + * A row: the name in 19 to 42 (NAME_X, NAME_W), wrapped to two lines in a taller row when + * longer (rowHeight(); never more than two, the second then ends in the cut mark); the value in + * 44 to 61 (VALUE_X, VALUE_W). + * + * ## How a group plugs in (SettingsOptions.tsx, SettingsKeys.tsx) + * + * Everything below is exported from SettingsFrame.tsx. The panes import it from there, not from + * './Settings': Settings.tsx imports the two panes, so a pane importing it back would read its + * constants before they exist. + * + * Each group owns its data (OPTIONS: settings_open/set/close; KEYS: its own settings_keys_* + * actions, which settings_act() routes to settings_keys_act()) and draws the two columns with + * : + * cats its categories for the left list ({id, label}; labels at most 13 characters) + * cat the open one (kept in the group's own state); onCat(id) opens another + * rows SettingsRowSpec[]: key, name (upper case), desc, value(ty, focused) drawing in the + * value zone, onPress (Enter or a click), onStep (Left/Right and the mouse arrows), + * muted; typing rows render a from value() (OPTIONS' number rows) + * focusKey the row that takes the focus when the rows mount (back from a level-2 screen); + * a row's own `claim` does the same when it turns on + * find, onFind the search text (upper case) and its setter; while it is not empty the group + * passes the matching rows of all its categories (OPTIONS by setting name, KEYS by + * action name) and no category is marked. A category press or Escape clears it. + * empty one dim line in place of the rows while the group's data is on its way + * SettingsColumns does the search field, the list, its paging, the rows' paging (PageUp/PageDown, + * the page mark and the mouse wheel), the description strip, Escape from a row up to the list and + * the page wipes, so both groups look and move the same. + * useSettings() gives sub(node, crumb, from) for a level-2 screen in the work column (the frame + * then draws `node` there and the crumbs SETTINGS / / , and Escape or + * [ BACK ] closes it; `node` must read live data itself), closeSub(), subOpen, from (the row that + * opened the last one, to give the focus back), setCrumb(label) (the open category's name, or + * SEARCH, for the crumbs) and home (bumped when SETTINGS is pressed while open: go back to the top + * state). + */ +import { type ReactNode, useEffect, useState } from 'react'; +import { useBackend } from 'tgui/backend'; + +import { type Crumb, Crumbs } from './CharFrame'; +import { useChanged, useScreen } from './motion'; +import { useBack } from './nav'; +import { + GroupSwitch, + SettingsContext, + type SettingsGroup, + type SettingsNav, + WORK_W, + WORK_X, +} from './SettingsFrame'; +import { SettingsKeys } from './SettingsKeys'; +import { SettingsOptions } from './SettingsOptions'; +import { BODY_Y, Box, Put, useGrid, WipeAt } from './term'; +import type { LobbyData } from './types'; + +/** The box, with SAVED on the border for two seconds after a save. */ +function SettingsBox() { + const { rows } = useGrid(); + const { data } = useBackend(); + const [saved, setSaved] = useState(false); + useChanged(data.settings_saved ?? 0, () => setSaved(true)); + useEffect(() => { + if (!saved) { + return; + } + const t = window.setTimeout(() => setSaved(false), 2000); + return () => window.clearTimeout(t); + }, [saved, data.settings_saved]); + return ( + <> + + {!!saved && ( + + {' SAVED '} + + )} + + ); +} + +type Sub = { node: ReactNode; crumb: string; from: string | null }; + +/** + * The screen. home: bumped when SETTINGS is pressed while open (back to the top state); + * onLeave: Escape at the top state (back to the tab that was open before). + */ +export function Settings(props: { home: number; onLeave?: () => void }) { + const { home, onLeave } = props; + const { act } = useBackend(); + const { rows: M } = useGrid(); + const [group, setGroup] = useState('options'); + const [sub, setSub] = useState(null); + const [from, setFrom] = useState(null); + const [crumb, setCrumb] = useState(''); + + useEffect(() => { + act('settings_open'); + return () => act('settings_close'); + }, []); + + const closeSub = () => { + setFrom(sub?.from ?? null); + setSub(null); + }; + useEffect(() => { + setSub(null); + setFrom(null); + }, [home]); + + useBack(sub ? closeSub : onLeave || null); + useScreen(`settings/${group}`, 0); + + const nav: SettingsNav = { + sub: (node, label, at) => { + setFrom(null); + setSub({ node, crumb: label, from: at ?? null }); + }, + closeSub, + subOpen: !!sub, + from, + setCrumb, + home, + }; + const crumbs: Crumb[] = [ + ['SETTINGS', closeSub], + [crumb, closeSub], + ]; + if (sub) { + crumbs.push([sub.crumb, null]); + } + + return ( + + + {!!sub && } + { + setSub(null); + setFrom(null); + setGroup(g); + }} + /> + {group === 'options' ? : } + {!!sub && sub.node} + {/* A picker or a colour panel wipes the work column only. */} + + + ); +} diff --git a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/SettingsFrame.tsx b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/SettingsFrame.tsx new file mode 100644 index 00000000000..2ecf90fc375 --- /dev/null +++ b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/SettingsFrame.tsx @@ -0,0 +1,519 @@ +/** + * The SETTINGS frame pieces shared by both groups: the layout constants, the context, the group + * switch, the category list and SettingsColumns (rows, paging, description strip). The screen + * itself and the contract for the KEYS group are in Settings.tsx. + */ +import { + createContext, + type ReactNode, + type WheelEvent as ReactWheelEvent, + useContext, + useEffect, + useRef, + useState, +} from 'react'; + +import { clamp, StepKeys, useListPager } from './CharFrame'; +import { FocusGroup, useBack } from './nav'; +import { + BODY_Y, + Field, + Key, + NameLine, + Pager, + Put, + Slab, + safe, + useGrid, + WipeAt, + wrapMax, +} from './term'; + +export const LIST_X = 1; +export const LIST_W = 15; +export const WORK_X = 17; +export const WORK_W = 45; +export const NAME_X = 19; +export const NAME_W = 24; +export const VALUE_X = 44; +export const VALUE_W = 18; +/** The description strip: two lines this wide from NAME_X. */ +export const DESC_W = 43; + +/** The rows' top; the search field sits under the group switch, the list's first slab under it. */ +const ROWS_Y = BODY_Y; +const FIND_Y = BODY_Y + 1.75; +const LIST_Y = BODY_Y + 3.5; +const SLAB_H = 1.5; +const SLAB_PITCH = 1.75; + +export type SettingsGroup = 'options' | 'keys'; + +export type SettingsCat = { id: string; label: string }; + +export type SettingsRowSpec = { + key: string; + /** Upper case, safe()d. */ + name: string; + desc?: string; + /** Draws the value in the value zone; ty is the row's first text line. */ + value?: (ty: number, focused: boolean) => ReactNode; + /** Enter or a click. Without it (and without onStep) the row is not a focus stop. */ + onPress?: () => void; + /** Left and Right on the focused row; the row then draws its `<` `>` keys (StepKeys). */ + onStep?: (by: number) => void; + /** A number at its low or high end: that key is drawn dead. */ + ends?: [boolean, boolean]; + /** Dead colours (shown, not changeable), still focusable for its description. */ + muted?: boolean; + /** The row takes the focus when this turns on (back from typing in it). */ + claim?: boolean; +}; + +export type SettingsNav = { + sub: (node: ReactNode, crumb: string, from?: string) => void; + closeSub: () => void; + subOpen: boolean; + from: string | null; + /** The open category's label, for the crumbs. */ + setCrumb: (label: string) => void; + /** Bumped when SETTINGS is pressed while open. */ + home: number; +}; + +export const SettingsContext = createContext({ + sub: () => undefined, + closeSub: () => undefined, + subOpen: false, + from: null, + setCrumb: () => undefined, + home: 0, +}); + +export const useSettings = () => useContext(SettingsContext); + +/** A row's height: one line, or two when the name wraps. */ +const rowHeight = (name: string) => (name.length > NAME_W ? 2.25 : 1.25); + +/** The name's lines in its zone (at most two; a longer one ends in the cut mark). */ +const nameLines = (name: string) => wrapMax(name, NAME_W, 2); + +/** tg's own order: by name, as a plain string compare (GamePreferencesPage binaryInsert). */ +export const byName = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0); + +/** OPTIONS | KEYS, side by side at the top of the list column. */ +export function GroupSwitch(props: { + group: SettingsGroup; + onGroup: (g: SettingsGroup) => void; +}) { + const { group, onGroup } = props; + return ( + <> + onGroup('options')} + /> + onGroup('keys')} + /> + + ); +} + +/** The mouse wheel turns a paged list's pages, one page a notch (as CREWS does). */ +function useWheelPages(page: number, pages: number, set: (p: number) => void) { + const last = useRef(0); + return (e: ReactWheelEvent) => { + if (pages <= 1 || !e.deltaY) { + return; + } + const now = Date.now(); + if (now - last.current < 150) { + return; + } + last.current = now; + set(clamp(page + (e.deltaY > 0 ? 1 : -1), 0, pages - 1)); + }; +} + +/** The categories under the group switch, paged when they don't fit. */ +function CategoryList(props: { + cats: SettingsCat[]; + cat: string | null; + onCat: (id: string) => void; + claim?: number; + /** Bumped to give the open category the focus again (Escape on a row). */ + bump?: number; +}) { + const { cats, cat, onCat, claim, bump = 0 } = props; + const { rows: M } = useGrid(); + const bottom = M - 1.25; + const fitAll = Math.floor((bottom - LIST_Y + 0.25) / SLAB_PITCH); + const paged = cats.length > fitAll; + const per = paged + ? Math.max(1, Math.floor((bottom - 1.25 - LIST_Y + 0.25) / SLAB_PITCH)) + : Math.max(1, cats.length); + const pages = Math.max(1, Math.ceil(cats.length / per)); + const at = cats.findIndex((c) => c.id === cat); + const [page, setPage] = useState(() => Math.max(0, Math.floor(at / per))); + useEffect(() => { + if (at >= 0) { + setPage(Math.floor(at / per)); + } + }, [cat, per]); + const pg = clamp(page, 0, pages - 1); + const shown = cats.slice(pg * per, pg * per + per); + const onWheel = useWheelPages(pg, pages, setPage); + return ( +
+ {shown.map((c, i) => { + const y = LIST_Y + i * SLAB_PITCH; + const on = c.id === cat; + return ( + onCat(c.id)} + > + + {safe(c.label) + .toUpperCase() + .slice(0, LIST_W - 2)} + + + ); + })} + setPage(p - 1)} + right + /> + {pages > 1 && ( + + )} +
+ ); +} + +/** One row of the work column: the slab, the name, the value. */ +function SettingRow(props: { + spec: SettingsRowSpec; + y: number; + h: number; + alt: boolean; + auto?: number; + /** The mouse is over the row. */ + onSeen: (key: string) => void; + /** Told when the row gains or loses the focus. */ + onFocused: (key: string, on: boolean) => void; +}) { + const { spec, y, h, alt, auto, onSeen, onFocused } = props; + const [focused, setFocused] = useState(false); + const lines = nameLines(spec.name); + const ty = y + 0.125; + const live = !!spec.onPress || !!spec.onStep; + const step = spec.onStep; + return ( + // Hovering anything in the row (its value's own keys too) shows its description. +
onSeen(spec.key)}> + { + setFocused(on); + onFocused(spec.key, on); + }} + onClick={live ? () => spec.onPress?.() : undefined} + edge={ + step + ? { + left: () => { + step(-1); + return true; + }, + right: () => { + step(1); + return true; + }, + } + : undefined + } + > + {lines.map((line, i) => ( + + {line} + + ))} + {spec.value?.(ty, focused)} + {!!step && ( + + )} + +
+ ); +} + +/** Splits rows into pages that fit `room` rows (each row's height from its name). */ +function pageRows(heights: number[], room: number): number[][] { + const pages: number[][] = []; + let cur: number[] = []; + let used = 0; + heights.forEach((h, i) => { + if (cur.length && used + h > room + 1e-6) { + pages.push(cur); + cur = []; + used = 0; + } + cur.push(i); + used += h; + }); + if (cur.length || !pages.length) { + pages.push(cur); + } + return pages; +} + +/** + * The list column (under the group switch) and the work column (rows, page mark, description + * strip) of either group. While a level-2 screen is open only the list is drawn. + */ +export function SettingsColumns(props: { + cats: SettingsCat[]; + cat: string | null; + onCat: (id: string) => void; + rows: SettingsRowSpec[]; + /** The row that takes the focus when the rows mount; else the open category's slab does. */ + focusKey?: string | null; + /** Drawn in the work column when there are no rows (dim, one line). */ + empty?: string; + /** + * The search text and its setter. While it is not empty the caller passes the matching rows + * of every category, and no category is marked. + */ + find?: string; + onFind?: (text: string) => void; + /** The row whose value is being typed: the strip keeps its description while the keys are in the field. */ + typing?: string | null; +}) { + const { cats, cat, onCat, rows, focusKey, empty, onFind, typing } = props; + const find = props.find || ''; + const { subOpen, closeSub } = useSettings(); + const { rows: M } = useGrid(); + const [page, setPage] = useState(0); + /** The strip describes the row under the mouse, else the focused row, else nothing. */ + const [seen, setSeen] = useState(null); + /** The focused row; Escape then goes up to the list before it leaves the screen. */ + const [focusRow, setFocusRow] = useState(null); + /** The search field's box: a row taking the focus (the mouse, say) takes the keys out of it. */ + const findBox = useRef(null); + const [bump, setBump] = useState(0); + + // A new category or search starts on its first page with no description. + useEffect(() => { + setPage(0); + setSeen(null); + }, [cat, find]); + useEffect(() => { + if (subOpen) { + setFocusRow(null); + } + }, [subOpen]); + + const heights = rows.map((r) => rowHeight(r.name)); + const total = heights.reduce((a, b) => a + b, 0); + // Unpaged the rows may run down to the description strip; paged they leave a row for the mark. + const openRoom = M - 3.5 - ROWS_Y; + const paged = total > openRoom + 1e-6; + const pages = pageRows(heights, paged ? M - 4.75 - ROWS_Y : openRoom); + // Back from a picker: the page with the row that opened it. + useEffect(() => { + if (!focusKey) { + return; + } + const i = rows.findIndex((r) => r.key === focusKey); + const p = pages.findIndex((list) => list.includes(i)); + if (p >= 0) { + setPage(p); + } + }, [focusKey]); + const pg = clamp(page, 0, pages.length - 1); + useListPager(pg, subOpen ? 1 : pages.length, setPage); + const onWheel = useWheelPages(pg, pages.length, setPage); + // A row that went away (another page, category or search) never says it lost the focus. + const shownRow = (key: string | null) => + key !== null && pages[pg].some((i) => rows[i].key === key); + const inRows = shownRow(focusRow); + useBack( + subOpen + ? null + : find + ? () => onFind?.('') + : inRows + ? () => setBump((n) => n + 1) + : null, + ); + + const onCatPress = (id: string) => { + if (subOpen) { + closeSub(); + } + if (find) { + onFind?.(''); + } + if (id !== cat) { + onCat(id); + } + }; + // The search field and the list are entered as one: sideways from the rows, the open category. + const list = ( + + {!!onFind && ( +
+ onFind(v.toUpperCase())} + onEnter={() => + (document.activeElement as HTMLElement | null)?.blur() + } + /> +
+ )} + +
+ ); + if (subOpen) { + // The same tree shape as below, so the list stays mounted and keeps the focus where it was. + return <>{list}; + } + + let y = ROWS_Y; + const drawn = pages[pg].map((i, n) => { + const spec = rows[i]; + const h = heights[i]; + const row = ( + { + if (on) { + const typing = document.activeElement; + if (typing && findBox.current?.contains(typing)) { + (typing as HTMLElement).blur(); + } + } + setFocusRow((was) => (on ? key : was === key ? null : was)); + }} + /> + ); + y += h; + return row; + }); + + const described = + seen ?? (inRows ? focusRow : shownRow(typing ?? null) ? typing : null); + const desc = safe( + rows.find((r) => r.key === described)?.desc || '', + ).toUpperCase(); + const descLines = desc ? wrapMax(desc, DESC_W, 2) : []; + const rowsBottom = paged ? M - 4.75 : M - 3.5; + + return ( + <> + {list} +
setSeen(null)}> + {drawn} +
+ {!rows.length && (!!empty || !!find) && ( + + )} + setPage(p - 1)} + right + /> + {descLines.map((line, i) => ( + + {line} + + ))} + {/* Another category, or another page of rows, turns the page of the rows only. */} + + + ); +} diff --git a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/SettingsKeys.tsx b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/SettingsKeys.tsx new file mode 100644 index 00000000000..4a5a9de184f --- /dev/null +++ b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/SettingsKeys.tsx @@ -0,0 +1,644 @@ +/** + * SETTINGS, KEYS group: tg's keybindings page (PreferencesMenu KeybindingsPage) in the terminal. + * + * Categories, names and descriptions come from tg's keybindings.json asset (settings_keys_open + * sends it); the player's bindings from the server's settings_keys block + * (lobby_settings_keys.dm). Every write goes through tg's keybindings middleware. + * + * A row shows the keybinding's keys in the value zone, cut with the mark when they don't fit. + * Enter or a click opens the keybinding at level 2: its three slots as blocks (each key whole up + * to the block's width), CLEAR for the selected slot, RESET (tg's "Reset to Defaults") and + * RESET ALL behind a confirm. + * + * Rebinding: pressing a slot listens. The next key, with its modifiers, is the binding, in tg's + * own format (formatKeyboardEvent below, copied from tg; it is not exported). A modifier alone + * binds on its key-up, as in tg. Escape cancels (tg clears the slot instead). While listening + * the page takes every key and mouse press first: the terminal's navigation is locked (lockNav), + * and capture listeners on window stop the keys before tgui-core passes them on to BYOND. + */ +import { useEffect, useRef, useState } from 'react'; +import { resolveAsset } from 'tgui/assets'; +import { useBackend } from 'tgui/backend'; +import { fetchRetry } from 'tgui-core/http'; +import { isEscape, KEY } from 'tgui-core/keys'; + +import { quietDialogClose, sfx, useBlink } from './motion'; +import { Back, lockNav } from './nav'; +import { + byName, + DESC_W, + NAME_X, + type SettingsCat, + SettingsColumns, + type SettingsRowSpec, + useSettings, + VALUE_W, + VALUE_X, + WORK_W, + WORK_X, +} from './SettingsFrame'; +import { + BODY_Y, + Big, + Btn, + Dialog, + HRule, + Put, + Slab, + cut, + safe, + useGrid, + wrapMax, +} from './term'; +import type { LobbyKeysData, SettingsKeysBlock } from './types'; + +// --------------------------------------------------------------------------- +// tg's keybindings.json catalog + +type KeybindInfo = { name: string; description?: string }; +/** category -> keybind_name -> its name and description. */ +type KeysCatalog = Record>; + +let cached: KeysCatalog | null = null; +let pending: Promise | null = null; +const listeners = new Set<() => void>(); + +/** The asset can arrive after the first fetch (settings_keys_open sends it): retry until it does. */ +function attempt(tries: number): Promise { + return fetchRetry(resolveAsset('keybindings.json')) + .then((response) => { + if (!response.ok) { + throw new Error(`keybindings.json: ${response.status}`); + } + return response.json(); + }) + .then((data: KeysCatalog) => { + cached = data && typeof data === 'object' ? data : {}; + for (const fn of listeners) { + fn(); + } + }) + .catch( + () => + new Promise((resolve) => + setTimeout( + () => resolve(attempt(tries + 1)), + tries < 20 ? 1500 : 5000, + ), + ), + ); +} + +/** The catalog, or null until it has arrived. Fetched once per window. */ +function useKeysCatalog(): KeysCatalog | null { + const [, setTick] = useState(0); + useEffect(() => { + const fn = () => setTick((t) => t + 1); + listeners.add(fn); + if (!cached && !pending) { + pending = attempt(0); + } + return () => { + listeners.delete(fn); + }; + }, []); + return cached; +} + +/** tg's order: categories by name, EMOTE and then ADMIN moved to the bottom; empty ones dropped. */ +function keyCats(catalog: KeysCatalog): SettingsCat[] { + const ids = Object.keys(catalog) + .filter((id) => Object.keys(catalog[id] || {}).length > 0) + .sort(byName); + for (const last of ['EMOTE', 'ADMIN']) { + const at = ids.indexOf(last); + if (at >= 0) { + ids.push(ids.splice(at, 1)[0]); + } + } + return ids.map((id) => ({ id, label: cut(upper(id), 13) })); +} + +function infoOf(catalog: KeysCatalog | null, id: string): KeybindInfo | null { + if (!catalog) { + return null; + } + for (const cat of Object.keys(catalog)) { + const info = catalog[cat]?.[id]; + if (info) { + return info; + } + } + return null; +} + +function bindsOf(block: SettingsKeysBlock | undefined, id: string): string[] { + const keys = block?.binds && !Array.isArray(block.binds) && block.binds[id]; + return Array.isArray(keys) ? keys.filter((k) => k && k !== 'Unbound') : []; +} + +const upper = (s: string) => safe(s).toUpperCase(); + +/** BYOND's names for the arrow and paging keys, as the keys are labelled. */ +const KEY_LABEL: Record = { + North: 'UP', + South: 'DOWN', + East: 'RIGHT', + West: 'LEFT', + Northeast: 'PGUP', + Southeast: 'PGDN', + Northwest: 'HOME', + Southwest: 'END', +}; +/** BYOND's modifier order in a stored key. */ +const MODIFIERS = ['Alt', 'Ctrl', 'Shift']; + +/** + * A stored key as players read it, for display only (what is stored and sent stays BYOND's): + * CtrlShiftNumpad5 -> CTRL+SHIFT+NUMPAD5, AltF -> ALT+F, CtrlShift -> CTRL+SHIFT, + * NumpadNortheast -> NUMPAD PGUP. + */ +function keyText(stored: string): string { + const parts: string[] = []; + let rest = stored; + for (const mod of MODIFIERS) { + if (rest.startsWith(mod)) { + parts.push(mod.toUpperCase()); + rest = rest.slice(mod.length); + } + } + if (rest) { + const pad = rest.startsWith('Numpad') && rest.length > 6; + const key = pad ? rest.slice(6) : rest; + const name = KEY_LABEL[key] || key.toUpperCase(); + parts.push( + pad ? (/^[0-9]$/.test(key) ? `NUMPAD${name}` : `NUMPAD ${name}`) : name, + ); + } + return upper(parts.join('+')); +} + +/** An action's keys, each as keyText(), between commas. */ +const keysText = (keys: string[]) => keys.map(keyText).join(', '); + +/** An empty slot. */ +const EMPTY = '---'; +/** tg's MAX_HOTKEY_SLOTS. */ +const SLOTS = 3; + +// --------------------------------------------------------------------------- +// Key capture, as tg's KeybindingsPage formats it + +function isStandardKey(event: KeyboardEvent): boolean { + return ( + event.key !== KEY.Alt && + event.key !== KEY.Control && + event.key !== KEY.Shift && + !isEscape(event.key) + ); +} + +const KEY_CODE_TO_BYOND: Record = { + // The names today's browser control reports. tg's table has only the old ones, so an arrow + // or Delete would be stored under a name the game never matches a key press to. + ARROWDOWN: 'South', + ARROWLEFT: 'West', + ARROWRIGHT: 'East', + ARROWUP: 'North', + DELETE: 'Delete', + DEL: 'Delete', + DOWN: 'South', + END: 'Southwest', + HOME: 'Northwest', + INSERT: 'Insert', + LEFT: 'West', + PAGEDOWN: 'Southeast', + PAGEUP: 'Northeast', + RIGHT: 'East', + ' ': 'Space', + UP: 'North', +}; + +/** KeyboardEvent.DOM_KEY_LOCATION_NUMPAD (tg spells it out for IE 11). */ +const DOM_KEY_LOCATION_NUMPAD = 3; + +function formatKeyboardEvent(event: KeyboardEvent): string { + let text = ''; + if (event.altKey) { + text += 'Alt'; + } + if (event.ctrlKey) { + text += 'Ctrl'; + } + if (event.shiftKey) { + text += 'Shift'; + } + if (event.location === DOM_KEY_LOCATION_NUMPAD) { + text += 'Numpad'; + } + if (isStandardKey(event)) { + const key = event.key.toUpperCase(); + text += KEY_CODE_TO_BYOND[key] || key; + } + return text; +} + +/** Takes the one event and stops it everywhere: the terminal, tgui-core's pass-through, the browser. */ +function swallow(e: Event) { + e.preventDefault(); + e.stopPropagation(); + e.stopImmediatePropagation(); +} + +/** Swallows the next event of that type (and key code) on window, once, within 3 s (tg's cancelNextKeyUp). */ +function swallowNext(type: 'keyup' | 'click', code?: number) { + const fn = (e: Event) => { + if (code !== undefined && (e as KeyboardEvent).keyCode !== code) { + return; + } + swallow(e); + stop(); + }; + const stop = () => window.removeEventListener(type, fn, true); + window.addEventListener(type, fn, true); + setTimeout(stop, 3000); +} + +/** + * While `on`: every key and mouse press goes here first. onHeld(text) shows modifiers held so far; + * onDone(text) ends it with the binding, or null when cancelled (Escape, or a mouse press anywhere). + */ +function useKeyCapture( + on: boolean, + onHeld: (text: string) => void, + onDone: (text: string | null) => void, +) { + const cb = useRef({ onHeld, onDone }); + cb.current = { onHeld, onDone }; + useEffect(() => { + if (!on) { + return; + } + let last: KeyboardEvent | null = null; + let over = false; + lockNav(true); + const done = (text: string | null) => { + if (over) { + return; + } + over = true; + lockNav(false); + cb.current.onDone(text); + }; + const down = (e: KeyboardEvent) => { + swallow(e); + if (over || e.repeat) { + return; + } + swallowNext('keyup', e.keyCode); + if (isEscape(e.key)) { + done(null); + } else if (isStandardKey(e)) { + done(formatKeyboardEvent(e)); + } else { + last = e; + cb.current.onHeld(formatKeyboardEvent(e)); + } + }; + const up = (e: KeyboardEvent) => { + swallow(e); + if (last) { + done(formatKeyboardEvent(last)); + } + }; + const press = (e: MouseEvent) => { + swallow(e); + // The click that follows this press must not start listening again. + swallowNext('click'); + done(null); + }; + const keyTypes = ['keydown', 'keyup', 'keypress'] as const; + const mouseTypes = ['mousedown', 'mouseup', 'click', 'mouseover'] as const; + const onKeyEvent = (e: Event) => { + if (e.type === 'keydown') { + down(e as KeyboardEvent); + } else if (e.type === 'keyup') { + up(e as KeyboardEvent); + } else { + swallow(e); + } + }; + const onMouseEvent = (e: Event) => { + if (e.type === 'mousedown') { + press(e as MouseEvent); + } else { + swallow(e); + } + }; + for (const t of keyTypes) { + window.addEventListener(t, onKeyEvent, true); + } + for (const t of mouseTypes) { + window.addEventListener(t, onMouseEvent, true); + } + return () => { + for (const t of keyTypes) { + window.removeEventListener(t, onKeyEvent, true); + } + for (const t of mouseTypes) { + window.removeEventListener(t, onMouseEvent, true); + } + lockNav(false); + }; + }, [on]); +} + +// --------------------------------------------------------------------------- +// Level 2: one keybinding + +const SLOT_Y = 5.5; +const SLOT_H = 1.5; +const SLOT_PITCH = 1.75; +/** The key's text in a slot: from WORK_X + 4, this wide. */ +const SLOT_TEXT_X = WORK_X + 4; +const SLOT_TEXT_W = WORK_W - 5; +const BTN_Y = SLOT_Y + SLOTS * SLOT_PITCH + 0.5; + +/** The keybinding's name over the slots: 1.25x when it fits, else normal size, cut. */ +function Head(props: { text: string }) { + const { text } = props; + return text.length * 1.25 <= WORK_W ? ( + + {text} + + ) : ( + + {cut(text, WORK_W)} + + ); +} + +/** RESET ALL, asked in the terminal's dialog with KEEP focused. */ +function ResetAllConfirm(props: { onClose: () => void; onReset: () => void }) { + const { onClose, onReset } = props; + const { cols } = useGrid(); + const w = 39; + const x = Math.floor((cols - w) / 2); + const y = BODY_Y + 2; + return ( + <> +
{ + e.stopPropagation(); + onClose(); + }} + /> + + + + PUT EVERY KEY BACK TO ITS DEFAULT? + + + { + quietDialogClose(); + onClose(); + onReset(); + }} + /> + + + ); +} + +function KeyEdit(props: { id: string }) { + const { id } = props; + const { act, data } = useBackend(); + const catalog = useKeysCatalog(); + const { closeSub } = useSettings(); + const { rows: M } = useGrid(); + const info = infoOf(catalog, id); + const block = data.settings_keys; + const rev = block?.rev ?? 0; + // The keys just sent, shown until the server's next push (which snaps a refused one back). + const [sent, setSent] = useState<{ rev: number; keys: string[] } | null>( + null, + ); + const keys = sent && sent.rev === rev ? sent.keys : bindsOf(block, id); + const [sel, setSel] = useState(0); + const [listen, setListen] = useState(null); + const [held, setHeld] = useState(''); + const [asking, setAsking] = useState(false); + const lit = useBlink(listen !== null && !held, 450); + + const gone = !!catalog && !info; + useEffect(() => { + if (gone) { + closeSub(); + } + }, [gone]); + + const send = (next: string[]) => { + setSent({ rev, keys: next }); + act('settings_keys_set', { keybind_name: id, hotkeys: next }); + }; + + useKeyCapture(listen !== null, setHeld, (text) => { + const slot = listen; + setListen(null); + setHeld(''); + if (text === null || slot === null) { + return; + } + // A key this keybinding already has (in this slot or another) changes nothing. + if (keys.includes(text)) { + return; + } + // tg's rule: a slot past the last bound key fills the next free one. + const next = [...keys]; + next[Math.min(next.length, slot)] = text; + sfx('slot'); + send(next.slice(0, SLOTS)); + }); + + if (!info) { + return null; + } + const desc = upper(info.description || ''); + const descLines = desc ? wrapMax(desc, DESC_W, 2) : []; + const selKey = keys[sel]; + + return ( + <> + + + {Array.from({ length: SLOTS }, (_, i) => { + const y = SLOT_Y + i * SLOT_PITCH; + const ty = y + 0.25; + const key = keys[i]; + const listening = listen === i; + let text: string; + let cls: string; + if (listening) { + text = held ? keyText(held) : 'PRESS A KEY'; + cls = held || lit ? 'wht' : 'faint'; + } else if (key) { + text = cut(keyText(key), SLOT_TEXT_W); + cls = sel === i ? 'wht' : ''; + } else { + text = EMPTY; + cls = 'faint'; + } + return ( + { + if (on) { + setSel(i); + } + }} + onClick={() => { + setSel(i); + setHeld(''); + setListen(i); + }} + > + + {String(i + 1)} + + + {cut(text, SLOT_TEXT_W)} + + + ); + })} + { + if (selKey) { + const next = [...keys]; + next.splice(sel, 1); + send(next); + } + }} + /> + { + setSent(null); + act('settings_keys_reset', { keybind_name: id }); + }} + /> + setAsking(true)} + /> + {descLines.map((line, i) => ( + + {line} + + ))} + {!!asking && ( + setAsking(false)} + onReset={() => { + setSent(null); + act('settings_keys_reset_all'); + }} + /> + )} + + ); +} + +// --------------------------------------------------------------------------- +// The KEYS group + +export function SettingsKeys() { + const { act, data } = useBackend(); + const catalog = useKeysCatalog(); + const { sub, from, setCrumb } = useSettings(); + const [open, setOpen] = useState(null); + const [find, setFind] = useState(''); + const needle = find.trim().toUpperCase(); + const block = data.settings_keys; + + useEffect(() => { + act('settings_keys_open'); + return () => act('settings_keys_close'); + }, []); + + const cats = catalog ? keyCats(catalog) : []; + const cat = cats.some((c) => c.id === open) ? open : cats[0]?.id || null; + useEffect(() => { + setCrumb(needle ? 'SEARCH' : cat ? cut(upper(cat), 13) : ''); + }, [cat, needle]); + + const rows: SettingsRowSpec[] = + catalog && cat && block + ? (needle + ? Object.values(catalog) + .flatMap((group) => Object.entries(group)) + .filter(([id, info]) => upper(info.name || id).includes(needle)) + : Object.entries(catalog[cat] || {}) + ) + .sort((a, b) => byName(a[1].name, b[1].name)) + .map(([id, info]) => { + const NAME = upper(info.name || id); + const keys = bindsOf(block, id); + const all = keysText(keys); + return { + key: id, + name: NAME, + // Keys too long for the row are cut there; the strip then shows them whole. + desc: all.length > VALUE_W ? all : info.description || '', + onPress: () => sub(, NAME, id), + value: (ty: number, focused: boolean) => ( + + {keys.length ? cut(all, VALUE_W) : EMPTY} + + ), + }; + }) + : []; + + return ( + + ); +} diff --git a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/SettingsOptions.tsx b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/SettingsOptions.tsx new file mode 100644 index 00000000000..28a77e336e0 --- /dev/null +++ b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/SettingsOptions.tsx @@ -0,0 +1,576 @@ +/** + * SETTINGS, OPTIONS group: every game preference tg's own window lists on its game page, by + * tg's categories, edited in place. + * + * Names, categories and descriptions come from tg's TSX feature registry (so they never drift + * from tg's window); kind, value and limits from the server's settings block + * (lobby_settings.dm); choices and their display names from tg's preferences.json catalog. + * Labelled dropdowns that tg builds in TSX (createDropdownInput: pixel scaling, scaling method, + * multi-z depth) give their labels by calling the registry's component once outside React and + * reading its Dropdown's options; it is a plain function with no hooks. + * + * Controls by kind: a toggle (a drawn checkbox) flips on Enter or a click; a choice steps with + * Left and Right or the mouse arrows, and Enter opens the list picker when it has more than + * HANDFUL choices or a choice's name is too long for the value zone (the picker shows names + * whole; the row cuts them with the mark), else steps on; a number steps the same way, and Enter + * or a click types it; a volume (tg's slider) is a track the mouse drags, with Left and Right + * stepping a twentieth of its range; a colour opens the colour panel; a text types. + */ +import { useEffect, useRef, useState } from 'react'; +import { useBackend } from 'tgui/backend'; +import { features } from 'tgui/interfaces/PreferencesMenu/preferences/features'; +import { + CheckboxInput, + CheckboxInputInverse, + FeatureColorInput, + FeatureNumberInput, + FeatureShortTextInput, + FeatureSliderInput, +} from 'tgui/interfaces/PreferencesMenu/preferences/features/base'; +import { FeatureDropdownInput } from 'tgui/interfaces/PreferencesMenu/preferences/features/dropdowns'; + +import { clamp } from './CharFrame'; +import { ColourPanel, ListPicker } from './CharPickers'; +import { parseHex } from './ColorEntry'; +import { + byName, + type SettingsCat, + SettingsColumns, + type SettingsRowSpec, + useSettings, + VALUE_X, + WORK_W, + WORK_X, +} from './SettingsFrame'; +import { Check, cut, Field, Put, Slide, Swatch, safe } from './term'; +import type { LobbyData, SettingRow } from './types'; +import { choicesOf, nameOf, usePrefsCatalog } from './usePrefsCatalog'; + +/** A choice with more values than this opens the list picker on Enter. */ +const HANDFUL = 6; +/** The value's text: from VALUE_X, this many cells beside the row's `<` `>` keys (column 56). */ +const VALUE_TEXT_X = VALUE_X; +const VALUE_TEXT_W = 11; +/** A value with no keys beside it runs to the row's end. */ +const VALUE_WIDE_W = 18; +/** A choice with a value name longer than this opens the list picker on Enter. */ +const PICK_W = 14; +/** A slider's track, with the number in the four cells after it. */ +const SLIDE_X = VALUE_X; +const SLIDE_W = 7; +/** The category tg's window puts last here. */ +const LAST_CAT = 'ADMIN'; + +const BASE_INPUTS = new Set([ + CheckboxInput, + CheckboxInputInverse, + FeatureColorInput, + FeatureNumberInput, + FeatureSliderInput, + FeatureShortTextInput, + FeatureDropdownInput, +]); + +const optionCache: Record = {}; + +/** + * [value, label] of a preference tg draws with createDropdownInput, or null. The component is + * called once, outside React: a plain function returning a Dropdown whose options carry the + * labels. Anything else (a component with hooks, another shape) gives null. + */ +function dropdownOptions(key: string): [string, string][] | null { + if (key in optionCache) { + return optionCache[key]; + } + let out: [string, string][] | null = null; + const comp = features[key]?.component as unknown; + if (typeof comp === 'function' && !BASE_INPUTS.has(comp)) { + try { + const el = (comp as (p: object) => any)({ + featureId: key, + value: undefined, + serverData: undefined, + handleSetValue: () => undefined, + }); + const opts = el?.props?.options; + if ( + Array.isArray(opts) && + opts.length && + opts.every( + (o) => + !!o && + typeof o === 'object' && + 'value' in o && + typeof o.displayText === 'string', + ) + ) { + out = opts.map((o) => [String(o.value), o.displayText]); + } + } catch { + out = null; + } + } + optionCache[key] = out; + return out; +} + +/** What a setting is called, where it goes and what it says, from tg's registry. */ +function featureOf(key: string) { + const f = features[key]; + return { + name: f?.name || key, + cat: (f?.category || 'OTHER').toUpperCase(), + desc: f?.description || '', + }; +} + +const upper = (s: string) => safe(s).toUpperCase(); + +/** A choice row's values and their names (labelled numbers count as choices). */ +function choiceSpec( + cat: ReturnType, + row: SettingRow, +): { list: string[]; name: (v: string) => string } | null { + const labelled = dropdownOptions(row.key); + const labels = labelled ? Object.fromEntries(labelled) : null; + let list: string[] | null = null; + if (row.kind === 'choice') { + list = choicesOf(cat, row.key) || row.choices || null; + if (!list && labelled) { + list = labelled.map((o) => o[0]); + } + } else if (row.kind === 'number' && labelled) { + list = labelled.map((o) => o[0]); + } + if (!list || !list.length) { + return null; + } + return { + list: list.map(String), + name: (v) => { + const shown = nameOf(cat, row.key, v); + return shown !== v ? shown : (labels?.[v] ?? v); + }, + }; +} + +/** What a number row shows: -1 on a preference whose least is -1 is "use the default". */ +function numberText(row: SettingRow, v: number) { + if (row.min === -1 && v === -1) { + return 'AUTO'; + } + return String(Math.round(v * 100) / 100); +} + +/** + * A number or text being typed, over the value zone. Enter sends it; leaving the field (Escape, + * a click elsewhere) drops it. + */ +function TypeIn(props: { + ty: number; + start: string; + max: number; + numeric: boolean; + /** Cells for the field. */ + w: number; + onDone: (text: string | null) => void; +}) { + const { ty, start, max, numeric, w, onDone } = props; + const [text, setText] = useState(start); + const wrap = useRef(null); + const done = useRef(false); + const finish = (value: string | null) => { + if (!done.current) { + done.current = true; + onDone(value); + } + }; + useEffect(() => { + const input = wrap.current?.querySelector('input'); + input?.focus(); + input?.select(); + }, []); + return ( +
finish(null)}> + + setText(numeric ? v.toUpperCase().replace(/[^0-9.\-AUTO]/g, '') : v) + } + onEnter={() => finish(text)} + /> +
+ ); +} + +/** The open setting's row, or null once it is gone (a parent toggle hid it). */ +function useSettingRow(k: string) { + const { data } = useBackend(); + const { closeSub } = useSettings(); + const row = data.settings?.rows.find((r) => r.key === k) || null; + const gone = !row; + useEffect(() => { + if (gone) { + closeSub(); + } + }, [gone]); + return row; +} + +/** Level 2: the list picker on a choice. */ +function OptionPick(props: { k: string }) { + const { k } = props; + const { act } = useBackend(); + const cat = usePrefsCatalog(); + const { closeSub } = useSettings(); + const row = useSettingRow(k); + if (!row) { + return null; + } + const spec = choiceSpec(cat, row); + const value = String(row.value); + return ( + upper(spec ? spec.name(v) : v)} + onPick={(v) => { + if (v !== value) { + act('settings_set', { + key: k, + value: row.kind === 'number' ? Number(v) : v, + }); + } + }} + onClose={closeSub} + /> + ); +} + +/** Level 2: the colour panel on a colour. */ +function OptionColour(props: { k: string }) { + const { k } = props; + const { act } = useBackend(); + const { closeSub } = useSettings(); + const row = useSettingRow(k); + if (!row) { + return null; + } + return ( + act('settings_set', { key: k, value: hex })} + onClose={closeSub} + /> + ); +} + +export function SettingsOptions() { + const { act, data } = useBackend(); + const catalog = usePrefsCatalog(); + const { sub, from, setCrumb, home } = useSettings(); + const [open, setOpen] = useState(null); + /** The row being typed in, and the row that gets the focus back after. */ + const [typing, setTyping] = useState(null); + const [back, setBack] = useState(null); + /** A slider being dragged, or let go and waiting for the server's value. */ + const [drag, setDrag] = useState<{ + key: string; + v: number; + held: boolean; + } | null>(null); + const rev = data.settings?.rev; + useEffect(() => { + setDrag((d) => (d && !d.held ? null : d)); + }, [rev]); + const rows = data.settings?.rows || []; + const [find, setFind] = useState(''); + const needle = find.trim().toUpperCase(); + + const items = rows.map((row) => ({ row, ...featureOf(row.key) })); + const cats: SettingsCat[] = Array.from(new Set(items.map((it) => it.cat))) + .sort((a, b) => (a === LAST_CAT ? 1 : b === LAST_CAT ? -1 : byName(a, b))) + .map((id) => ({ id, label: id })); + const cat = cats.some((c) => c.id === open) ? open : cats[0]?.id || null; + + useEffect(() => { + setCrumb(needle ? 'SEARCH' : cat || ''); + }, [cat, needle]); + useEffect(() => { + setTyping(null); + setBack(null); + }, [cat, home]); + + const set = (key: string, value: unknown) => + act('settings_set', { key, value }); + + const specs: SettingsRowSpec[] = items + .filter((it) => (needle ? upper(it.name).includes(needle) : it.cat === cat)) + .sort((a, b) => byName(a.name, b.name)) + .map(({ row, name, desc }) => { + const key = row.key; + const NAME = upper(name); + const base = { key, name: NAME, desc, claim: back === key }; + if (row.locked) { + const shown = choiceSpec(catalog, row); + return { + ...base, + muted: true, + value: (ty: number) => ( + + {cut( + upper( + shown ? shown.name(String(row.value)) : String(row.value), + ), + VALUE_WIDE_W, + )} + + ), + }; + } + const typeIn = + ( + start: string, + max: number, + numeric: boolean, + send: (t: string) => void, + ) => + (ty: number) => ( + { + setTyping(null); + setBack(key); + if (t !== null) { + send(t); + } + }} + /> + ); + switch (row.kind) { + case 'toggle': { + const inverse = features[key]?.component === CheckboxInputInverse; + const on = inverse ? !row.value : !!row.value; + return { + ...base, + onPress: () => set(key, row.value ? 0 : 1), + value: (ty: number) => , + }; + } + case 'choice': + case 'number': { + const spec = choiceSpec(catalog, row); + if (spec) { + const value = String(row.value); + const step = (by: number) => { + const n = spec.list.length; + const at = spec.list.indexOf(value); + const next = spec.list[(((at < 0 ? 0 : at + by) % n) + n) % n]; + set(key, row.kind === 'number' ? Number(next) : next); + }; + return { + ...base, + onStep: step, + onPress: + spec.list.length > HANDFUL || + spec.list.some((c) => upper(spec.name(c)).length > PICK_W) + ? () => sub(, NAME, key) + : () => step(1), + value: (ty: number) => ( + + {cut(upper(spec.name(value)), VALUE_TEXT_W)} + + ), + }; + } + if (row.kind === 'choice') { + // No catalog yet: the value alone. + return { + ...base, + value: (ty: number) => ( + + {cut(upper(String(row.value)), VALUE_WIDE_W)} + + ), + }; + } + const v = Number(row.value) || 0; + const lo = row.min ?? 0; + const hi = row.max ?? 0; + const st = row.step || 1; + const step = (by: number) => { + const next = clamp(Math.round((v + by * st) * 100) / 100, lo, hi); + if (next !== v) { + set(key, next); + } + }; + const send = (t: string) => { + if (lo === -1 && t.trim() === 'AUTO') { + if (v !== -1) { + set(key, -1); + } + return; + } + const n = Number(t); + if (!t.trim() || !Number.isFinite(n)) { + return; + } + const stepped = lo + Math.round((n - lo) / st) * st; + const next = clamp(Math.round(stepped * 100) / 100, lo, hi); + if (next !== v) { + set(key, next); + } + }; + // tg draws these as sliders (the volumes): a track the mouse drags, coarse key steps. + if (features[key]?.component === FeatureSliderInput && hi > lo) { + const span = hi - lo; + const snap = (share: number) => + clamp( + Math.round((lo + Math.round((share * span) / st) * st) * 100) / + 100, + lo, + hi, + ); + const coarse = Math.max(1, Math.round(span / 20 / st)); + const held = drag?.key === key ? drag.v : null; + const now = held ?? v; + return { + ...base, + onStep: (by: number) => step(by * coarse), + ends: [now <= lo, now >= hi], + onPress: () => setTyping(key), + value: + typing === key + ? typeIn(numberText(row, v), 6, true, send) + : (ty: number, focused: boolean) => { + const text = numberText(row, now); + return ( + <> + + setDrag({ key, v: snap(share), held: true }) + } + onRelease={(share) => { + const next = snap(share); + setDrag({ key, v: next, held: false }); + if (next !== v) { + set(key, next); + } else { + setDrag(null); + } + }} + /> + + {text.slice(0, 4)} + + + ); + }, + }; + } + return { + ...base, + onStep: step, + ends: [v <= lo, v >= hi], + onPress: () => setTyping(key), + value: + typing === key + ? typeIn(numberText(row, v), 6, true, send) + : (ty: number) => ( + + {cut(numberText(row, v), VALUE_TEXT_W)} + + ), + }; + } + case 'color': { + const hex = parseHex(String(row.value)) || '#000000'; + return { + ...base, + onPress: () => sub(, NAME, key), + value: (ty: number) => ( + <> + + + {hex.toUpperCase()} + + + ), + }; + } + case 'text': { + const text = String(row.value ?? ''); + return { + ...base, + onPress: () => setTyping(key), + value: + typing === key + ? typeIn( + text, + Math.max(1, (row.max_length || 256) - 1), + false, + (t) => { + if (t !== text) { + set(key, t); + } + }, + ) + : (ty: number) => ( + + {cut(upper(text), VALUE_WIDE_W)} + + ), + }; + } + default: + return { + ...base, + muted: true, + value: (ty: number) => ( + + {cut(upper(String(row.value ?? '')), VALUE_WIDE_W)} + + ), + }; + } + }); + + return ( + + ); +} diff --git a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/ShipPic.tsx b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/ShipPic.tsx index 7169b0d3564..8240cc4b526 100644 --- a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/ShipPic.tsx +++ b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/ShipPic.tsx @@ -1,24 +1,50 @@ /** - * The yard's real full-colour preview on a recessed viewscreen: the finish's hull picture - * with each picked module laid on its slot, the same compositing as ShipPreview in - * ShipUpgradeSelector.tsx (module connector tile onto the slot marker tile). + * The colour ship picture (spec 02, 5.1): the yard's real pre-rendered preview inside a Well, + * the finish's hull picture with each picked module laid on its slot, the same compositing as + * ShipPreview in ShipUpgradeSelector.tsx (module connector tile onto the slot marker tile). * - * Scale: whole screen pixels per tile. 32 px tiles or more snap to a multiple of 32 and - * draw pixelated; anything smaller is a smooth downscale at a whole number of px per tile, - * so tiles never land between pixels. + * Scale: whole screen pixels per tile, the largest that fits inside a padding of 4 * lw. 32 px + * tiles or more snap down to a multiple of 32 and draw pixelated; anything smaller is a smooth + * downscale at a whole number of px per tile, so tiles never land between pixels. + * + * Missing pictures: no preview data, a well too small to hold one, or a hull layer that never + * arrives show `NO PICTURE ON FILE`. While the layers are on their way the well is empty. A + * module layer that never arrives is left out, so that room shows the bare hull. */ import { type CSSProperties, type ReactNode, useEffect, useState } from 'react'; import { resolveAsset } from 'tgui/assets'; +import { Wipe } from './motion'; +import { useGrid, Well } from './term'; +import type { ShipFit } from './YardTab'; + +/** Retries before a layer counts as missing: 20 x 250 ms = 5 s. */ +const TRIES = 20; +const RETRY_MS = 250; + +export const NO_PICTURE = 'NO PICTURE ON FILE'; + /** - * A preview image that keeps trying until its file has arrived. The first time a hull is - * opened its PNGs (and the URL mappings) are still on their way to the client, so the - * first load can fail; retry a few times, re-resolving the asset name each time. + * A preview layer that keeps trying until its file has arrived. The first time a hull is opened + * its PNGs (and the URL mappings) are still on their way to the client, so the first load can + * fail; retry, re-resolving the asset name each time. `onMissing` once it gives up. */ -function PreviewImg(props: { name: string; style: CSSProperties }) { - const { name, style } = props; +function PreviewImg(props: { + name: string; + style: CSSProperties; + onMissing?: () => void; +}) { + const { name, style, onMissing } = props; const [tries, setTries] = useState(0); - useEffect(() => setTries(0), [name]); + const [gone, setGone] = useState(false); + useEffect(() => { + if (gone) { + onMissing?.(); + } + }, [gone]); + if (gone) { + return null; + } // A new key remounts the , so the browser asks for the file again. return ( { - if (tries < 20) { - setTimeout(() => setTries((n) => n + 1), 250); + if (tries < TRIES) { + setTimeout(() => setTries((n) => n + 1), RETRY_MS); + } else { + setGone(true); } }} /> ); } -import { useGrid } from './term'; -import type { ShipFit } from './YardTab'; - type Geom = { png: string; width: number; @@ -50,45 +75,43 @@ type PreviewData = { modules: Record }>; }; -const PAD = 10; - export function ShipPic(props: { - /** Cells; fractions allowed. */ + /** Cells; y and h may be quarter rows. */ x: number; y: number; w: number; h: number; fit: ShipFit; - /** Slot key to outline in amber, or null. */ + /** Slot key of the room to mark (the fit's current room), or null. */ hiSlot?: string | null; + /** + * Counts options taken on the fit. When it changes, a cover the colour of the well retracts + * top to bottom over the marked room (the whole picture when no room is marked: a new + * finish), showing what was fitted. + */ + took?: number; }) { - const { x, y, w, h, fit, hiSlot } = props; - const { cw, ch } = useGrid(); - const sx = Math.round(x * cw); - const sy = Math.round(y * ch); - const sw = Math.round(w * cw); - const sh = Math.round(h * ch); - const frame: CSSProperties = { - left: sx, - top: sy, - width: sw, - height: sh, - }; - + const { x, y, w, h, fit, hiSlot, took } = props; + const { cw, ch, lw, s } = useGrid(); const pv = fit.hull.preview as PreviewData | null; const themeKey = fit.finish?.id || ''; const hull = pv?.hulls?.[themeKey] || pv?.hulls?.['']; - if (!pv || !hull || sw <= PAD * 2 || sh <= PAD * 2) { - return ( -
-
-
- ); + const hullPng = hull?.png || ''; + /** The hull picture that never arrived, if any. */ + const [missing, setMissing] = useState(null); + + // The well's inside: its rect less the 1 px screen border on each side. + const sw = Math.round((x + w) * cw) - Math.round(x * cw) - 2; + const sh = Math.round((y + h) * ch) - Math.round(y * ch) - 2; + const pad = 4 * lw; + const small = sw < 8 * lw + 8 || sh < 8 * lw + 8; + if (!pv || !hull || small || missing === hullPng) { + return ; } const tile = pv.tile_px || 32; - const aw = sw - PAD * 2; - const ah = sh - PAD * 2; + const aw = sw - pad * 2; + const ah = sh - pad * 2; let d = Math.floor(Math.min(aw / hull.width, ah / hull.height)); const crisp = d >= tile; if (crisp) { @@ -101,8 +124,9 @@ export function ShipPic(props: { const layers: ReactNode[] = [ setMissing(hullPng)} style={{ position: 'absolute', left: 0, @@ -113,10 +137,23 @@ export function ShipPic(props: { }} />, ]; + let mark: { l: number; t: number; w: number; h: number } | null = null; for (const slot of fit.slots) { const marker = hull.slots?.[slot.key]; + if (!marker) { + continue; + } const mod = slot.pick ? pv.modules?.[slot.pick.id] : undefined; - if (!marker || !mod) { + if (!mod) { + if (slot.key === hiSlot) { + // No picture for this room: the marker goes round its marker tile alone. + mark = { + l: (marker[0] - 1) * d, + t: (hull.height - marker[1]) * d, + w: d, + h: d, + }; + } continue; } const g = (themeKey && mod.themes?.[themeKey]) || mod; @@ -125,7 +162,7 @@ export function ShipPic(props: { const t = (hull.height - (marker[1] - cy) - g.height) * d; layers.push( , ); if (slot.key === hiSlot) { - layers.push( -
, - ); + mark = { l, t, w: g.width * d, h: g.height * d }; } } + if (mark) { + // An outline lw wide, one lw outside the room's rect, white with the violet glow. Still. + layers.push( +
, + ); + } + const left = Math.round((sw - iw) / 2); + const top = Math.round((sh - ih) / 2); + // The cover keeps inside the well: a room at the picture's edge never spills past it. + const room = mark + ? { + left: Math.max(0, left + mark.l), + top: Math.max(0, top + mark.t), + width: Math.min(sw, left + mark.l + mark.w) - Math.max(0, left + mark.l), + height: Math.min(sh, top + mark.t + mark.h) - Math.max(0, top + mark.t), + } + : { left: 0, top: 0, width: sw, height: sh }; return ( -
+
{layers}
-
-
+ {took !== undefined && ( + + )} +
); } diff --git a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/TraitsEditor.tsx b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/TraitsEditor.tsx index ea5925f65ac..0679a096a3a 100644 --- a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/TraitsEditor.tsx +++ b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/TraitsEditor.tsx @@ -1,95 +1,214 @@ /** - * TRAITS (CHARACTER-PLAN 2.7): GOOD/BAD/OTHER quirk list with values, the hovered or selected - * quirk's first sentence, the TAKEN box with POINTS and the positive count, char_quirk. - * Options of a taken quirk (customization_options) show under its description as ordinary - * char_set rows. Owner: C4. + * TRAITS (design 03b section 2): full width, no preview. The list on the left (columns 1 to + * 31): the filters TAKEN, GOOD, BAD and OTHER, paged trait rows, and under a taken trait one + * row an option. The panel on the right (33 to 61): points, the focused trait's name, its + * effect on the points, the reason a press would be refused, and its whole description. * - * Box: x and w are the editor frame's outer columns, y the row under its top line, - * y + h - 1 its bottom line. Points and caps are worked out here for display only, with - * tg's own rules (QuirksPage.tsx); the server decides. + * Whether a press would go through is worked out with tg's own rules (QuirksPage.tsx: the + * species list, the cap on good traits, the points, the clash groups) for display only; the + * server decides and the page redraws on the push. Options are ordinary char_set keys. */ -import { type ReactNode, useState } from 'react'; +import { Fragment, type ReactNode, useEffect, useState } from 'react'; import { useBackend } from 'tgui/backend'; import type { Quirk } from 'tgui/interfaces/PreferencesMenu/types'; -import { ColorEntry } from './ColorEntry'; +import { fileColours } from './BodyEditor'; import { - Cycler, - Frame, - Hit, - lpad, + clamp, + StepKeys, + useChar, + useLatePager, + useWheel, +} from './CharFrame'; +import { ColourPanel, ListPicker } from './CharPickers'; +import { parseHex } from './ColorEntry'; +import { sfx, sfxInstead, useChanged } from './motion'; +import { + Band, + Big, + BODY_Y, + bodyRows, + cut, + FlashAt, + HRule, + NameLine, + Pager, Put, - pad, RPut, - Rule, + Slab, + Swatch, + safe, useGrid, - wrap, + WipeAt, + wrapMax, } from './term'; -import type { CellBox, LobbyData } from './types'; -import { usePrefsCatalog } from './usePrefsCatalog'; +import type { LobbyData } from './types'; +import { choicesOf, nameOf, usePrefsCatalog } from './usePrefsCatalog'; -type Filter = 'good' | 'bad' | 'other'; -const FILTERS: [Filter, string][] = [ - ['good', 'GOOD'], - ['bad', 'BAD'], - ['other', 'OTHER'], +type Filter = 'taken' | 'good' | 'bad' | 'other'; +/** Filter, label, text column, block column, block width. */ +const FILTERS: [Filter, string, number, number, number][] = [ + ['taken', 'TAKEN', 2, 1, 7], + ['good', 'GOOD', 10, 9, 6], + ['bad', 'BAD', 17, 16, 5], + ['other', 'OTHER', 23, 22, 7], ]; -const HEX = /^#?[0-9a-f]{6}$/i; +/** The list column. */ +const LX = 1; +const LW = 31; +/** The panel. */ +const PX = 33; +const PW = 29; + +/** Option labels (03b section 2.2). */ +const LABELS: Record = { + language: 'LANGUAGE', + language_speakable: 'SPEAKS IT', + language_skill: 'FLUENCY', + csl_strength: 'FLUENCY', + chipped: 'CHIP', + paint_color: 'PAINT', + alcoholic: 'DRINK', + blindfold_color: 'BLINDFOLD', + food_allergy: 'ALLERGY', + hemiplegic: 'SIDE', + junkie: 'HABIT', + glasses: 'GLASSES', + paraplegic: 'LEGS', + prosthetic: 'LIMB', + prosthetic_organ: 'ORGAN', + rds_limit: 'UNLIMITED', + scarred_eye: 'EYE', + smoker: 'SMOKES', + phobia: 'FEAR', + trans_prosthetic: 'PART', + heterochromatic: 'ODD EYE', +}; + +export const optionLabel = (key: string) => + LABELS[key] || key.replace(/_/g, ' ').toUpperCase().slice(0, 9); -/** The first sentence of a description. */ -export function firstSentence(text: string): string { - const flat = (text || '').replace(/\s+/g, ' ').trim(); - const m = flat.match(/^(.+?[.!?])(\s|$)/); - return m ? m[1] : flat; +/** A trait's option keys that this file has (plus Heterochromatic's second eye colour). */ +function optionsOf(k: string, q: Quirk, prefs: Record) { + const keys = [...(q.customization_options || [])]; + if (k === 'Heterochromatic' && !keys.includes('heterochromatic')) { + keys.push('heterochromatic'); + } + return keys.filter((key) => key in prefs); } -/** A savefile key as a row label: "prosthetic_organ" -> "PROSTHETIC ORGAN". */ -function keyLabel(key: string): string { - return key.replace(/_/g, ' ').toUpperCase(); +type OptKind = 'pick' | 'flip' | 'colour' | 'none'; + +function kindOf(cat: ReturnType, key: string, value: unknown): OptKind { + const list = choicesOf(cat, key); + if (list && list.length >= 3) { + return 'pick'; + } + if (list && list.length === 2) { + return 'flip'; + } + if (typeof value === 'string' && parseHex(value)) { + return 'colour'; + } + if (typeof value === 'number' || typeof value === 'boolean') { + return 'flip'; + } + return 'none'; } -/** Every "#rrggbb" already on the file, for the colour entry's recent row. */ -export function fileColors( - prefs: Record, - extra: string[] = [], -): string[] { - const out: string[] = []; - const add = (v: unknown) => { - if (typeof v !== 'string' || !HEX.test(v)) { - return; +/** The list picker on a trait option (level 2, in the list column). */ +function TraitPick(props: { k: string; label: string }) { + const { k, label } = props; + const { act, data } = useBackend(); + const cat = usePrefsCatalog(); + const { closeSub } = useChar(); + const prefs = data.char?.prefs || {}; + const gone = !(k in prefs); + useEffect(() => { + if (gone) { + closeSub(); } - const hex = (v[0] === '#' ? v : `#${v}`).toLowerCase(); - if (!out.includes(hex)) { - out.push(hex); + }, [gone]); + return ( + nameOf(cat, k, v)} + onPick={(v) => act('char_set', { key: k, value: v })} + onClose={closeSub} + /> + ); +} + +/** The colour panel on a trait option (level 2, in the list column, no native picker). */ +function TraitColour(props: { k: string; label: string }) { + const { k, label } = props; + const { act, data } = useBackend(); + const { closeSub } = useChar(); + const char = data.char; + const prefs = char?.prefs || {}; + const gone = !(k in prefs); + useEffect(() => { + if (gone) { + closeSub(); } - }; - extra.forEach(add); - Object.values(prefs || {}).forEach(add); - return out.slice(0, 8); + }, [gone]); + return ( + act('char_set', { key: k, value: hex })} + onClose={closeSub} + /> + ); } -export function TraitsEditor(props: CellBox) { - const { x, y, w, h } = props; +/** One drawn block of the list: a trait and its option rows. */ +type Block = { k: string; opts: string[] }; + +export function TraitsEditor() { const { act, data } = useBackend(); - const { narrow } = useGrid(); - const catalog = usePrefsCatalog(); + const cat = usePrefsCatalog(); + const { sub, subOpen, from, quiet } = useChar(); + const { rows: M } = useGrid(); const char = data.char; - const [filter, setFilter] = useState('good'); - const [page, setPage] = useState(1); - const [sel, setSel] = useState(null); - const [hover, setHover] = useState(null); + const takenAtOpen = (char?.quirks || []).length > 0; + const [filter, setFilter] = useState(takenAtOpen ? 'taken' : 'good'); + const [page, setPage] = useState(0); + const [shown, setShown] = useState(null); + const [fresh, setFresh] = useState(true); + /** Presses the rules refused: each one draws the reason again. */ + const [refused, setRefused] = useState(0); + const pager = useLatePager(); + const wheel = useWheel(); + // A trait was taken: the accepted sound (its row flashes below). + useChanged((char?.quirks || []).length, (was, now) => { + if (now > was) { + sfx('ok', { own: true }); + } + }); - if (!char || !catalog) { + if (!char || !cat?.quirks) { + pager.current = null; return null; } + const prefs = char.prefs || {}; const { quirk_info: info, max_positive_quirks: maxGood, quirk_blacklist: blacklist, - points_enabled: pointsOn, - } = catalog.quirks; + points_enabled: pointsOnRaw, + } = cat.quirks; + const pointsOn = !!pointsOnRaw; + // char.quirks are quirk_info keys (sanitize_css_class_name), in the order taken. const taken = (char.quirks || []).filter((k) => !!info[k]); let balance = 0; let good = 0; @@ -102,491 +221,395 @@ export function TraitsEditor(props: CellBox) { const points = -balance; const takenNames = taken.map((k) => info[k].name); const blocked = char.quirks_blocked || []; + const species = safe(nameOf(cat, 'species', prefs.species)).toUpperCase(); - const canAdd = (k: string) => { + /** Why a press on this trait would be refused, or null. */ + const reasonOf = (k: string): string | null => { const q = info[k]; + if (taken.includes(k)) { + return pointsOn && balance - q.value > 0 ? 'ITS POINTS ARE SPENT' : null; + } if (blocked.includes(k) || blocked.includes(q.name)) { - return false; + return `${species || 'YOUR SPECIES'} CAN'T TAKE IT`; } - if (q.value > 0) { - if (maxGood !== -1 && good >= maxGood) { - return false; - } - if (pointsOn && balance + q.value > 0) { - return false; - } + if (q.value > 0 && maxGood !== -1 && good >= maxGood) { + return `${maxGood} GOOD TRAITS ALREADY`; + } + if (q.value > 0 && pointsOn && balance + q.value > 0) { + return 'NOT ENOUGH POINTS'; } for (const group of blacklist || []) { if (!group.includes(q.name)) { continue; } - if (group.some((n) => n !== q.name && takenNames.includes(n))) { - return false; + const other = group.find((n) => n !== q.name && takenNames.includes(n)); + if (other) { + return `CLASHES WITH ${safe(other).toUpperCase()}`; } } - return true; + return null; }; - const canRemove = (k: string) => !(pointsOn && balance - info[k].value > 0); - const toggle = (k: string) => { - const on = !taken.includes(k); - if (on ? !canAdd(k) : !canRemove(k)) { + const press = (k: string) => { + setShown(k); + if (reasonOf(k)) { + // Refused: the reason draws itself in the panel, with the refusal sound. + sfxInstead('warn'); + setRefused((n) => n + 1); return; } - act('char_quirk', { quirk: k, on: on ? 1 : 0 }); + act('char_quirk', { quirk: k, on: taken.includes(k) ? 0 : 1 }); }; - const split = !narrow && w >= 80; - const takenW = split ? Math.floor(w * 0.42) : w; - const ax = x; - const aw = split ? w - takenW : w; - - // ---- TAKEN ---- - const tx = split ? x + aw : x; - const TW = split ? takenW - 2 : w; - const takenRows: ReactNode[] = []; - let ty = y + (split ? 2 : 1); - takenRows.push( - , - ); - ty += 2; - const takenMax = split - ? y + h - 4 - ty - : Math.max(2, Math.min(taken.length, Math.floor((h - 12) / 2))); - const shownTaken = taken.slice(0, Math.max(0, takenMax)); - for (const k of shownTaken) { - const q = info[k]; - const can = canRemove(k); - takenRows.push( - setSel(k)} - onRemove={() => toggle(k)} - />, - ); - ty++; - } - if (taken.length > shownTaken.length) { - takenRows.push( - - {`+${taken.length - shownTaken.length}`} - , - ); - ty++; + // ---- the list + let keys: string[]; + if (filter === 'taken') { + keys = taken; + } else { + keys = Object.keys(info).filter((k) => { + const v = info[k].value; + return filter === 'good' ? v > 0 : filter === 'bad' ? v < 0 : v === 0; + }); + keys.sort((a, b) => { + const va = Math.abs(info[a].value); + const vb = Math.abs(info[b].value); + if (va !== vb) { + return vb - va; + } + return info[a].name < info[b].name ? -1 : 1; + }); } + const blocks: Block[] = keys.map((k) => ({ + k, + opts: taken.includes(k) ? optionsOf(k, info[k], prefs) : [], + })); - // ---- list ---- - let yy = split ? y + 1 : ty + 1; - const ruleY = yy - 0.5; - if (!split) { - yy += 1; + const B = bodyRows(M); + const roomy = B >= 20; + const pitch = roomy ? 1.5 : 1.25; + const gap = pitch - 1.25; + const sizeOf = (b: Block) => (1 + b.opts.length) * 1.25 + gap; + const fill = (room: number) => { + const pages: Block[][] = [[]]; + let used = 0; + for (const b of blocks) { + const s = sizeOf(b); + if (used + s > room + 1e-6 && pages[pages.length - 1].length) { + pages.push([]); + used = 0; + } + pages[pages.length - 1].push(b); + used += s; + } + return pages; + }; + const listTop = 5.25; + let pages = fill(M - 1.25 - listTop + gap); + if (pages.length > 1) { + pages = fill(M - 2.25 - 0.25 - listTop + gap); } - const filterY = yy; - yy += 2; + const pg = Math.min(page, pages.length - 1); + const onPage = pages[pg] || []; + const turn = + pages.length > 1 && !subOpen + ? (step: number) => { + setFresh(false); + setPage(clamp(pg + step, 0, pages.length - 1)); + } + : null; + pager.current = turn; - const options = - sel && info[sel] && taken.includes(sel) && (!hover || hover === sel) - ? (info[sel].customization_options || []).filter( - (key) => key in (char.prefs || {}), - ) - : []; - const descH = 3 + options.length; + // The panel shows the focused row; on entry the first row. + const panelKey = + shown && info[shown] ? shown : onPage[0]?.k || keys[0] || null; - const list = Object.keys(info).filter((k) => { - const v = info[k].value; - return filter === 'good' ? v > 0 : filter === 'bad' ? v < 0 : v === 0; - }); - list.sort((a, b) => { - const va = Math.abs(info[a].value); - const vb = Math.abs(info[b].value); - if (va !== vb) { - return vb - va; - } - return info[a].name < info[b].name ? -1 : 1; - }); - const room = Math.max(3, Math.floor(y + h - 2 - descH - yy)); - const pages = Math.max(1, Math.ceil(list.length / room)); - const pg = Math.min(pages, page); - const rows = list.slice((pg - 1) * room, pg * room); - // The selected row, else the first one on the page, so the description is never blank. - const current = sel && info[sel] ? sel : rows[0] || null; - // The quirk whose words show at the bottom: the hovered row, else the current one. - const shown = hover && info[hover] ? hover : current; - const descLines = shown - ? wrap(firstSentence(info[shown].description), aw - 6).slice( - 0, - options.length ? 1 : 2, - ) - : []; - const py = y + h - 2 - descH; - const descY = y + h - 1 - descH; - const recent = fileColors(char.prefs); - - return ( - <> - {!!split && } - {takenRows} - {!split && } - { - setFilter(f); - setPage(1); - setHover(null); + const rows: ReactNode[] = []; + let y = listTop; + onPage.forEach((b, i) => { + const q = info[b.k]; + const isTaken = taken.includes(b.k); + const reason = reasonOf(b.k); + const alt = !roomy && i % 2 === 1; + const v = q.value; + const blockY = y; + rows.push( + { + if (f) { + setShown(b.k); + } }} - /> - {rows.map((k, i) => { - const isTaken = taken.includes(k); - return ( - { - setSel(k); - toggle(k); - }} - onHover={(over) => setHover((h) => (over ? k : h === k ? null : h))} - /> + onClick={() => press(b.k)} + > + + {cut(safe(q.name), 24)} + + {!!pointsOn && v !== 0 && ( + 0 ? 'amb' : ''} + > + {v > 0 ? `-${v}` : `+${-v}`} + + )} + , + // The row flashes when it is taken, dropped, or loses its mark to another trait. + , + ); + b.opts.forEach((key, j) => { + const oy = blockY + 1.25 * (j + 1); + const value = prefs[key]; + const kind = kindOf(cat, key, value); + const label = optionLabel(key); + const list = choicesOf(cat, key) || []; + let onPress: (() => void) | undefined; + let shownValue: ReactNode = null; + /** `<` `>` on a value with two or more choices (as BODY's rows have them). */ + let onStep: ((by: number) => void) | null = null; + if (kind === 'pick') { + onPress = () => sub(, label, key); + onStep = (by) => { + const at = list.indexOf(String(value)); + const n = list.length; + act('char_set', { + key, + value: list[(((at < 0 ? 0 : at + by) % n) + n) % n], + }); + }; + shownValue = ( + + {cut(safe(nameOf(cat, key, value)), 10)} + ); - })} - {pages > 1 && ( - { - setPage(p); - setHover(null); + } else if (kind === 'flip') { + onPress = () => { + if (list.length === 2) { + act('char_set', { + key, + value: list[list.indexOf(String(value)) === 0 ? 1 : 0], + }); + } else { + act('char_set', { key, value: value ? 0 : 1 }); + } + }; + onStep = onPress; + shownValue = ( + + {list.length === 2 + ? cut(safe(nameOf(cat, key, value)), 10) + : value + ? 'YES' + : 'NO'} + + ); + } else if (kind === 'colour') { + const hex = parseHex(String(value)) || '#000000'; + onPress = () => sub(, label, key); + shownValue = ( + <> + + + {hex.toUpperCase()} + + + ); + } else { + shownValue = ( + + {cut(safe(String(value ?? '')), 16)} + + ); + } + rows.push( + { + if (f) { + setShown(b.k); + } }} - /> - )} - {descLines.map((line, i) => ( - - {line} - - ))} - {options.map((key, i) => ( - act('char_set', { key, value })} - /> - ))} - - ); -} + onClick={onPress} + > + + {label} + + {shownValue} + {!!onStep && } + , + ); + }); + y += sizeOf(b); + }); -function TakenHead(props: { - x: number; - y: number; - w: number; - points: number | null; - good: number; - maxGood: number; -}) { - const { x, y, w, points, good, maxGood } = props; + // ---- the panel const capped = maxGood !== -1 && good >= maxGood; - return ( + const goodText = + maxGood === 0 ? '' : maxGood === -1 ? `GOOD ${good}` : `GOOD ${good}/${maxGood}`; + const pq = panelKey ? info[panelKey] : null; + const pv = pq?.value || 0; + const panelReason = panelKey ? reasonOf(panelKey) : null; + const descLines = pq + ? wrapMax( + safe(pq.description).replace(/\s+/g, ' ').trim(), + PW, + // From 9.75, ending by M - 1.5 so the last line clears the box's bottom border. + Math.max(1, Math.floor(M - 11.25)), + ) + : []; + const panel = ( <> - {points !== null && ( + {!!pointsOn && ( <> - - {'POINTS'} - - 0 ? 'amb' : ''} + 0 ? 'acc' : 'dim'} + pulse={points} > - {lpad(points, 3)} + {String(Math.min(999, points))} + + + {'POINTS'} )} - {maxGood !== 0 && ( - - {maxGood === -1 ? `GOOD ${good}` : `GOOD ${good}/${maxGood}`} - - )} - - ); -} - -function TakenRow(props: { - x: number; - y: number; - w: number; - quirk: Quirk; - sel: boolean; - canRemove: boolean; - onSelect: () => void; - onRemove: () => void; -}) { - const { x, y, w, quirk, sel, canRemove, onSelect, onRemove } = props; - const v = quirk.value; - return ( - <> - - {pad(quirk.name, w - 13)} - - 0 ? 'amb' : v < 0 ? 'dim' : 'faint'}> - {lpad(v, 3)} - - {canRemove ? ( - - {'[X]'} - - ) : ( - - {'[X]'} + {!!goodText && ( + + {goodText} )} + + {!!pq && ( + <> + + {!!pointsOn && pv !== 0 && ( + 0 ? 'amb' : ''}> + {pv > 0 ? `-${pv} POINTS` : `+${-pv} POINTS`} + + )} + {!!taken.includes(panelKey!) && ( + + {' TAKEN '} + + )} + {!!panelReason && ( + + {cut(panelReason, PW)} + + )} + + {descLines.map((line, i) => ( + + {line} + + ))} + + )} ); -} -function FilterKeys(props: { - x: number; - y: number; - filter: Filter; - onFilter: (f: Filter) => void; -}) { - const { x, y, filter, onFilter } = props; - let fx = x; + if (subOpen) { + return panel; + } + return ( <> - {FILTERS.map(([key, label]) => { - const at = fx; - fx += label.length + 4; + {FILTERS.map(([f, label, tx, bx, bw]) => { + const open = f === filter; return ( - onFilter(key)} - > - {` ${label} `} - + + {!!open && } + { + if (f !== filter) { + setFresh(false); + setFilter(f); + setPage(0); + } + }} + > + {label} + + ); })} - - ); -} - -function QuirkRow(props: { - x: number; - y: number; - w: number; - quirk: Quirk; - taken: boolean; - /** Can't be taken now: dim, and a click only selects it. */ - cant: boolean; - /** Taken but can't be dropped now. */ - locked: boolean; - sel: boolean; - onClick: () => void; - onHover: (over: boolean) => void; -}) { - const { x, y, w, quirk, taken, cant, sel, onClick, onHover } = props; - const v = quirk.value; - const nameCls = sel ? 'inv' : taken ? 'amb' : cant ? 'faint' : ''; - const valCls = sel ? 'inv' : cant ? 'faint' : v > 0 ? 'amb' : 'dim'; - return ( - <> - {!!sel && ( - - {' '.repeat(Math.max(0, w - 2))} - - )} - - {taken ? '*' : ' '} - - - {pad(quirk.name, w - 10)} - - - {String(v)} - - - - ); -} - -function Pager(props: { - x: number; - y: number; - page: number; - pages: number; - onPage: (page: number) => void; -}) { - const { x, y, page, pages, onPage } = props; - return ( - <> - {page > 1 ? ( - onPage(page - 1)}> - {' < '} - + + {keys.length ? ( + // The mouse wheel turns the pages, one a notch. +
{rows}
) : ( - - {' < '} - - )} - - {`${page}/${pages}`} - - {page < pages ? ( - onPage(page + 1)}> - {' > '} - - ) : ( - - {' > '} - + <> + + + )} + { + setFresh(false); + setPage(p - 1); + }} + right + /> + {/* Another filter, or another page, turns the page of the rows only. */} + f[0] === filter) * 1000 + pg} + /> + {panel} ); } - -type OptionServerData = { - choices?: string[]; - display_names?: Record; - minimum?: number; - maximum?: number; - step?: number; -} | null; - -/** One quirk option row: a choice cycler, a number stepper, a yes/no, or a colour. */ -function QuirkOption(props: { - x: number; - y: number; - w: number; - prefKey: string; - value: any; - serverData: OptionServerData; - recent: string[]; - onSet: (value: unknown) => void; -}) { - const { x, y, w, prefKey, value, serverData, recent, onSet } = props; - const label = keyLabel(prefKey); - const lw = 18; - const cw = Math.max(8, Math.min(24, w - lw - 4)); - const labelRow = ( - - {pad(label, lw - 1)} - - ); - if (serverData?.choices?.length) { - const choices = serverData.choices; - const i = Math.max(0, choices.indexOf(value)); - const name = (v: string) => serverData.display_names?.[v] || v; - const step = (d: number) => - onSet(choices[(i + d + choices.length) % choices.length]); - return ( - <> - {labelRow} - step(-1)} - onNext={() => step(1)} - /> - - ); - } - if (typeof serverData?.minimum === 'number') { - const lo = serverData.minimum; - const hi = serverData.maximum ?? lo; - const st = serverData.step || 1; - const n = Number(value) || 0; - return ( - <> - {labelRow} - onSet(Math.max(lo, n - st))} - onNext={() => onSet(Math.min(hi, n + st))} - /> - - ); - } - if (typeof value === 'string' && HEX.test(value)) { - const hex = value[0] === '#' ? value : `#${value}`; - return ( - onSet(c)} - /> - ); - } - if (typeof value === 'number') { - const flip = () => onSet(value ? 0 : 1); - return ( - <> - {labelRow} - - - ); - } - return null; -} diff --git a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/Welcome.tsx b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/Welcome.tsx new file mode 100644 index 00000000000..11b70fdbd38 --- /dev/null +++ b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/Welcome.tsx @@ -0,0 +1,78 @@ +/** + * WELCOME, asked once of a first-timer (first_time_notice.dm): combat mode or intents, with + * COMBAT MODE focused. LATER, Escape or a click outside closes it for this connection. + */ +import { useBackend } from 'tgui/backend'; + +import { quietDialogClose } from './motion'; +import { Back } from './nav'; +import { BODY_Y, Big, Btn, Dialog, Put, RPut, Slab, useGrid } from './term'; +import type { LobbyData } from './types'; + +const W = 45; +const H = 11; + +const CHOICES: [mode: string, name: string, key: string, line: string][] = [ + ['combat', 'COMBAT MODE', 'F', 'ONE SWITCH: GUARD UP OR DOWN.'], + ['intents', 'INTENTS', '1-4', 'HELP, DISARM, GRAB, HARM.'], +]; + +export function Welcome(props: { onLater: () => void; onClose: () => void }) { + const { onLater, onClose } = props; + const { act } = useBackend(); + const { cols } = useGrid(); + const x = Math.floor((cols - W) / 2); + const y = BODY_Y + 2; + const pick = (mode: string) => { + // Answered, not backed out of: the box goes without the back sound. + quietDialogClose(); + onClose(); + act('welcome_pick', { mode }); + }; + return ( + <> +
{ + e.stopPropagation(); + onLater(); + }} + /> + + + + FIRST TIME IN PORT. HOW DO YOU FIGHT? + + {CHOICES.map(([mode, name, key, line], i) => { + const sy = y + 2.5 + i * 3.25; + return ( + pick(mode)} + > + + {name} + + + {key} + + + {line} + + + ); + })} + + IT CAN BE CHANGED IN SETTINGS. + + + + + ); +} diff --git a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/YardHome.tsx b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/YardHome.tsx new file mode 100644 index 00000000000..3f0a8f3cf24 --- /dev/null +++ b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/YardHome.tsx @@ -0,0 +1,219 @@ +/** + * SHIPYARD home (spec 02, 3.2): two stacked boxes. SHIPYARD holds the NEW SHIP slab with the + * parts on account and, while the yard offers one, the SURPLUS HULL slab. SAVED SHIPS holds + * the three save slots (SaveSlots.tsx). + * + * Forms, the first that fits: 1 tall top slabs and full slots; 2 compact top slabs and full + * slots; 3 tall top slabs and compact slot rows; 4 compact everything (M = 18 with the + * surplus hull leaves exactly 7.25 rows for three rows). + */ +import { useBackend } from 'tgui/backend'; + +import { SaveSlots } from './SaveSlots'; +import { + BOX_Y, + Box, + ClassFigures, + ClassHeads, + fig, + Key, + NameLine, + PART_CLASSES, + Put, + Slab, + SEP, + useGrid, +} from './term'; +import type { LobbyData, SaveCard } from './types'; +import { YARD_OPENS, type YardCtx } from './YardTab'; + +/** Rounded down to a quarter row. */ +const f4 = (v: number) => Math.floor(v * 4) / 4; + +const BEFORE_ROUND = ['loading', 'pregame', 'setup']; + +/** Compact NEW SHIP figures: `COMBAT n` at 10, `SCIENCE n` at 23, `TRADE n` at 37, `MISC n` at 49. */ +const COMPACT_AT = [10, 23, 37, 49]; + +/** A slot whose ship could load once the port opens. */ +export function loadable(card: SaveCard | null): boolean { + return !!card && !card.denial && !card.locked; +} + +export type HomeForm = { + /** Top slabs tall (h 3) or compact (h 2.25). */ + tall: boolean; + /** Slots full (plan, h = slotH) or compact rows. */ + full: boolean; + /** Rows of slabs in the SHIPYARD box. */ + a: number; + /** First slot row. */ + yB: number; + /** Rows the slots may use. */ + availB: number; + /** Full slot height. */ + slotH: number; +}; + +export function homeForm(M: number, tops: number, foot: number): HomeForm { + const at = (Ht: number) => { + const a = tops * Ht + 0.25 * (tops - 1); + const yB = a + 4.75; + const availB = M - 1.25 - yB - foot; + return { a, yB, availB, slotH: f4((availB - 0.5) / 3) }; + }; + const tallF = at(3); + if (tallF.slotH >= 4) { + return { tall: true, full: true, ...tallF }; + } + const compF = at(2.25); + if (compF.slotH >= 4) { + return { tall: false, full: true, ...compF }; + } + if (tallF.availB >= 7.25) { + return { tall: true, full: false, ...tallF }; + } + return { tall: false, full: false, ...compF }; +} + +export function YardHome(props: { ctx: YardCtx }) { + const { ctx } = props; + const { data } = useBackend(); + const { rows: M } = useGrid(); + const req = !!data.can_requisition; + const saves = data.saves || { state: 'wait', slots: [] }; + const slots: (SaveCard | null)[] = + saves.state === 'ok' ? [0, 1, 2].map((i) => saves.slots[i] || null) : []; + const before = BEFORE_ROUND.includes(data.phase); + const footLine = before && slots.some(loadable); + const form = homeForm(M, req ? 2 : 1, footLine ? 1.25 : 0); + const Ht = form.tall ? 3 : 2.25; + const variant = form.tall ? 'block' : 'row'; + const y0 = 3; + const y1 = y0 + Ht + 0.25; + + // The parts on account: not drawn while the ledger is read, nor when every hull is free. + const ledger = data.free_ships ? 'none' : ctx.ledger; + const account = data.account || {}; + + return ( + <> + + + {form.tall ? ( + + ) : ( + + NEW SHIP + + )} + {ledger === 'off' && ( + + {form.tall ? 'Ledger offline' : 'LEDGER OFFLINE'} + + )} + {ledger === 'ok' && !!form.tall && ( + <> + + Parts on account + + + + + )} + {ledger === 'ok' && !form.tall && ( + <> + + PARTS + + {PART_CLASSES.map((k, i) => ( + + {k.toUpperCase()} + + ))} + {PART_CLASSES.map((k, i) => ( + + {fig(account[k]) || '0'} + + ))} + + )} + + {!!req && ( + + {form.tall ? ( + + ) : ( + + SURPLUS HULL + + )} + + {`Yard's choice ${SEP} no charge`} + + + ctx.found({ + action: 'yard_requisition', + params: {}, + label: 'REQUISITION', + }) + } + /> + + )} + + + {!!footLine && ( + + {YARD_OPENS} + + )} + + ); +} diff --git a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/YardTab.tsx b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/YardTab.tsx index 0b099dc9bd5..c9ae0e35463 100644 --- a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/YardTab.tsx +++ b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/YardTab.tsx @@ -1,9 +1,40 @@ /** - * SHIPYARD tab: home (new ship, requisition, saved ships), then HULLS -> hull record -> - * FIT -> BILL. Where the player is and what they picked stays in React (a module-level - * store, so it survives a tab switch); only yard_* actions reach DM. + * SHIPYARD tab: the store, the screen router, the tab row's right zone (BACK, crumbs, the hull + * stepper) and the helpers every shipyard screen shares. One file a screen: YardHome.tsx + * (home), Hulls.tsx (list) and HullRecord.tsx (record), Fit.tsx, Bill.tsx, and LeaveCrew.tsx + * (the LEAVE CREW dialog, drawn by the router over any screen). * - * The catalog arrives in static data only after `yard_open`. Keys: see types.ts. + * Screens get everything through `ctx: YardCtx`, worked out once a render here: + * + * ctx.view the store (YardView). Module level: a tab switch or the CONFIRMED + * box keeps it. Taken values live here (finish, picks); the option + * shown on the fit's open step may live here (`shown`) or in the Fit. + * ctx.set(patch) patch the store; `patch` may be a function of the current view. + * ctx.go.home() the home. + * ctx.go.hulls() the hull list; it focuses `view.lastHull` and turns to its page. + * ctx.go.record(id) a hull's record. + * ctx.go.fitOut(hull) FIT OUT: keeps the fit when it belongs to this hull, else starts from + * stock. A hull with nothing to fit goes straight to the bill. + * ctx.go.fit(step?) the fit, at `step` or where it was. + * ctx.go.bill() the bill. + * ctx.go.back() [ BACK ] and Escape (spec 02, 2.3). The router mounts the useBack. + * ctx.catalog the shelf ([] until it arrives; ctx.loaded says whether it has). + * ctx.hull the hull open in the record, fit or bill, or null. + * ctx.fit, ctx.bill that hull's fit as taken (fitOf) and its bill (billOf), or null. + * ctx.own, ctx.account, ctx.ledger ('wait' | 'ok' | 'off') + * ctx.open the port is open (2.5). Keys that put the player in the round are + * dead while it is not; YARD_OPENS is the one line that says why. + * ctx.sent a founding key was just sent (2.6): draw those keys dead. + * ctx.crewChange the crew the player would leave, or null. + * ctx.found(ask) press COMMISSION, REQUISITION or LOAD: in a crew it opens LEAVE + * CREW (not for a load that `restores`), otherwise it sends with + * leave_crew 0. Only the dialog's own key ever sends leave_crew 1. + * + * Helpers: PART_ORDER, costOf, partsOf, priceText, thousands, hullOwned, finishOwned, + * moduleOwned, slotLabel, defaultFinish, slotOptions, fitOf, stockFit, fittable, stepsOf, + * crewOf, crewCount, crewText, billOf (the one place the page works a bill out; its `total` is + * what yard_commission sends), usePreview. Drawing: ClassHeads, ClassFigures, Well, Slab `on` + * and fig() are in term.tsx. */ import { type ReactNode, useEffect, useMemo, useState } from 'react'; import { useBackend } from 'tgui/backend'; @@ -11,25 +42,43 @@ import { useBackend } from 'tgui/backend'; import { Bill } from './Bill'; import { Fit } from './Fit'; import { Hulls } from './Hulls'; +import { LeaveCrew } from './LeaveCrew'; +import { noteFounding, quietDialogClose, useScreen } from './motion'; import { useBack } from './nav'; -import { SaveSlots } from './SaveSlots'; -import { Frame, type NavProps, Put, RPut, TOP, useGrid } from './term'; +import { + BODY_Y, + Box, + BOX_Y, + Btn, + NameLine, + PART_CLASSES, + Pager, + Put, + Slab, + useGrid, +} from './term'; import type { CrewLine, Finish, Hull, + LedgerState, + LobbyActions, LobbyData, Module, Owned, PartClass, Parts, } from './types'; +import { YardHome } from './YardHome'; // --------------------------------------------------------------------------- -// Catalog helpers (shared by Hulls, HullRecord, Fit and Bill). +// Numbers and words (spec 02, 2.1) // --------------------------------------------------------------------------- -export const PART_ORDER: PartClass[] = ['combat', 'science', 'trade', 'misc']; +export const PART_ORDER: PartClass[] = PART_CLASSES; + +/** The line shown before the round, once a tab (2.5). */ +export const YARD_OPENS = 'THE YARD OPENS AT DEPARTURE.'; /** "4 COMBAT 2 TRADE", or '' when nothing is due. */ export function costOf(cost?: Parts | null): string { @@ -42,6 +91,12 @@ export function partsOf(cost?: Parts | null): number { return PART_ORDER.reduce((a, k) => a + (cost?.[k] || 0), 0); } +/** A price in `room` cells: by class when it fits, else the sum as `9 PARTS`. */ +export function priceText(cost: Parts | null | undefined, room: number): string { + const byClass = costOf(cost); + return byClass.length <= room ? byClass : `${partsOf(cost)} PARTS`; +} + /** 1,850 */ export function thousands(n: number): string { return String(Math.round(n)).replace(/\B(?=(\d{3})+(?!\d))/g, ','); @@ -147,6 +202,16 @@ export function stockFit(hull: Hull): ShipFit { return fitOf(hull, null, {}); } +/** A hull with finishes or rooms has a fit; one with neither goes from the record to the bill. */ +export function fittable(hull: Hull): boolean { + return !!hull.finishes.length || !!hull.slots.length; +} + +/** Steps of a fit: FINISH when the hull has finishes, then one a room. */ +export function stepsOf(fit: ShipFit): number { + return (fit.hull.finishes.length ? 1 : 0) + fit.slots.length; +} + /** Crew manifest of a fit, same titles summed. */ export function crewOf(fit: ShipFit): CrewLine[] { const out: CrewLine[] = []; @@ -174,15 +239,59 @@ export function crewCount(fit: ShipFit): number { return crewOf(fit).reduce((a, l) => a + l[1], 0); } -/** [label, name, cost or null when owned] */ -export type BillLine = [string, string, Parts | null]; +/** The jobs as `Title` or `Title x3`, joined by `, `. */ +export function crewText(fit: ShipFit): string { + return crewOf(fit) + .filter((l) => l[1] > 0) + .map(([title, n]) => (n > 1 ? `${title} x${n}` : title)) + .join(', '); +} + +/** What a line costs nothing for: a hull that costs nothing, a stock item, one bought earlier. */ +export type BillWord = 'FREE' | 'STOCK' | 'OWNED'; + +export type BillLine = { + kind: 'hull' | 'finish' | 'module'; + id: string; + /** HULL, FINISH or the room's label. */ + label: string; + /** The name of what is built. */ + name: string; + /** What this line costs now, or null when it costs nothing. */ + cost: Parts | null; + /** Why it costs nothing (when cost is null). */ + word: BillWord | null; +}; export type ShipBill = { lines: BillLine[]; + /** Only the classes due. */ total: Parts; + /** Only the classes the account can't cover. Empty when the account isn't known. */ short: Parts; }; +function lineOf( + kind: BillLine['kind'], + id: string, + label: string, + name: string, + cost: Parts, + stock: boolean, + owned: boolean, + free: boolean, +): BillLine { + let word: BillWord | null = null; + if (kind === 'hull') { + word = free || !partsOf(cost) ? 'FREE' : owned ? 'OWNED' : null; + } else if (stock || !partsOf(cost)) { + word = 'STOCK'; + } else if (free || owned) { + word = 'OWNED'; + } + return { kind, id, label, name, cost: word ? null : cost, word }; +} + export function billOf( o: Ownership, fit: ShipFit, @@ -190,86 +299,156 @@ export function billOf( ): ShipBill { const { hull, finish } = fit; const lines: BillLine[] = [ - ['HULL', hull.short, hullOwned(o, hull) ? null : hull.cost], + lineOf( + 'hull', + hull.id, + 'HULL', + hull.short, + hull.cost, + false, + !!o.owned?.hulls?.includes(hull.id), + o.free || !!hull.free, + ), ]; if (finish) { - lines.push([ - 'FINISH', - finish.name, - finishOwned(o, hull, finish) ? null : finish.cost, - ]); + lines.push( + lineOf( + 'finish', + finish.id, + 'FINISH', + finish.name, + finish.cost, + !!finish.def, + finishOwned(o, hull, finish), + o.free, + ), + ); } for (const s of fit.slots) { if (s.pick) { - lines.push([ - s.label, - s.pick.name, - moduleOwned(o, hull, s.pick) ? null : s.pick.cost, - ]); + lines.push( + lineOf( + 'module', + s.pick.id, + s.label, + s.pick.name, + s.pick.cost, + !!s.pick.def, + moduleOwned(o, hull, s.pick), + o.free, + ), + ); } } const total: Parts = {}; for (const l of lines) { for (const k of PART_ORDER) { - const n = l[2]?.[k] || 0; - if (n) { + const n = l.cost?.[k] || 0; + if (n > 0) { total[k] = (total[k] || 0) + n; } } } const short: Parts = {}; - for (const k of PART_ORDER) { - const due = total[k] || 0; - const have = account?.[k] || 0; - if (due > have) { - short[k] = due - have; + if (account) { + for (const k of PART_ORDER) { + const due = total[k] || 0; + const have = account[k] || 0; + if (due > have) { + short[k] = due - have; + } } } return { lines, total, short }; } // --------------------------------------------------------------------------- -// UI-local state. +// The store // --------------------------------------------------------------------------- export type YardScreen = 'home' | 'hulls' | 'fit' | 'bill'; +/** A founding key pressed: commission, requisition or load. */ +export type FoundAsk = + | { + action: 'yard_commission'; + params: Omit; + label: 'COMMISSION'; + } + | { + action: 'yard_requisition'; + params: Record; + label: 'REQUISITION'; + } + | { + action: 'yard_load'; + params: { slot: number }; + label: 'LOAD'; + /** The save returns the player to the crew they are in: no question. */ + restores?: boolean; + }; + export type YardView = { screen: YardScreen; - /** Selected hull id (HULLS record, FIT, BILL). */ + /** On 'hulls': the record open, or null for the list. On 'fit' and 'bill': the hull. */ hull: string | null; + /** The hull last opened from the list: the list focuses it and turns to its page. */ + lastHull: string | null; + /** The hull the fit below belongs to; FIT OUT on any other hull starts from stock. */ + fitHull: string | null; + /** Taken: the finish id. */ finish: string | null; - /** slot key -> module id */ + /** Taken: slot key -> module id. */ picks: Record; + /** The fit's open step (0 = FINISH when the hull has finishes). */ step: number; - /** The key that has been pressed once and now reads CONFIRM. */ - confirm: string | null; + /** Shown: the option tried on the open step, or null for the one taken. */ + shown: string | null; + /** The founding action waiting on the LEAVE CREW dialog, or null. */ + leave: FoundAsk | null; }; const HOME: YardView = { screen: 'home', hull: null, + lastHull: null, + fitHull: null, finish: null, picks: {}, step: 0, - confirm: null, + shown: null, + leave: null, }; /** Survives the tab unmounting (tab switch, the CONFIRMED box). */ -const store: { view: YardView; fitSerial: number | null } = { +const store: { + view: YardView; + fitSerial: number | null; + /** The sent-key rule (2.6): the notice it was sent under, and when. */ + sent: { at: number | null; t: number } | null; +} = { view: HOME, fitSerial: null, + sent: null, }; /** Hulls whose preview pictures have been asked for this session. */ const previewed = new Set(); -export type SetView = (patch: Partial) => void; +/** How long a sent founding key stays dead when the notice doesn't change. */ +const SENT_MS = 4000; + +export type SetView = ( + patch: Partial | ((view: YardView) => Partial), +) => void; function useYardView(): [YardView, SetView] { const [view, setView] = useState(store.view); const set: SetView = (patch) => setView((prev) => { - const next = { ...prev, confirm: null, ...patch }; + const next = { + ...prev, + ...(typeof patch === 'function' ? patch(prev) : patch), + }; store.view = next; return next; }); @@ -287,146 +466,164 @@ export function usePreview(hullId: string | null) { }, [hullId]); } +export type YardGo = { + home: () => void; + hulls: () => void; + record: (hullId: string) => void; + fitOut: (hull: Hull) => void; + fit: (step?: number) => void; + bill: () => void; + back: () => void; +}; + /** Everything the screens need, worked out once per render. */ export type YardCtx = { view: YardView; set: SetView; + go: YardGo; catalog: Hull[]; + /** The catalog has arrived (it comes in static data after yard_open). */ + loaded: boolean; hull: Hull | null; + fit: ShipFit | null; + bill: ShipBill | null; own: Ownership; account: Parts | null | undefined; - /** Commissioning, requisition and loading are open (round running). */ + ledger: LedgerState; + /** The port is open: commissioning, requisition and loading can run. */ open: boolean; + /** A founding key was just sent: draw those keys dead (a courtesy; the server holds the lock). */ + sent: boolean; crewChange: string | null; + found: (ask: FoundAsk) => void; }; +function makeGo( + view: YardView, + set: SetView, + hull: Hull | null, + fit: ShipFit | null, +): YardGo { + const go: YardGo = { + home: () => set({ screen: 'home', hull: null, shown: null }), + hulls: () => + set((v) => ({ + screen: 'hulls', + hull: null, + lastHull: v.hull || v.lastHull, + shown: null, + })), + record: (hullId) => + set({ screen: 'hulls', hull: hullId, lastHull: hullId, shown: null }), + fitOut: (hull) => + set((v) => { + const keep = v.fitHull === hull.id; + const fresh = keep + ? {} + : { fitHull: hull.id, finish: null, picks: {}, step: 0 }; + return { + ...fresh, + screen: fittable(hull) ? 'fit' : 'bill', + hull: hull.id, + lastHull: hull.id, + step: 0, + shown: null, + }; + }), + fit: (step) => + set((v) => ({ screen: 'fit', step: step ?? v.step, shown: null })), + bill: () => set({ screen: 'bill', shown: null }), + back: () => { + const v = view; + if (v.screen === 'hulls') { + if (v.hull) { + set({ hull: null, lastHull: v.hull }); + } else { + go.home(); + } + } else if (v.screen === 'fit') { + set({ screen: 'hulls', shown: null }); + } else if (v.screen === 'bill') { + // The fit at its last step, or the record for a hull with nothing to fit. + if (hull && fit && fittable(hull)) { + go.fit(Math.max(0, stepsOf(fit) - 1)); + } else { + set({ screen: 'hulls', shown: null }); + } + } + }, + }; + return go; +} + // --------------------------------------------------------------------------- -// Shared bits of drawing. +// The tab row's right zone (2.3) // --------------------------------------------------------------------------- -/** A `[ LABEL ]` key in any colour class; faint and dead when disabled. */ -export function Key( - props: NavProps & { - x: number; - y: number; - label: string; - cls?: string; - right?: boolean; - disabled?: boolean; - bg?: boolean; - onClick?: () => void; - }, -) { - const { - x, - y, - label, - cls = '', - right, - disabled, - bg, - onClick, - auto, - edge, - } = props; - const text = `[ ${label} ]`; - const at = right ? x - text.length : x; - if (disabled) { - return ( - - {text} - - ); - } - const amber = cls === 'amb' || cls === 'inva'; - return ( - - {text} - - ); -} +/** Right edge of the right zone: the box's right edge, column 62. */ +const RIGHT_END = 63; +const ZONE_Y = 0.25; -/** Breadcrumb and [ BACK ] on the tab row, right-aligned. */ -function Crumbs(props: { ctx: YardCtx; screen: YardScreen }) { +function RightZone(props: { ctx: YardCtx; screen: YardScreen }) { const { ctx, screen } = props; - const { view, set, hull } = ctx; - const { cols } = useGrid(); - const seg: [string, (() => void) | null][] = [ - ['SHIPYARD', () => set({ screen: 'home', hull: null })], - [ - 'HULLS', - () => - set({ - screen: 'hulls', - hull: screen === 'hulls' ? null : view.hull, - }), - ], - ]; - if (hull && screen !== 'hulls') { - seg.push([hull.short.toUpperCase(), () => set({ screen: 'hulls' })]); - } - // A hull with no finishes and no rooms skips FIT entirely. - const fittable = !hull || !!hull.finishes.length || !!hull.slots.length; - if ((screen === 'fit' || screen === 'bill') && fittable) { - seg.push(['FIT', () => set({ screen: 'fit' })]); - } - if (screen === 'bill') { - seg.push(['BILL', null]); - } - // The tab names end near column 41; drop leading crumbs until the rest fits. - const room = cols - 1 - 42 - 12; - const width = () => seg.map((s) => s[0]).join(' / ').length; - while (seg.length > 1 && width() > room) { - seg.shift(); + const { go, hull, catalog } = ctx; + useBack(screen === 'home' ? null : go.back); + if (screen === 'home') { + return null; } - const showCrumbs = width() <= room; - const back: Record> = { - home: {}, - hulls: view.hull ? { hull: null } : { screen: 'home', hull: null }, - fit: { screen: 'hulls' }, - bill: { screen: fittable ? 'fit' : 'hulls' }, - }; - useBack(() => set(back[screen])); const out: ReactNode[] = []; - let x = cols - 1 - (showCrumbs ? width() : 0); - out.push( - set(back[screen])} - />, - ); - if (showCrumbs) { - seg.forEach(([label, go], i) => { - const last = i === seg.length - 1; + let backEnd = RIGHT_END; + if (screen === 'hulls' && hull) { + // The record: [ BACK ], three spaces, the stepper through the catalog in list order. + const at = catalog.findIndex((h) => h.id === hull.id); + const n = catalog.length; + if (n > 1 && at >= 0) { + const text = `< ${Math.min(99, at + 1)}/${Math.min(99, n)} >`; + out.push( + go.record(catalog[p - 1].id)} + />, + ); + backEnd = RIGHT_END - text.length - 3; + } + } else { + const crumbs: [string, (() => void) | null][] = []; + if (screen === 'hulls') { + crumbs.push(['HULLS', null]); + } else { + crumbs.push(['HULLS', go.hulls]); + const fitting = !!hull && fittable(hull); + if (fitting) { + crumbs.push(['FIT', screen === 'fit' ? null : () => go.fit()]); + } + crumbs.push(['BILL', screen === 'bill' ? null : go.bill]); + } + const width = crumbs.map((c) => c[0]).join(' / ').length; + let x = RIGHT_END - width; + backEnd = x - 2; + crumbs.forEach(([word, onGo], i) => { out.push( - {label} + {word} , ); - x += label.length; - if (!last) { + x += word.length; + if (i < crumbs.length - 1) { out.push( - + {' / '} , ); @@ -434,183 +631,73 @@ function Crumbs(props: { ctx: YardCtx; screen: YardScreen }) { } }); } + out.push( + // Keyed by screen: it remounts on each screen, so its first-focus claim on the bill + // registers (the purchase guard: with something due, focus never starts on COMMISSION). + , + ); return <>{out}; } // --------------------------------------------------------------------------- -// Home: NEW SHIP, REQUISITION, SAVED SHIPS. +// The catalog not here yet (3.1) // --------------------------------------------------------------------------- -function Home(props: { ctx: YardCtx }) { - const { ctx } = props; - const { data, act } = useBackend(); - const { cols, rows, narrow } = useGrid(); - const bottom = rows - 1; - const req = !!data.can_requisition; - const account = data.account || {}; - const confirmReq = ctx.view.confirm === 'req'; - const reqLine = ctx.crewChange - ? `LEAVES ${ctx.crewChange.toUpperCase()}` - : 'SURPLUS HULL'; - - const requisition = () => { - if (ctx.crewChange && !confirmReq) { - ctx.set({ confirm: 'req' }); +function Waiting(props: { empty: boolean }) { + const { rows } = useGrid(); + const [on, setOn] = useState(true); + useEffect(() => { + if (props.empty) { return; } - ctx.set({ confirm: null }); - act('yard_requisition', { leave_crew: ctx.crewChange ? 1 : 0 }); - }; - const newShip = () => ctx.set({ screen: 'hulls', hull: null }); - - const out: ReactNode[] = []; - let th = 5; - const y = TOP + 2; - if (narrow) { - // One box: NEW SHIP and the parts on account, the surplus hull below. - th = req ? 6 : 5; - out.push( - , - , - ); - const short = PART_ORDER.map( - (k) => `${k.slice(0, 3).toUpperCase()} ${account[k] || 0}`, - ).join(' '); - if (cols - 20 >= short.length) { - out.push( - - {short} - , - ); - } - if (req) { - out.push( - - {reqLine.slice(0, cols - 24)} - , - , - ); - } - } else { - const lw = req ? Math.floor(cols * 0.62) : cols; - out.push( - , - , - ); - const segs = PART_ORDER.map((k) => [ - k.toUpperCase(), - String(account[k] || 0), - ]); - const partsW = - 7 + - segs.reduce((a, [k, n]) => a + k.length + 1 + n.length, 0) + - 3 * (segs.length - 1); - let x = lw - 3 - partsW; - out.push( - - PARTS - , - ); - x += 7; - for (const [k, n] of segs) { - out.push( - - {k} - , - - {n} - , - ); - x += k.length + 1 + n.length + 3; - } - if (req) { - const rx = lw + 1; - const rw = cols - lw - 1; - out.push( - , - - {reqLine.slice(0, Math.max(0, rw - 23))} - , - , - ); - } - } - - if (data.saves) { - out.push( - , - ); - } - return <>{out}; -} - -// --------------------------------------------------------------------------- - -function Waiting() { - const { cols, rows } = useGrid(); + const id = setInterval(() => setOn((v) => !v), 530); + return () => clearInterval(id); + }, [props.empty]); + const line = props.empty ? 'NO HULLS ON THE SHELF.' : 'CONTACTING THE YARD.'; return ( - - - CONTACTING THE YARD... - - + <> + + + + {!props.empty && !!on && ( + + {' '} + + )} + + ); } +// --------------------------------------------------------------------------- +// The router +// --------------------------------------------------------------------------- + export function YardTab(props: { home: number }) { const { data, act } = useBackend(); const [view, set] = useYardView(); + const [, rerender] = useState(0); useEffect(() => { act('yard_open'); + // A dialog left open when the tab closed does not come back with it. + if (store.view.leave) { + set({ leave: null }); + } }, []); // SHIPYARD pressed again while on it: back to the yard's front page. const [home, setHome] = useState(props.home); if (home !== props.home) { setHome(props.home); - if (view.screen !== 'home') { - set(HOME); + if (view.screen !== 'home' || view.leave) { + set({ screen: 'home', hull: null, shown: null, leave: null }); } } // A commission put the player aboard: the fit was built, so forget it. A refusal keeps it. @@ -625,49 +712,113 @@ export function YardTab(props: { home: number }) { store.fitSerial = fitSerial; }, [fitSerial]); + // The sent-key rule (2.6): dead until the notice changes or SENT_MS pass. + const noticeAt = data.notice ? data.notice.at : null; + const sentLeft = store.sent ? store.sent.t + SENT_MS - Date.now() : 0; + const sent = !!store.sent && store.sent.at === noticeAt && sentLeft > 0; + useEffect(() => { + if (!sent) { + return; + } + const id = setTimeout(() => rerender((n) => n + 1), sentLeft + 20); + return () => clearTimeout(id); + }, [sent, noticeAt]); + + const send = (ask: FoundAsk, leave: boolean) => { + // The CONFIRMED box that answers this starts a long job (motion.ts). + noteFounding(); + store.sent = { at: noticeAt, t: Date.now() }; + rerender((n) => n + 1); + act(ask.action, { ...ask.params, leave_crew: leave ? 1 : 0 }); + }; + const crewChange = data.crew_change || null; + const found = (ask: FoundAsk) => { + if (sent) { + return; + } + const restores = ask.action === 'yard_load' && !!ask.restores; + if (crewChange && !restores) { + set({ leave: ask }); + return; + } + send(ask, false); + }; + + const loaded = !!data.catalog; const catalog = useMemo(() => data.catalog || [], [data.catalog]); const hull = useMemo( () => catalog.find((h) => h.id === view.hull) || null, [catalog, view.hull], ); + const own: Ownership = { owned: data.owned, free: !!data.free_ships }; + const fit = hull + ? view.fitHull === hull.id + ? fitOf(hull, view.finish, view.picks) + : stockFit(hull) + : null; + const bill = fit ? billOf(own, fit, data.account) : null; const ctx: YardCtx = { view, set, + go: makeGo(view, set, hull, fit), catalog, + loaded, hull, - own: { owned: data.owned, free: !!data.free_ships }, + fit, + bill, + own, account: data.account, + ledger: data.ledger || 'wait', open: data.phase === 'playing', - crewChange: data.crew_change || null, + sent, + crewChange, + found, }; - let screen = view.screen; - if ((screen === 'fit' || screen === 'bill') && !hull && !!data.catalog) { + if (screen !== 'home' && loaded && view.hull && !hull) { + // The hull left the shelf. screen = 'hulls'; } + // Each screen is a step further in: going on wipes forward, BACK and an earlier crumb wipe + // back, and the hull stepper turns a page. + const onRecord = screen === 'hulls' && !!hull; + useScreen( + `shipyard/${onRecord ? 'record' : screen}`, + onRecord ? 2 : { home: 0, hulls: 1, fit: 3, bill: 4 }[screen], + onRecord && hull ? hull.id : '', + onRecord && hull ? catalog.indexOf(hull) : 0, + ); let body: ReactNode; if (screen === 'home') { - body = ; - } else if (!data.catalog) { - body = ; + body = ; + } else if (!loaded || !catalog.length) { + body = ; } else if (screen === 'hulls') { body = ; } else if (screen === 'fit' && hull) { body = ; } else if (hull) { - body = ( - act('yard_commission', params)} - /> - ); + body = ; } + const leave = view.leave; return ( <> - {screen !== 'home' && } + {body} + {!!leave && !!crewChange && ( + set({ leave: null })} + onGo={() => { + // Answered, not backed out of: the box goes without the back sound. + quietDialogClose(); + set({ leave: null }); + send(leave, true); + }} + /> + )} ); } diff --git a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/audio.ts b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/audio.ts new file mode 100644 index 00000000000..3ee25b9c03e --- /dev/null +++ b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/audio.ts @@ -0,0 +1,290 @@ +/** + * Sound for the dock terminal, played in the page so a sound never costs a round trip. + * + * Web Audio: each clip is fetched from the terminal's assets and decoded once, and every play + * starts a fresh source, so plays never cut each other off or get dropped. Clips are named by + * their asset name (lobby_assets.dm), e.g. 'lt_key1.ogg'. + * + * preload(['lt_boot_seq.ogg', ...]) fetch and decode ahead of time + * play('lt_press.ogg', { gain: 0.3 }) now + * play('lt_boot_tick.ogg', { when: 0.25, rate: 1.2 }) a quarter second from now, pitched up + * + * Everything here is a quiet no-op when sound is not available: no Web Audio, a clip that did + * not arrive, or a browser that will not start audio before the player has pressed something + * (`audioState()` says which). Nothing throws. A clip that is not loaded yet is dropped and + * starts loading, so `preload` whatever a screen is about to need. + */ +import { resolveAsset } from 'tgui/assets'; + +export type PlayOpts = { + /** Seconds from now to start. Default: now. */ + when?: number; + /** Playback rate, which also shifts the pitch. Default 1. */ + rate?: number; + /** Linear volume. Default 1. */ + gain?: number; + /** Seconds into the clip to start from. Default 0. */ + offset?: number; + /** Stop earlier plays of this clip first, like restarting it. */ + solo?: boolean; +}; + +export type AudioState = 'running' | 'suspended' | 'none'; + +/** A clip is tried this many times, this far apart: asset URLs can arrive after the first render. */ +const LOAD_TRIES = 14; +const LOAD_RETRY_MS = 700; +/** A play asked for while a key or click is still starting the audio is kept this long, then dropped as stale. */ +const RESUME_GRACE_MS = 200; + +type AudioCtor = typeof AudioContext; + +let ctx: AudioContext | null | undefined; +/** Every sound passes through this on its way out. */ +let master: GainNode | null = null; +let masterGain = 1; +/** The last attempt to start a suspended context, and when it was made. */ +let waking: Promise | null = null; +let wokeAt = 0; +const buffers = new Map(); +const loads = new Map>(); +const live = new Map(); + +/** One asked-for play: the clip, when (ms on the page clock, plus any delay), and how it went. */ +export type AudioPlay = { + id: string; + at: number; + rate: number; + gain: number; + /** played, or why not: the clip was not loaded, sound is not running, or there is none. */ + did: 'played' | 'not loaded' | 'suspended' | 'no sound'; +}; + +/** The last plays asked for, oldest first: nobody can hear a test client, so the page keeps a record. */ +const LOG_MAX = 120; +const log: AudioPlay[] = []; + +function note(id: string, opts: PlayOpts, did: AudioPlay['did']) { + log.push({ + id, + at: Math.round(performance.now() + (opts.when || 0) * 1000), + rate: Math.round((opts.rate || 1) * 1000) / 1000, + gain: Math.round((opts.gain ?? 1) * 1000) / 1000, + did, + }); + if (log.length > LOG_MAX) { + log.shift(); + } +} + +/** The last plays asked for, and the page clock now (ms), for diagnostics. */ +export function audioLog(): { now: number; plays: AudioPlay[] } { + return { now: Math.round(performance.now()), plays: log.slice() }; +} + +const noop = () => undefined; + +function context(): AudioContext | null { + if (ctx !== undefined) { + return ctx; + } + ctx = null; + try { + const Ctor: AudioCtor | undefined = + window.AudioContext || + (window as unknown as { webkitAudioContext?: AudioCtor }) + .webkitAudioContext; + if (Ctor) { + ctx = new Ctor(); + master = ctx.createGain(); + master.gain.value = masterGain; + master.connect(ctx.destination); + } + } catch { + ctx = null; + master = null; + } + return ctx; +} + +/** Scales every sound, playing or still to come. 1 leaves each clip at the level it was made for. */ +export function setMasterGain(gain: number) { + masterGain = Math.max(0, gain); + if (master) { + master.gain.value = masterGain; + } +} + +/** Asks a suspended context to start. Browsers only allow it after a key or click. */ +function wake() { + const c = ctx; + if (c && c.state === 'suspended') { + wokeAt = Date.now(); + waking = c.resume().catch(noop); + } +} + +if (typeof window !== 'undefined') { + window.addEventListener('pointerdown', wake, true); + window.addEventListener('keydown', wake, true); +} + +/** running: sound plays. suspended: waiting for the player's first key or click. none: no sound. */ +export function audioState(): AudioState { + const c = context(); + if (!c || c.state === 'closed') { + return 'none'; + } + return c.state === 'running' ? 'running' : 'suspended'; +} + +function fetchClip( + id: string, + c: AudioContext, + left: number, +): Promise { + return fetch(resolveAsset(id)) + .then((response) => { + if (!response.ok) { + throw new Error(`${id}: ${response.status}`); + } + return response.arrayBuffer(); + }) + .then((bytes) => c.decodeAudioData(bytes)) + .then((buffer) => { + buffers.set(id, buffer); + return true; + }) + .catch(() => + left > 1 + ? new Promise((resolve) => + setTimeout( + () => resolve(fetchClip(id, c, left - 1)), + LOAD_RETRY_MS, + ), + ) + : false, + ); +} + +function load(id: string): Promise { + if (buffers.has(id)) { + return Promise.resolve(true); + } + const c = context(); + if (!c) { + return Promise.resolve(false); + } + let pending = loads.get(id); + if (!pending) { + pending = fetchClip(id, c, LOAD_TRIES).then((ok) => { + loads.delete(id); // a failed clip is tried again the next time it is wanted + return ok; + }); + loads.set(id, pending); + } + return pending; +} + +/** Fetches and decodes clips ahead of time. Resolves TRUE when every one is ready to play. */ +export function preload(ids: readonly string[]): Promise { + wake(); + return Promise.all(ids.map(load)).then((all) => all.every(Boolean)); +} + +export function isLoaded(id: string): boolean { + return buffers.has(id); +} + +/** Drops decoded clips that will not be played again (the start-up sounds). */ +export function unload(ids: readonly string[]) { + for (const id of ids) { + buffers.delete(id); + } +} + +function start( + c: AudioContext, + id: string, + buffer: AudioBuffer, + opts: PlayOpts, +) { + if (opts.solo) { + stop(id); + } + const source = c.createBufferSource(); + const gain = c.createGain(); + source.buffer = buffer; + source.playbackRate.value = opts.rate || 1; + gain.gain.value = opts.gain ?? 1; + source.connect(gain); + gain.connect(master || c.destination); + live.set(source, id); + source.onended = () => { + live.delete(source); + source.disconnect(); + gain.disconnect(); + }; + source.start( + c.currentTime + Math.max(0, opts.when || 0), + Math.max(0, opts.offset || 0), + ); +} + +/** + * Plays a clip. Returns TRUE when it was started or scheduled, FALSE when it was dropped + * (not loaded yet, in which case it starts loading for next time; or no sound available). + */ +export function play(id: string, opts: PlayOpts = {}): boolean { + try { + const c = context(); + if (!c) { + note(id, opts, 'no sound'); + return false; + } + const buffer = buffers.get(id); + if (!buffer) { + note(id, opts, 'not loaded'); + load(id).catch(noop); + return false; + } + if (c.state === 'running') { + start(c, id, buffer, opts); + note(id, opts, 'played'); + return true; + } + note(id, opts, 'suspended'); + // Suspended. Scheduling on a stopped clock would play the sound whenever the clock starts, + // so the sound is dropped, unless a key or click is starting the audio this very moment. + const asked = Date.now(); + if (waking && asked - wokeAt < RESUME_GRACE_MS) { + waking + .then(() => { + if (c.state === 'running' && Date.now() - asked < RESUME_GRACE_MS) { + start(c, id, buffer, opts); + } + }) + .catch(noop); + } + return false; + } catch { + return false; + } +} + +/** Stops every sound still playing or scheduled; with an id, only that clip. */ +export function stop(id?: string) { + for (const [source, name] of Array.from(live)) { + if (id !== undefined && name !== id) { + continue; + } + live.delete(source); + try { + source.onended = null; + source.stop(); + source.disconnect(); + } catch { + // Already stopped. + } + } +} diff --git a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/emblemDraw.ts b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/emblemDraw.ts new file mode 100644 index 00000000000..ace5b979905 --- /dev/null +++ b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/emblemDraw.ts @@ -0,0 +1,301 @@ +/** + * The Voidcrew symbol, drawn pixel by pixel into a canvas: a two-tone V through a black disc + * with a dithered glow, an orbit ring that passes behind the disc at the top and in front at + * the bottom, a moon on the ring and a glint. + * + * Every pixel is set whole (no antialiasing). Show the canvas scaled by a whole number of + * device pixels with `image-rendering: pixelated`; never scale it by a fraction. + * + * Coordinates: the design is about 90 units wide (the ring), centred on the canvas and scaled + * by `k`. The start-up rings (`hud`) are fixed at radius 76 to 90 canvas pixels, so they need a + * canvas of at least 190 px and are not scaled by `k`. + */ + +export type EmblemOpts = { + /** Seconds. Steps the glint and the start-up rings; quantise it to the frame rate you draw at. */ + t: number; + /** Design scale inside the canvas. 1.45 fills a 190 px canvas (start-up), 0.62 fits 64 px. */ + k?: number; + /** 0 to 1: the disc, glow and ring growing in. 1 for the finished symbol. */ + grow: number; + /** The V's turn about its vertical axis, in radians. 0 faces the viewer. */ + yaw: number; + /** Draw the V. */ + v: boolean; + /** Where the highlight sits on the orbit ring, in radians. Advance it to make the ring turn. */ + ring: number; + /** Start-up rings: 0 off, 0 to 1 the three arcs sweeping in, 1 or more fully drawn. */ + hud: number; + /** Kept so old call sites read the same. Only the eclipse (1) exists. */ + variant?: 1; +}; + +type Rgb = readonly [number, number, number]; + +const hex = (h: string): Rgb => [ + parseInt(h.slice(1, 3), 16), + parseInt(h.slice(3, 5), 16), + parseInt(h.slice(5, 7), 16), +]; + +const C = { + void: hex('#05010b'), + ink: hex('#12071f'), + p0: hex('#2a0f5c'), + p1: hex('#5b2bc0'), + p2: hex('#8e5cf0'), + p3: hex('#b48aff'), + p4: hex('#dfc4ff'), + w: hex('#ffffff'), + m0: hex('#7a2a8c'), + m1: hex('#c044b0'), + m2: hex('#ff66d6'), + m3: hex('#ffb0ee'), +} as const; + +const BAYER = [ + [0, 8, 2, 10], + [12, 4, 14, 6], + [3, 11, 1, 9], + [15, 7, 13, 5], +]; +const TAU = Math.PI * 2; +/** Light direction for the disc rim and the glow (from the upper left). */ +const LX = -0.6; +const LY = -0.8; +const RING_TILT = -0.32; +const RING_STEPS = 1440; + +/** Which facet of the V a design point is in: 0 outside, 1 left, 2 right. */ +function inV(x: number, y: number): 0 | 1 | 2 { + if (y < -30 || y > 32) { + return 0; + } + const ax = Math.abs(x); + const outer = (22 * (32 - y)) / 62; + const inner = (10 * (4 - y)) / 34; + if (ax > outer) { + return 0; + } + if (y < 4 && ax < inner) { + return 0; + } + return x <= 0 ? 1 : 2; +} + +const tone = (b: number): Rgb => + b > 0.8 ? C.w : b > 0.55 ? C.p4 : b > 0.3 ? C.p3 : C.p2; + +/** One pixel buffer per canvas, reused every frame. */ +const frames = new WeakMap(); + +/** Draws one frame of the symbol, replacing whatever the canvas held. Pixels it does not set are clear. */ +export function renderEmblem(canvas: HTMLCanvasElement, o: EmblemOpts): void { + const W = canvas.width; + const H = canvas.height; + const ctx = canvas.getContext('2d'); + if (!ctx || W <= 0 || H <= 0) { + return; + } + let img = frames.get(canvas); + if (!img || img.width !== W || img.height !== H) { + img = ctx.createImageData(W, H); + frames.set(canvas, img); + } else { + img.data.fill(0); + } + const d = img.data; + const K = o.k || 1; + const cx = W / 2; + const cy = H / 2 + 2 * K; + const { t, grow } = o; + + const put = (fx: number, fy: number, c: Rgb) => { + const x = Math.floor(fx); + const y = Math.floor(fy); + if (x < 0 || y < 0 || x >= W || y >= H) { + return; + } + const i = (y * W + x) * 4; + d[i] = c[0]; + d[i + 1] = c[1]; + d[i + 2] = c[2]; + d[i + 3] = 255; + }; + const blob = (x: number, y: number, c: Rgb, n: number) => { + for (let a = 0; a < n; a++) { + for (let b = 0; b < n; b++) { + put(x + a - n / 2 + 0.5, y + b - n / 2 + 0.5, c); + } + } + }; + + const R = 26 * grow; + + // Glow around the disc, dithered. + if (grow > 0.05) { + for (let py = 0; py < H; py++) { + for (let px = 0; px < W; px++) { + const x = (px + 0.5 - cx) / K; + const y = (py + 0.5 - cy) / K; + const r = Math.hypot(x, y); + const dd = r - R; + if (dd <= 0 || dd > 11) { + continue; + } + const light = Math.max(0, (x * LX + y * LY) / r); + const v = (1 - dd / 11) ** 1.6 * (0.45 + 0.75 * light); + const th = (BAYER[py & 3][px & 3] + 0.5) / 16; + if (v > th) { + put(px, py, v > th + 0.45 ? C.p3 : v > th + 0.2 ? C.p2 : C.p1); + } + } + } + } + + // Orbit ring: the far half first, the near half after the disc and the V. + const a = 43 * grow; + const b = a * 0.27; + const ct = Math.cos(RING_TILT); + const st = Math.sin(RING_TILT); + const ring = (front: boolean) => { + if (grow < 0.3) { + return; + } + for (let k = 0; k < RING_STEPS; k++) { + const th = (k / RING_STEPS) * TAU; + if (Math.sin(th) > 0 !== front) { + continue; + } + const hl = Math.cos(th - o.ring); + let col: Rgb; + if (front) { + col = hl > 0.92 ? C.w : hl > 0.6 ? C.m3 : hl > -0.2 ? C.m2 : C.m1; + } else { + col = hl > 0.8 ? C.m2 : hl > 0 ? C.m1 : C.m0; + } + for (const rr of [a, a - 0.7, a - 1.4]) { + const ex = rr * Math.cos(th); + const ey = rr * 0.27 * Math.sin(th); + put(cx + K * (ex * ct - ey * st), cy + K * (ex * st + ey * ct), col); + } + } + }; + ring(false); + + // Disc, then the V over it with a dark outline. + const sx = Math.cos(o.yaw); + const sa = Math.max(Math.abs(sx), 0.07); + const e = 1.2 / K; + const vAt = (x: number, y: number) => inV(x / sa, y); + for (let py = 0; py < H; py++) { + for (let px = 0; px < W; px++) { + const x = (px + 0.5 - cx) / K; + const y = (py + 0.5 - cy) / K; + const r = Math.hypot(x, y); + if (r < R) { + const l = (x * LX + y * LY) / (r || 1); + if (r > R - 2) { + put( + px, + py, + l > 0.55 ? C.w : l > 0.1 ? C.p4 : l > -0.45 ? C.p2 : C.p1, + ); + } else if (r > R - 3 && l > 0.3) { + put(px, py, C.p0); + } else { + put(px, py, C.void); + } + } + if (!o.v) { + continue; + } + const f = vAt(x, y); + if (f) { + // The left facet catches the light head on; the right one never goes fully white. + const lit = f === 1 ? 0.5 + 0.5 * sx : 0.5 - 0.5 * sx; + put( + px, + py, + tone(lit) === C.w && f === 2 + ? C.p4 + : tone(f === 1 ? lit : 0.32 - 0.32 * sx + 0.1), + ); + } else if ( + vAt(x - e, y) || + vAt(x + e, y) || + vAt(x, y - e) || + vAt(x, y + e) + ) { + put(px, py, C.ink); + } + } + } + ring(true); + + // Moon on the ring, hidden while it is behind the disc. + if (grow > 0.6) { + const th = o.ring * 0.5 + 1; + const ex = a * Math.cos(th); + const ey = b * Math.sin(th); + const rx = ex * ct - ey * st; + const ry = ex * st + ey * ct; + if (Math.sin(th) > 0 || Math.hypot(rx, ry) > R + 2) { + const mx = cx + K * rx; + const my = cy + K * ry; + blob(mx, my, C.m3, 3); + put(mx, my, C.w); + } + } + + // Glint, upper right. + if (o.v && grow > 0.9) { + const gx = cx + 31 * K; + const gy = cy - 31 * K; + const n = 2 + (Math.floor(t * 3) % 3); + for (let k = 1; k <= n; k++) { + const c = k < n ? C.p4 : C.p2; + put(gx + k, gy, c); + put(gx - k, gy, c); + put(gx, gy + k, c); + put(gx, gy - k, c); + } + put(gx, gy, C.w); + } + + // Start-up rings: a stepping tick ring with four markers, and three arcs turning the other way. + if (o.hud > 0) { + const rot = Math.floor(t * 8) * (TAU / 96); + for (let i = 0; i < 60; i++) { + if (i % 15 === 0) { + continue; + } + const an = (i / 60) * TAU + rot; + const big = i % 5 === 0; + for (let rr = big ? 84 : 87; rr <= 90; rr += 0.5) { + blob( + cx + rr * Math.cos(an), + cy + rr * Math.sin(an), + big ? C.p4 : C.p2, + big ? 2 : 1, + ); + } + } + for (let i = 0; i < 4; i++) { + const an = (i / 4) * TAU; + blob(cx + 88 * Math.cos(an + rot), cy + 88 * Math.sin(an + rot), C.w, 5); + } + const rot2 = -Math.floor(t * 12) * (TAU / 120); + const len = Math.min(1, o.hud) * 1.25; + for (let j = 0; j < 3; j++) { + for (let k = 0; k < 400; k++) { + const an = rot2 + (j * TAU) / 3 + (k / 400) * len; + for (const rr of [76, 76.7, 77.4]) { + put(cx + rr * Math.cos(an), cy + rr * Math.sin(an), C.m2); + } + } + } + } + + ctx.putImageData(img, 0, 0); +} diff --git a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/index.tsx b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/index.tsx index 946b49f5506..ec5cd2a24e2 100644 --- a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/index.tsx +++ b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/index.tsx @@ -8,20 +8,40 @@ * * UI-local state (tab, selections, pages, fits) lives in React; only actions round-trip. */ -import { useEffect, useMemo, useState } from 'react'; +import { Fragment, useEffect, useMemo, useRef, useState } from 'react'; import { resolveAsset } from 'tgui/assets'; import { useBackend } from 'tgui/backend'; -import { BEZEL_EXTRA_CSS, Bezel } from './Bezel'; +import { Bezel } from './Bezel'; +import { Boot } from './Boot'; import { CharacterTab } from './CharacterTab'; import { CrewsTab } from './CrewsTab'; -import { Header, TABS } from './Header'; +import { HeaderBand, TABS, TabRow } from './Header'; import { HousingTab } from './HousingTab'; -import { computeLayout, START_KEY_W } from './layout'; +import { computeLayout, regions } from './layout'; +import { KeyBar, MenuPopup, SideMenu } from './Menu'; +import { + backNextScreen, + MOTION_CSS, + quietNextScreen, + ScreenWipe, + setSfxTune, + usePauseWhenHidden, +} from './motion'; import { Confirmed, NoticeLine } from './Notice'; import { NAV_CSS, NavProvider } from './nav'; -import { type Grid, GridContext, TERM_CSS } from './term'; +import { ObserveConfirm } from './ObserveConfirm'; +import { Settings } from './Settings'; +import { + type Grid, + GridContext, + Region, + STARS, + TERM_CSS, + useBoxInside, +} from './term'; import type { LobbyData, TabId } from './types'; +import { Welcome } from './Welcome'; import { YardTab } from './YardTab'; const FONT = 'VCR'; @@ -102,23 +122,22 @@ function useTerminalFont() { return advance; } +/** The cover a screen change draws over the inside of the main box (motion.ts). */ +function MainWipe() { + return ; +} + export function LobbyTerminal() { const { data, act } = useBackend(); + const root = usePauseWhenHidden(); + // Stand-in sound clips play at the rate and volume the server lists for them. + const tune = data.sfx_tune; + useEffect(() => setSfxTune(tune), [tune]); const pane = usePaneSize(); const advance = useTerminalFont(); - const startKey = - !!data.localhost_admin && - (data.phase === 'loading' || data.phase === 'pregame'); const layout = useMemo( - () => - computeLayout( - pane.w, - pane.h, - pane.dpr, - advance, - startKey ? START_KEY_W : 0, - ), - [pane.w, pane.h, pane.dpr, advance, startKey], + () => computeLayout(pane.w, pane.h, pane.dpr, advance), + [pane.w, pane.h, pane.dpr, advance], ); const grid: Grid = useMemo( () => ({ @@ -127,23 +146,95 @@ export function LobbyTerminal() { cw: layout.cw, ch: layout.ch, s: layout.s, - narrow: layout.narrow, + lw: layout.lw, + mode: layout.mode, }), [layout], ); + const reg = regions(layout.mode, layout.rows); const [tab, setTab] = useState('crews'); + /** The tab that was open before CHARACTER or SETTINGS, for Escape at their top level. */ + const [prevTab, setPrevTab] = useState('crews'); /** Bumped when SHIPYARD is pressed while already on it. */ const [yardHome, setYardHome] = useState(0); - /** Bumped when CHARACTER (tab or bezel key) is pressed while already on it: back to the file view. */ + /** Bumped when CHARACTER is pressed while already on it: back to the file view. */ const [charHome, setCharHome] = useState(0); + /** Bumped when SETTINGS is pressed while already on it: back to its top state. */ + const [settingsHome, setSettingsHome] = useState(0); + const [observeOpen, setObserveOpen] = useState(false); + const [menuOpen, setMenuOpen] = useState(false); + /** CHARACTER was opened by the shell before the round, not by the player. */ + const [autoChar, setAutoChar] = useState(false); + const autoTried = useRef(false); + + // CHARACTER and SETTINGS are screens the menu opens, not tabs: Escape at their top level goes + // back to the tab that was open before either. + const isScreen = (id: TabId) => id === 'character' || id === 'settings'; + const openScreen = (next: TabId) => { + if (isScreen(next) && !isScreen(tab)) { + setPrevTab(tab); + } + setTab(next); + }; + const request = data.tab_request; + /** Counts screens the server picked; the tab row mounts again on each so its claim runs. */ + const [served, setServed] = useState(0); useEffect(() => { if (request) { - setTab(request.tab); + // The server picked the screen: the CHARACTER file no longer opens by itself. + autoTried.current = true; + openScreen(request.tab); + setServed((n) => n + 1); } }, [request?.serial]); + // The player's first key press or click after LOGIN. + const bootRef = useRef(data.boot); + bootRef.current = data.boot; + const [acted, setActed] = useState(false); + useEffect(() => { + if (acted) { + return; + } + const onAct = () => { + if (!bootRef.current) { + setActed(true); + } + }; + window.addEventListener('keydown', onAct, true); + window.addEventListener('click', onAct, true); + return () => { + window.removeEventListener('keydown', onAct, true); + window.removeEventListener('click', onAct, true); + }; + }, [acted]); + + // Before the round the main area opens on the CHARACTER file, once per page load, until the + // player does something. When the round starts and they still have not, CREWS. + const before = data.phase === 'loading' || data.phase === 'pregame'; + useEffect(() => { + if (autoTried.current || acted || !before || !data.prefs_ready) { + return; + } + autoTried.current = true; + if (tab !== 'character') { + openScreen('character'); + setAutoChar(true); + } + }, [acted, before, data.prefs_ready]); + useEffect(() => { + if (data.phase === 'playing' && autoChar && !acted && tab === 'character') { + // The shell's own move: no wipe, no sound. + quietNextScreen(); + setTab('crews'); + } + if (data.phase === 'playing' || acted) { + setAutoChar(false); + } + }, [data.phase, acted]); + // Report display metrics once the font settles (Windows scaling, pane size), for tuning. useEffect(() => { const id = setTimeout( @@ -155,6 +246,7 @@ export function LobbyTerminal() { s: layout.s, cols: layout.cols, rows: layout.rows, + mode: layout.mode, }), 3000, ); @@ -164,6 +256,16 @@ export function LobbyTerminal() { const notice = data.notice; const confirmed = !!notice && notice.kind === 'ok'; + // The first-time WELCOME box, once the start-up screen is done. Gone here at once when + // answered or put off; the server stops sending welcome too. + const [welcomeGone, setWelcomeGone] = useState(false); + const welcomeOpen = + !!data.welcome && !data.boot && !welcomeGone && !confirmed; + const welcomeLater = () => { + setWelcomeGone(true); + act('welcome_later'); + }; + const switchTab = (next: TabId) => { if (next === tab && next === 'shipyard') { setYardHome(yardHome + 1); @@ -171,38 +273,93 @@ export function LobbyTerminal() { if (next === tab && next === 'character') { setCharHome(charHome + 1); } - setTab(next); - if (confirmed) { - act('dismiss'); + if (next === tab && next === 'settings') { + setSettingsHome(settingsHome + 1); + } + openScreen(next); + setObserveOpen(false); + setMenuOpen(false); + if (welcomeOpen) { + welcomeLater(); + } + if (confirmed && notice) { + act('dismiss', { at: notice.at }); } }; const { s } = layout; - const scan = Math.max(2, Math.round(s)); let body; if (confirmed) { body = ; } else if (tab === 'crews') { - body = ; + body = ; } else if (tab === 'shipyard') { body = ; } else if (tab === 'character') { - body = ; + // The tab sends char_open (with auto: 1 for the shell's pre-round open) once, on mount, and + // handles Escape at every level; at the file view it calls onLeave. + body = ( + { + backNextScreen(); + switchTab(prevTab); + }} + /> + ); + } else if (tab === 'settings') { + // The screen sends settings_open on mount and settings_close when it goes; Escape at its top + // level calls onLeave. + body = ( + { + backNextScreen(); + switchTab(prevTab); + }} + /> + ); } else { body = ; } + // When the start-up screen ends, the first-focus owners mount again so their claim runs. + // The CHARACTER screen is left alone: mounting it again would ask for its file again. + const bootKey = data.boot ? 'boot' : 'live'; + // The open tab's first-focus claim: in setup and ended it wins (design 01 section 9); on + // HOUSING it is the stand-in when no key is live (design 02 section 4.4), so a live key's + // claim (1) and READY's (9) beat it. + const tabClaim = + data.phase === 'setup' || data.phase === 'ended' + ? 9 + : tab === 'housing' + ? 0 + : undefined; + const menu = { + charOpen: tab === 'character' && !confirmed, + onCharacter: () => switchTab('character'), + settingsOpen: tab === 'settings' && !confirmed, + onSettings: () => switchTab('settings'), + onObserve: () => { + setMenuOpen(false); + setObserveOpen(true); + if (welcomeOpen) { + welcomeLater(); + } + }, + }; return (
- + { const next = TABS[n - 1]; @@ -216,12 +373,23 @@ export function LobbyTerminal() { switchTab(next[0]); }} > - switchTab('character')} - > +
+
+
+ {STARS.map(([left, top, opacity], i) => ( + + ))} +
-
- {body} - + + + + {!!reg.menu && ( + + + + )} + + + + {body} + + + + {!!observeOpen && !confirmed && ( + setObserveOpen(false)} /> + )} + {!!reg.bar && !!menuOpen && ( + setMenuOpen(false)} /> + )} + {!!welcomeOpen && ( + setWelcomeGone(true)} + /> + )} + + {!!reg.bar && ( + + { + setObserveOpen(false); + if (welcomeOpen) { + welcomeLater(); + } + setMenuOpen(!menuOpen); + }} + /> + + )}
-
-
+
+
diff --git a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/layout.ts b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/layout.ts index 7354a3f5b2a..a13178b38bc 100644 --- a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/layout.ts +++ b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/layout.ts @@ -1,49 +1,82 @@ /** - * Terminal geometry: bezel scale, the screen rect and the text grid, from the pane size. + * Terminal geometry: bezel scale, the glass rect and the text grid, from the pane size. * * Bezel: integer pixel-art scale s = clamp(min(floor(H / 360), floor(W / 472)), 1, 4), * snapped to whole device pixels so Windows display scaling doesn't blur the art. - * Grid: font size aims at about 110 columns, independent of s. + * + * Grid: a fixed column count. Side mode is exactly 84 columns (a 19-column menu, a 2-column + * gap and the 63-column main area); bar mode is exactly 63. The text size is the largest that + * fits those columns plus one margin cell each side, so only the row count changes with the + * pane. Text sizes are fractional; the cell height is whole pixels. */ -/** 1x pixel numbers of the bezel (bezel.json). */ +/** 1x pixel numbers of the bezel (bezel.json). The frame covers the whole pane. */ export const BEZEL = { baseHeight: 360, minWidth: 472, screenTop: 15, screenSide: 13, - screenBottom: 52, - deck: 49, + screenBottom: 3, } as const; -/** 1x width the localhost START key adds to the deck (52 px key plus its 4 px gap). */ -export const START_KEY_W = 56; +/** Canvas columns in side-menu mode. */ +export const SIDE_COLS = 84; +/** The main area in both modes; the whole canvas in bar mode. */ +export const MAIN_COLS = 63; +/** The side menu; then a 2-column gap; then the main area at column 21. */ +export const MENU_COLS = 19; +export const MAIN_X = MENU_COLS + 2; +export const SIDE_MIN_ROWS = 28; +export const BAR_MIN_ROWS = 22; +export const MAX_ROWS = 48; +export const SIDE_MIN_FS = 14; +export const BAR_MIN_FS = 9; +export const MAX_FS = 40; -/** Below this many columns or rows, tabs use their narrow (one panel at a time) layout. */ -export const NARROW_COLS = 96; -export const NARROW_ROWS = 22; +export type Mode = 'side' | 'bar'; export type Layout = { /** CSS pixels per art pixel (a whole number of device pixels). */ s: number; dpr: number; - /** Screen rect in CSS px, relative to the pane. */ + /** Glass rect in CSS px, relative to the pane. */ screen: { x: number; y: number; w: number; h: number }; + /** Font size in CSS px (fractional). */ fs: number; - /** Cell size in CSS px. */ + /** Cell size in CSS px: cw fractional, ch whole. */ cw: number; ch: number; cols: number; rows: number; - /** Grid origin inside the screen. */ + /** Canvas origin inside the glass. */ ox: number; oy: number; - narrow: boolean; + mode: Mode; + /** Line weight in px: every border and rule. */ + lw: number; }; +/** A rect in canvas cells. */ +export type CellRect = { x: number; y: number; w: number; h: number }; + const clamp = (v: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, v)); +function fitGrid( + sw: number, + sh: number, + advance: number, + cols: number, + minRows: number, +) { + const chMax = Math.max(1, Math.floor(sh / (minRows + 1))); + const fs = + Math.floor( + Math.min(sw / ((cols + 2) * advance), chMax / 1.2, MAX_FS) * 100, + ) / 100; + return { fs, chMax }; +} + /** * @param advance width of one character at 1px font size (measured from the real font). */ @@ -52,14 +85,12 @@ export function computeLayout( paneH: number, dpr: number, advance: number, - /** Extra 1x deck width (the START key), so the deck still fits the pane. */ - extraW = 0, ): Layout { const ratio = dpr > 0 ? dpr : 1; const sCss = clamp( Math.min( Math.floor(paneH / BEZEL.baseHeight), - Math.floor(paneW / (BEZEL.minWidth + extraW)), + Math.floor(paneW / BEZEL.minWidth), ), 1, 4, @@ -72,11 +103,20 @@ export function computeLayout( const sw = Math.max(0, paneW - 2 * sx); const sh = Math.max(0, paneH - sy - BEZEL.screenBottom * s); - const fs = clamp(Math.floor(sw / (0.6 * 110)), 11, 24); + let mode: Mode = 'side'; + let cols = SIDE_COLS; + let { fs, chMax } = fitGrid(sw, sh, advance, SIDE_COLS, SIDE_MIN_ROWS); + if (fs < SIDE_MIN_FS) { + mode = 'bar'; + cols = MAIN_COLS; + ({ fs, chMax } = fitGrid(sw, sh, advance, MAIN_COLS, BAR_MIN_ROWS)); + fs = Math.max(BAR_MIN_FS, fs); + } + const ch = Math.max(1, Math.min(chMax, Math.round(fs * 1.2))); const cw = fs * advance; - const ch = Math.round(fs * 1.2); - const cols = Math.max(20, Math.floor((sw - 2 * cw) / cw)); - const rows = Math.max(8, Math.floor((sh - ch) / ch)); + const minRows = mode === 'side' ? SIDE_MIN_ROWS : BAR_MIN_ROWS; + // Below the supported minimum the canvas keeps its minimum rows and clips. + const rows = clamp(Math.floor(sh / ch) - 1, minRows, MAX_ROWS); const ox = Math.floor((sw - cols * cw) / 2); const oy = Math.floor((sh - rows * ch) / 2); return { @@ -90,6 +130,25 @@ export function computeLayout( rows, ox, oy, - narrow: cols < NARROW_COLS || rows < NARROW_ROWS, + mode, + lw: Math.round(s) + 1, + }; +} + +/** Canvas regions (cells) for a layout: header band, side menu, main area, key bar. */ +export function regions(mode: Mode, rows: number) { + if (mode === 'side') { + return { + header: { x: 0, y: 0, w: SIDE_COLS, h: 1.5 } as CellRect, + menu: { x: 0, y: 2, w: MENU_COLS, h: rows - 2 } as CellRect | null, + main: { x: MAIN_X, y: 2, w: MAIN_COLS, h: rows - 2 } as CellRect, + bar: null as CellRect | null, + }; + } + return { + header: { x: 0, y: 0, w: MAIN_COLS, h: 1.5 } as CellRect, + menu: null as CellRect | null, + main: { x: 0, y: 2, w: MAIN_COLS, h: rows - 4 } as CellRect, + bar: { x: 0, y: rows - 1.5, w: MAIN_COLS, h: 1.5 } as CellRect | null, }; } diff --git a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/motion.ts b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/motion.ts new file mode 100644 index 00000000000..ae98f7f8e39 --- /dev/null +++ b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/motion.ts @@ -0,0 +1,750 @@ +/** + * Motion and sound for the dock terminal. + * + * Every animation is stepped, 80 to 240 ms long, and moves only opacity, a transform or a + * cover. Nothing waits for one: the new state is mounted and focusable at once and the + * animation only reveals it. No cover can be left on the screen: each one ends outside its + * clip, and a timer takes it away whether or not the animation ran. While the page is hidden + * nothing starts and nothing sounds. + * + * sfx('wipe') a named sound at its level; a no-op when it may not play + * pressFx() / sfxInstead('slot') the key-press sound, or the sound a press has instead + * a cover over a px rect that plays when k changes + * a white bar over a px rect when k changes + * const ref = usePulse(count) flashes ref's element white when count changes + * useScreen('crews/record', 1, ref) says which screen the main box shows; ScreenWipe covers the change + * useBlink(on, 500) TRUE and FALSE in turn while on + */ +import { + type CSSProperties, + createElement, + useEffect, + useLayoutEffect, + useRef, + useState, +} from 'react'; + +import { play, preload } from './audio'; + +// --------------------------------------------------------------------------- +// Sound +// --------------------------------------------------------------------------- + +/** + * The start-up clips are baked at their approved levels and play at a master gain of 1. Every + * other sound of the terminal is scaled by this instead, so the lobby sits under them. + */ +const LOBBY_GAIN = 0.8; + +/** The start-up screen's eight keystroke rates, used in turn for typing. */ +const TYPE_RATES = [1, 0.97, 1.04, 0.99, 1.02, 0.96, 1.03, 1]; + +type Sound = { + /** Asset names (lobby_assets.dm); several are played in turn. */ + ids: string[]; + gain: number; + rate?: number; + /** Rates used in turn. */ + rates?: number[]; + /** At most one play per this many ms. */ + gap?: number; + /** Restarts the clip instead of layering it. */ + solo?: boolean; +}; + +const SOUNDS = { + /** The focus moves. */ + move: { + ids: ['lt_key1.ogg', 'lt_key2.ogg', 'lt_key3.ogg'], + gain: 0.22, + gap: 55, + solo: true, + }, + /** A key, slab or tab is pressed. */ + press: { ids: ['lt_press.ogg'], gain: 0.3, solo: true }, + /** A screen opens; `back` is the same clip slowed. */ + wipe: { ids: ['lt_wipe.ogg'], gain: 0.3 }, + back: { ids: ['lt_wipe.ogg'], gain: 0.3, rate: 0.85 }, + /** A page turns, a stepper steps. */ + page: { ids: ['lt_boot_tick.ogg'], gain: 0.5 }, + ready_on: { ids: ['lt_ready_on.ogg'], gain: 0.5 }, + ready_off: { ids: ['lt_ready_off.ogg'], gain: 0.45 }, + /** The departure clock's last seconds. */ + clock: { ids: ['lt_boot_tick.ogg'], gain: 0.35 }, + /** The CONFIRMED box. */ + stamp: { ids: ['lt_stamp.ogg'], gain: 0.6 }, + /** A long job starts under STAND BY. */ + working: { ids: ['lt_working.ogg'], gain: 0.25 }, + warn: { ids: ['lt_warn.ogg'], gain: 0.45 }, + bad: { ids: ['lt_bad.ogg'], gain: 0.5 }, + /** Something was accepted: a code, an application, a ping, a name, a trait. */ + ok: { ids: ['lt_ok.ogg'], gain: 0.4 }, + /** The place in line changes. */ + queue: { ids: ['lt_key1.ogg'], gain: 0.3 }, + /** A character typed in a field. */ + type: { ids: ['lt_boot_key.ogg'], gain: 0.35, gap: 30, rates: TYPE_RATES }, + /** An option is fitted in the shipyard. */ + slot: { ids: ['lt_slot.ogg'], gain: 0.4 }, + /** The character picture turns. */ + turn: { ids: ['lt_turn.ogg'], gain: 0.35 }, +} satisfies Record; + +export type SfxName = keyof typeof SOUNDS; + +export type SfxOpts = { + /** Multiplies the sound's own rate. */ + rate?: number; + /** Seconds from now. */ + when?: number; + /** + * Only when the player pressed a key or clicked a moment ago: for sounds that answer an + * action but are set off by the server's reply, so a change made elsewhere stays silent. + */ + own?: boolean; +}; + +/** Stand-in clips: asset name -> [rate, gain scale], sent by the server with the clip list. */ +let tune: Record = {}; +/** The start-up screen is up: it plays its own sounds and the terminal under it stays silent. */ +let muted = false; +const lastPlayed: Partial> = {}; +const turns: Partial> = {}; +/** When the player last pressed a key or clicked. */ +let actedAt = 0; +/** How long after a key or click a sound marked `own` still counts as its answer. */ +const OWN_WINDOW = 4000; + +const hidden = () => typeof document !== 'undefined' && document.hidden; + +/** Notes a key press or click (nav.tsx calls it). */ +export function noteAction() { + actedAt = Date.now(); +} + +/** Silences the terminal's sounds while something drawn over it owns the screen. */ +export function muteSfx(on: boolean) { + muted = on; +} + +/** Playback tuning for clips that are stand-ins (ShellStatic.sfx_tune). */ +export function setSfxTune(next: Record | undefined) { + tune = next || {}; +} + +/** Fetches and decodes every sound of the terminal. Safe to call again. */ +export function preloadSfx() { + const ids = new Set(); + for (const sound of Object.values(SOUNDS) as Sound[]) { + for (const id of sound.ids) { + ids.add(id); + } + } + preload(Array.from(ids)).catch(() => undefined); +} + +/** Plays a named sound. Returns TRUE when it was started. Never throws. */ +export function sfx(name: SfxName, opts: SfxOpts = {}): boolean { + try { + if (muted || hidden()) { + return false; + } + const now = Date.now(); + if (opts.own && now - actedAt > OWN_WINDOW) { + return false; + } + const sound: Sound = SOUNDS[name]; + if (sound.gap && now - (lastPlayed[name] || 0) < sound.gap) { + return false; + } + lastPlayed[name] = now; + const turn = turns[name] || 0; + turns[name] = turn + 1; + const id = sound.ids[turn % sound.ids.length]; + const [tuneRate, tuneGain] = tune[id] || [1, 1]; + const rate = + (sound.rate || 1) * + (sound.rates ? sound.rates[turn % sound.rates.length] : 1) * + (opts.rate || 1) * + (tuneRate || 1); + return play(id, { + gain: sound.gain * LOBBY_GAIN * (tuneGain || 1), + rate, + when: opts.when, + solo: sound.solo, + }); + } catch { + return false; + } +} + +let pressQueued = false; +let pressTaken = false; + +/** + * The key-press sound, for a press about to be handled. It plays just after the handler has + * run, so a handler with a sound of its own can take its place (sfxInstead). + */ +export function pressFx() { + if (pressQueued) { + return; + } + pressQueued = true; + pressTaken = false; + setTimeout(() => { + pressQueued = false; + if (!pressTaken) { + sfx('press'); + } + }, 0); +} + +/** Plays a sound in place of the key-press sound of the press being handled. */ +export function sfxInstead(name: SfxName, opts?: SfxOpts) { + pressTaken = true; + sfx(name, opts); +} + +/** Drops the key-press sound of the press being handled (it did nothing). */ +export function noPressFx() { + pressTaken = true; +} + +const PRESS_MS = 80; + +/** The shape flashes white for 80 ms. Set on the element itself, so a re-render never cuts it. */ +export function pressFlash(el: Element | null | undefined) { + if (!el || hidden()) { + return; + } + try { + el.setAttribute('data-press', ''); + setTimeout(() => el.removeAttribute('data-press'), PRESS_MS); + } catch { + // An element that went away mid-press has nothing to flash. + } +} + +// --------------------------------------------------------------------------- +// A long job (commission, requisition, load) sent just now +// --------------------------------------------------------------------------- + +let foundingAt = 0; + +/** A founding key was sent: the CONFIRMED box that answers it starts a long job. */ +export function noteFounding() { + foundingAt = Date.now(); +} + +/** TRUE when a founding key was sent in the last few seconds. */ +export function foundingSent() { + return Date.now() - foundingAt < 15000; +} + +// --------------------------------------------------------------------------- +// Triggers +// --------------------------------------------------------------------------- + +type Run = { serial: number; back: boolean }; + +/** + * A run counter that starts when `k` changes (and on mount with `first`) and ends by timer + * `ms` later. Starting happens before the browser paints, so a cover is up in the same frame + * as what it covers. `n` orders the values: a lower one than before runs as `back`. + */ +function useRun( + k: unknown, + n: number | undefined, + ms: number, + first: boolean | undefined, + onStart?: (back: boolean) => void, +): Run | null { + const [run, setRun] = useState(null); + const prev = useRef<{ k: unknown; n: number | undefined } | null>(null); + const serial = useRef(0); + const timer = useRef | null>(null); + const started = useRef(onStart); + started.current = onStart; + useLayoutEffect(() => { + const was = prev.current; + prev.current = { k, n }; + if (was ? Object.is(was.k, k) : !first) { + return; + } + if (hidden()) { + return; + } + const order = typeof n === 'number' ? n : typeof k === 'number' ? k : null; + const wasOrder = !was + ? null + : typeof was.n === 'number' + ? was.n + : typeof was.k === 'number' + ? was.k + : null; + const back = order !== null && wasOrder !== null && order < wasOrder; + serial.current += 1; + setRun({ serial: serial.current, back }); + if (timer.current) { + clearTimeout(timer.current); + } + timer.current = setTimeout(() => { + timer.current = null; + setRun(null); + }, ms + 50); + started.current?.(back); + }, [k]); + useEffect( + () => () => { + if (timer.current) { + clearTimeout(timer.current); + } + }, + [], + ); + return run; +} + +// --------------------------------------------------------------------------- +// The wipe +// --------------------------------------------------------------------------- + +export type WipeKind = 'screen' | 'page' | 'slot' | 'draw'; + +/** Duration in ms of each kind; the step counts are in MOTION_CSS. */ +const WIPE_MS: Record = { + screen: 160, + page: 100, + slot: 120, + draw: 120, +}; + +type Px = { left: number; top: number; width: number; height: number }; + +function cover( + run: Run | null, + kind: WipeKind, + up: boolean, + tone: 'bg' | 'well', + style: Px, + z: number | undefined, +) { + if (!run) { + return null; + } + const clip: CSSProperties = { ...style }; + if (z !== undefined) { + clip.zIndex = z; + } + return createElement( + 'div', + { className: 'lt-wipe', style: clip }, + createElement('div', { + key: run.serial, + className: `lt-wipe-c is-${kind} is-${up ? 'up' : 'down'} is-${tone}`, + }), + ); +} + +/** + * A cover over a px rect of the positioned parent, played when `k` changes: it starts whole + * and retracts in steps with a bright line on its leading edge, showing what is under it. + * + * screen 160 ms, 8 steps; forward it retracts top to bottom, back bottom to top; the wipe sound + * page 100 ms, 5 steps, always top to bottom; the tick, lower going back + * slot 120 ms, 4 steps, top to bottom; no sound of its own + * draw 120 ms, 6 steps, left to right (a line of text being drawn); no sound of its own + * + * Back is a lower `n` (or a lower numeric `k`) than before, or `dir="up"`. + */ +export function Wipe(props: { + k: unknown; + n?: number; + kind?: WipeKind; + dir?: 'down' | 'up'; + /** The cover's colour: the terminal background, or a picture well's. */ + tone?: 'bg' | 'well'; + /** No sound. */ + quiet?: boolean; + /** Also plays when it mounts. */ + first?: boolean; + z?: number; + style: Px; +}) { + const { k, n, kind = 'screen', dir, tone = 'bg', quiet, first, z } = props; + /** The direction of the run under way, fixed when it starts. */ + const up = useRef(false); + const run = useRun(k, n, WIPE_MS[kind], first, (back) => { + const goingBack = dir ? dir === 'up' : back; + up.current = kind === 'screen' && goingBack; + if (quiet || kind === 'slot' || kind === 'draw') { + return; + } + if (kind === 'page') { + sfx('page', { rate: goingBack ? 0.9 : 1 }); + } else { + sfx(goingBack ? 'back' : 'wipe'); + } + }); + return cover(run, kind, up.current, tone, props.style, z); +} + +/** A white bar over a px rect for 200 ms when `k` changes: the row that changed. */ +export function Flash(props: { + k: unknown; + first?: boolean; + z?: number; + style: Px; +}) { + const run = useRun(props.k, undefined, 200, props.first); + if (!run) { + return null; + } + const style: CSSProperties = { ...props.style }; + if (props.z !== undefined) { + style.zIndex = props.z; + } + return createElement('div', { + key: run.serial, + className: 'lt-flashbar', + style, + }); +} + +// --------------------------------------------------------------------------- +// The screen in the main box +// --------------------------------------------------------------------------- + +type Screen = { id: string; depth: number; item: string; order: number }; +/** rect: a px rect of the main region to cover instead of the box (a dialog that closed). */ +type ScreenPlay = { serial: number; kind: WipeKind; up: boolean; rect?: Px }; + +let screen: Screen | null = null; +let screenSerial = 0; +let screenWipeAt = 0; +/** Hints for the screen change about to happen; each lapses if no change follows at once. */ +let quietUntil = 0; +let backUntil = 0; +const HINT_MS = 500; +const screenSubs = new Set<(play: ScreenPlay) => void>(); + +function playMain(play: Omit) { + screenSerial += 1; + const next = { ...play, serial: screenSerial }; + for (const fn of Array.from(screenSubs)) { + fn(next); + } +} + +const tabOf = (id: string) => id.split('/')[0]; + +/** The screen change about to happen makes no sound and draws no cover (the shell moved, not the player). */ +export function quietNextScreen() { + quietUntil = Date.now() + HINT_MS; +} + +/** The screen change about to happen is a step back, whatever the screens' depths say. */ +export function backNextScreen() { + backUntil = Date.now() + HINT_MS; +} + +function reportScreen(next: Screen, quiet: boolean) { + const was = screen; + screen = next; + if (!was || (was.id === next.id && was.item === next.item)) { + return; + } + const now = Date.now(); + const silent = quiet || now < quietUntil; + const forcedBack = now < backUntil; + quietUntil = 0; + backUntil = 0; + if (silent || muted || hidden()) { + return; + } + let kind: WipeKind = 'screen'; + let up = false; + if (was.id === next.id) { + // The same screen on another record: a stepper. + kind = 'page'; + up = next.order < was.order; + } else if (forcedBack || was.id === 'confirmed') { + up = true; + } else if (tabOf(was.id) === tabOf(next.id)) { + up = next.depth < was.depth; + } + if (kind === 'page') { + sfx('page', { rate: up ? 0.9 : 1 }); + } else { + sfx(up ? 'back' : 'wipe'); + } + screenWipeAt = Date.now(); + playMain({ kind, up: kind === 'screen' && up }); +} + +let quietCloseUntil = 0; + +/** The dialog about to close was answered, not backed out of: it goes without the back sound. */ +export function quietDialogClose() { + quietCloseUntil = Date.now() + 4000; +} + +/** + * A dialog closed: the wipe runs back over the px rect of the main region where it was, with + * the back sound, unless it was answered (quietDialogClose) or the screen under it changed in + * the same moment (that change has its own wipe). + */ +export function closeDialogFx(rect: Px) { + const answered = Date.now() < quietCloseUntil; + quietCloseUntil = 0; + if (muted || hidden()) { + return; + } + playMain({ kind: 'screen', up: true, rect }); + if (answered) { + return; + } + setTimeout(() => { + if (Date.now() - screenWipeAt > 100) { + sfx('back'); + } + }, 0); +} + +/** + * Tells the shell which screen the main box shows. id: 'tab/screen'; depth: how far in it is + * (a deeper screen opens forward, a shallower one is a step back); item and order: the record + * a stepper is on and its place in the list. quiet: the shell opened it, not the player. + */ +export function useScreen( + id: string, + depth = 0, + item = '', + order = 0, + quiet = false, +) { + useLayoutEffect(() => { + reportScreen({ id, depth, item, order }, quiet); + }, [id, depth, item, order]); +} + +/** Forgets the screen, so the next one reported opens without a cover (the page starting over). */ +export function resetScreen() { + screen = null; +} + +/** + * The shell's cover over the main box, played when the reported screen changes; also the + * cover over a dialog that has just closed. Mount it once, in the main region. + */ +export function ScreenWipe(props: { style: Px; z?: number }) { + const [run, setRun] = useState(null); + const timer = useRef | null>(null); + useLayoutEffect(() => { + const onPlay = (next: ScreenPlay) => { + setRun(next); + if (timer.current) { + clearTimeout(timer.current); + } + timer.current = setTimeout( + () => { + timer.current = null; + setRun(null); + }, + WIPE_MS[next.kind] + 50, + ); + }; + screenSubs.add(onPlay); + return () => { + screenSubs.delete(onPlay); + if (timer.current) { + clearTimeout(timer.current); + } + }; + }, []); + return cover( + run ? { serial: run.serial, back: run.up } : null, + run ? run.kind : 'screen', + !!run?.up, + 'bg', + run?.rect || props.style, + run?.rect ? 9 : props.z, + ); +} + +// --------------------------------------------------------------------------- +// Pulses and blinks +// --------------------------------------------------------------------------- + +export type PulseKind = 'w' | 'inva' | 'blink3'; + +const PULSE_MS: Record = { + w: 200, + inva: 240, + blink3: 960, +}; + +/** + * Restarts a short animation on the returned ref's element when `value` changes (never when + * it first appears). 'w': the text flashes white for 200 ms. 'inva': inverse amber for 240 ms. + * 'blink3': blinks three times, 160 ms on and 160 ms off. + */ +export function usePulse( + value: unknown, + kind: PulseKind = 'w', +) { + const ref = useRef(null); + const prev = useRef(value); + useEffect(() => { + const was = prev.current; + prev.current = value; + if (Object.is(was, value) || was === undefined || was === null) { + return; + } + const el = ref.current; + if (!el || hidden()) { + return; + } + el.removeAttribute('data-pulse'); + // Reading the box restarts the animation when the attribute comes back. + void el.offsetWidth; + el.setAttribute('data-pulse', kind); + const id = setTimeout( + () => el.removeAttribute('data-pulse'), + PULSE_MS[kind] + 40, + ); + return () => clearTimeout(id); + }, [value]); + return ref; +} + +/** TRUE and FALSE in turn, `ms` each, while `on` and the page is showing; FALSE otherwise. */ +export function useBlink(on: boolean, ms: number): boolean { + const [lit, setLit] = useState(false); + useEffect(() => { + if (!on) { + setLit(false); + return; + } + const id = setInterval(() => { + setLit((v) => (hidden() ? false : !v)); + }, ms); + return () => clearInterval(id); + }, [on, ms]); + return on && lit; +} + +/** Calls fn when `value` changes (never when it first appears), with the value before. */ +export function useChanged(value: T, fn: (was: T, now: T) => void) { + const prev = useRef(value); + const ref = useRef(fn); + ref.current = fn; + useEffect(() => { + const was = prev.current; + prev.current = value; + if (!Object.is(was, value)) { + ref.current(was, value); + } + }, [value]); +} + +/** + * The same, before the browser paints: for a change whose animation must start in the very + * frame the new value shows, so the end state is never seen ahead of it. State set in fn is + * drawn in that same frame. + */ +export function useChangedNow(value: T, fn: (was: T, now: T) => void) { + const prev = useRef(value); + const ref = useRef(fn); + ref.current = fn; + useLayoutEffect(() => { + const was = prev.current; + prev.current = value; + if (!Object.is(was, value)) { + ref.current(was, value); + } + }, [value]); +} + +/** Pauses every running animation under the returned ref's element while the page is hidden. */ +export function usePauseWhenHidden() { + const ref = useRef(null); + useEffect(() => { + const sync = () => { + const el = ref.current; + if (!el) { + return; + } + if (document.hidden) { + el.setAttribute('data-paused', ''); + } else { + el.removeAttribute('data-paused'); + } + }; + sync(); + document.addEventListener('visibilitychange', sync); + return () => document.removeEventListener('visibilitychange', sync); + }, []); + return ref; +} + +/** + * Keyframes and classes. --lw (the line weight in px) is set on .lt-tui by the shell. + * + * Step counts: a cover uses steps(n, end), so it shows n positions, the first of them whole, and + * is gone at the end; READY's fill does too, so it lands at the very end, when [#] appears. A band + * being drawn uses steps(n, start), so its first step shows at once and it is whole for the last. + */ +export const MOTION_CSS = ` +[data-paused] * { animation-play-state: paused !important; } +.lt-tui [data-press] { background: #fff !important; border-color: #fff !important; color: var(--lt-ink) !important; + text-shadow: none !important; } +.lt-tui [data-press] span { color: var(--lt-ink) !important; text-shadow: none !important; } +.lt-tui .lt-hit[data-press] { background: rgba(255,255,255,.8) !important; } +.lt-tui .lt-vscreen[data-press] { background: #07030d !important; border-color: #3a2466 !important; } +.lt-tui input[data-press] { background: transparent !important; color: var(--lt-fg) !important; } +.lt-wipe { position: absolute; overflow: hidden; pointer-events: none; z-index: 6; } +.lt-wipe-c { position: absolute; left: 0; top: 0; width: 100%; height: 100%; box-sizing: border-box; + background: var(--lt-bg, #0f0620); border: 0 solid var(--lt-fg, #dfc4ff); animation-fill-mode: forwards; } +.lt-wipe-c.is-well { background: #07030d; } +.lt-wipe-c.is-down { border-top-width: var(--lw, 2px); animation-name: lt-wipe-down; + box-shadow: 0 calc(var(--lw, 2px) * -1) calc(var(--lw, 2px) * 3) rgba(190,140,255,.55); } +.lt-wipe-c.is-up { border-bottom-width: var(--lw, 2px); animation-name: lt-wipe-up; + box-shadow: 0 var(--lw, 2px) calc(var(--lw, 2px) * 3) rgba(190,140,255,.55); } +.lt-wipe-c.is-screen { animation-duration: 160ms; animation-timing-function: steps(8, end); } +.lt-wipe-c.is-page { animation-duration: 100ms; animation-timing-function: steps(5, end); } +.lt-wipe-c.is-slot { animation-duration: 120ms; animation-timing-function: steps(4, end); } +.lt-wipe-c.is-draw { border-top-width: 0; border-left-width: var(--lw, 2px); box-shadow: none; + animation: lt-wipe-right 120ms steps(6, end) forwards; } +@keyframes lt-wipe-down { from { transform: translateY(0); } to { transform: translateY(100%); } } +@keyframes lt-wipe-up { from { transform: translateY(0); } to { transform: translateY(-100%); } } +@keyframes lt-wipe-right { from { transform: translateX(0); } to { transform: translateX(100%); } } +.lt-flashbar { position: absolute; z-index: 6; pointer-events: none; background: #fff; + animation: lt-flashbar 200ms steps(2, end) forwards; } +@keyframes lt-flashbar { from { opacity: .9; } to { opacity: 0; } } +.lt-tui [data-pulse="w"] { animation: lt-pulse-w 200ms steps(1, end); } +@keyframes lt-pulse-w { from, to { color: #fff; text-shadow: 0 0 6px #fff; } } +.lt-tui [data-pulse="inva"] { animation: lt-pulse-inva 240ms steps(1, end); } +@keyframes lt-pulse-inva { from, to { background: var(--lt-amb); color: var(--lt-ink); text-shadow: none; } } +@keyframes lt-draw { from { transform: scaleX(0); } to { transform: scaleX(1); } } +.lt-tui [data-pulse="blink3"], .lt-tui .lt-blink3 { animation: lt-blink3 320ms steps(1, end) 3; } +@keyframes lt-blink3 { 0% { opacity: 1; } 50% { opacity: 0; } } +.lt-tui .lt-draw { transform-origin: 0 50%; animation: lt-draw 120ms steps(6, start); } +.lt-tui .lt-draw-bad { transform-origin: 0 50%; + animation: lt-draw 120ms steps(6, start), lt-blink2 240ms steps(1, end) 120ms 2; } +@keyframes lt-blink2 { 0% { opacity: .55; } 50% { opacity: 1; } } +.lt-tui .lt-fill { position: absolute; left: 0; top: 0; width: 100%; height: 100%; background: var(--lt-acc); + transform-origin: 0 50%; pointer-events: none; animation-fill-mode: forwards; } +.lt-tui .lt-fill.is-on { animation: lt-fill-on 180ms steps(6, end) forwards; } +.lt-tui .lt-fill.is-off { animation: lt-fill-off 120ms steps(4, end) forwards; } +@keyframes lt-fill-on { from { transform: scaleX(0); } to { transform: scaleX(1); } } +@keyframes lt-fill-off { from { transform: scaleX(1); } to { transform: scaleX(0); } } +.lt-tui .lt-k.is-busy span { animation: lt-vblink 1.06s steps(1) infinite; } +.lt-tui .lt-light { position: absolute; z-index: 5; pointer-events: none; background: var(--lt-bg); + animation: lt-light 40ms steps(1, end) both; } +@keyframes lt-light { from { opacity: .62; } to { opacity: 0; } } +.lt-tui .lt-turn-a { animation: lt-turn-a 60ms steps(2, start) forwards; } +.lt-tui .lt-turn-b { animation: lt-turn-b 60ms steps(2, end) forwards; } +.lt-tui .lt-turn-hold { transform: scaleX(.2); } +@keyframes lt-turn-a { from { transform: scaleX(1); } to { transform: scaleX(.2); } } +@keyframes lt-turn-b { from { transform: scaleX(.2); } to { transform: scaleX(1); } } +`; diff --git a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/nav.tsx b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/nav.tsx index 26bd0cc95bd..0e041a26435 100644 --- a/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/nav.tsx +++ b/tgui/packages/voidcrew_tgui/interfaces/LobbyTerminal/nav.tsx @@ -10,7 +10,9 @@ * (lobby_terminal show code). tgui-core keeps arrows, Enter, Space, Escape and Tab in the page; * a key handled here is preventDefault()ed so tgui-core never passes it on to BYOND either. * - * Sounds play in the page from the terminal's assets, so a key press never costs a round trip. + * Sounds play in the page from the terminal's assets (motion.ts), so a key press never costs a + * round trip: a click when the focus moves, the key-press sound and an 80 ms white flash when + * an item is pressed, by Enter or by the mouse. */ import { createContext, @@ -24,7 +26,15 @@ import { useRef, useState, } from 'react'; -import { resolveAsset } from 'tgui/assets'; + +import { + muteSfx, + noteAction, + preloadSfx, + pressFlash, + pressFx, + sfx, +} from './motion'; export type Dir = 'up' | 'down' | 'left' | 'right'; @@ -40,16 +50,29 @@ export type FocusOpts = { edge?: Partial boolean>>; /** A tab: keeps the focus while the screen under it changes, and switches on arrow focus. */ tab?: boolean; + /** + * The open tab: an arrow move into the tab row from outside it lands here, not on the nearest + * tab. In a FocusGroup: the item a sideways move into the group lands on (the open category). + */ + entry?: boolean; /** Lit by the mouse only; the arrow keys pass it by (a cycler's < and >, which Left/Right drive). */ mouseOnly?: boolean; /** A text field: Enter starts typing in it. */ input?: RefObject; + /** + * Layout zone: 'menu' for the side menu and key bar, 'main' (the default) for the rest. An + * arrow move from the menu back into the main area returns to the main item that last had + * the focus, if it is still there. + */ + zone?: string; }; type Item = { el: () => HTMLElement | null; /** The FocusScope it sits in; only the newest open scope's items take the focus. */ scope: string; + /** The FocusGroup it sits in, if any. */ + group?: string; opts: RefObject; }; @@ -63,59 +86,30 @@ type Nav = { focus: (id: string, how: How) => void; register: (id: string, item: Item) => void; unregister: (id: string) => void; - pushBack: (id: string, fn: RefObject<() => void>) => void; + pushBack: (id: string, fn: RefObject<() => void>, scope: string) => void; popBack: (id: string) => void; + pushPager: (id: string, fn: RefObject<(step: number) => void>) => void; + popPager: (id: string) => void; }; const NavContext = createContext