diff --git a/bgs/tutorial.js b/bgs/tutorial.js index 86251ea..027074f 100644 --- a/bgs/tutorial.js +++ b/bgs/tutorial.js @@ -8,8 +8,9 @@ import { snapshot } from "../src/view.js"; import { mountConsole } from "../preview/app.js"; import { pictogram } from "../preview/icons.js"; import { tutorialTextHtml } from "../preview/tutorial-text.js"; +import { tutorialMissionHeader, updateTutorialMissionProgress } from "../preview/tutorial-header.js"; import { tutorialPhaseButton } from "../preview/tutorial-program.js"; -import { duration, practiceClockText } from "../preview/clock.js"; +import { duration } from "../preview/clock.js"; import { createSoundDesign } from "../preview/sound.js"; import html from "../preview/index.html"; import css from "../preview/style.css"; @@ -118,7 +119,12 @@ export async function mountLesson( ) await play({ type: "practice-tick", ms }); } + let displayedFrames = []; const ui = mountConsole(target, { + onDisplayedResolutionFrames(frames) { + displayedFrames = frames; + updateTutorialMissionProgress(guide, frames, locale); + }, tutorial: true, missions: [], locale, @@ -175,29 +181,6 @@ export async function mountLesson( : [t("tutorial.discover"), t("basics.plan"), t("tutorial.execute")]; const transport = (action, icon, title, disabled = false) => ``; - function missionOverview() { - return `
${[ - ["clock", "plan"], - ["lock", "lock"], - ["step", "play"], - ] - .map( - ([icon, key], i) => - `${i ? `` : ""}
${pictogram(icon)}${t(`overview.${key}`)}${t(`overview.${key}_detail`)}
`, - ) - .join( - "", - )}
${t("overview.turns")}
${[ - { first: 1, last: 3 }, - { first: 4, last: 7 }, - { first: 8, last: 12 }, - ] - .map( - ({ first, last }, i) => - `
${Array.from({ length: last - first + 1 }, (_, n) => `${first + n}`).join("")}
`, - ) - .join("")}
${pictogram("step")}
`; - } function renderGuide(s) { // Put planning decisions beside the program tools, without moving playback. if (s.state.stage === 'programming') @@ -228,12 +211,13 @@ export async function mountLesson( s.state.mission.phaseEndsMs[s.state.phase - 1] - s.state.observedAt, ); - programControls.innerHTML = `
${s.state.phase === 1 ? transport("phase-deadline", "forward", t("phases.skip"), !ready || !s.state.game.threats.length || s.busy) : ``}
${t("phases.deadline", { phase: s.state.phase, time: phaseTime })}${t("phases.total")} · ${practiceClockText(s.state, locale)}
${transport("phase-clock", s.state.tutorial.clockRunning ? "pause" : "clock", t(s.state.tutorial.clockRunning ? "basics.pause" : "basics.start_clock"))}
`; + programControls.innerHTML = `
${s.state.phase === 1 ? transport("phase-deadline", "forward", t("phases.skip"), !ready || !s.state.game.threats.length || s.busy) : ``}
${t("phases.deadline", { phase: s.state.phase, time: phaseTime })}
${transport("phase-clock", s.state.tutorial.clockRunning ? "pause" : "clock", t(s.state.tutorial.clockRunning ? "basics.pause" : "basics.start_clock"))}
`; } guide.innerHTML = `
${standalone ? `${t("tutorial.local_game")}` : ""}${transport("sound", soundOn ? "speaker" : "muted", soundOn ? t("tutorial.mute_sounds") : t("tutorial.enable_sounds"))}
-

${escape(s.title)}

${s.step === 0 && (chapter === "basics" || phaseLesson) ? missionOverview() : ""}${["basics", "first-shot", "energy"].includes(chapter) ? `${t("timing.exercise", { turns: chapter === "energy" ? 4 : 3 })}${chapter === "basics" ? ` · ${deadline ? 2 : 1}/2` : ""}` : ""}

${tutorialTextHtml(missed ? t("tutorial.destination_missed_go_back_and_plan_another_route") : s.text, locale)}

${chapter === "first-shot" && s.step < 2 ? `

${pictogram("shield")}${t("lesson.first-shot.shield")}

` : ""} +

${escape(s.title)}

${tutorialMissionHeader(chapter, s.step, locale)}

${tutorialTextHtml(missed ? t("tutorial.destination_missed_go_back_and_plan_another_route") : s.text, locale)}

${chapter === "first-shot" && s.step < 2 ? `

${pictogram("shield")}${t("lesson.first-shot.shield")}

` : ""}
${transport("restart", "rewind", t("tutorial.restart_exercise"), s.busy)}${transport("previous", "left", t("tutorial.previous_step"), s.step === 0 || s.busy)}${transport("replay", "restart", t("tutorial.replay_step"), s.busy || s.step === 0)}${s.canContinue ? `` : ""}${s.completed && (nextChapter || (standalone && LESSONS[index + 1])) ? `` : ""}
${s.error ? `

${escape(s.error)}

` : ""}`; + updateTutorialMissionProgress(guide, displayedFrames, locale); } const unsubscribe = tutorial.subscribe((s) => { if (disposed) return; diff --git a/preview/app.js b/preview/app.js index 0ab059d..ca044c4 100644 --- a/preview/app.js +++ b/preview/app.js @@ -737,7 +737,7 @@ export function mountConsole(root, host = null) { .join("") : ""; $("#replay").innerHTML = resolution - ? `

${resolution.outcome ? `${resolution.outcome.survived ? "✓" : "✕"} ${t("app.score")} : ${resolution.outcome.score} · ${resolution.outcome.threatPoints} ${t("app.threats_87b951")} + ${resolution.outcome.visual} ${t("app.visual")} − ${resolution.outcome.penalties} ${t("app.penalties")}` : resolution.turn > resolution.lastTurn ? t("app.final_threat_movement") : `${t("app.turn")} ${resolution.turn} · ${esc({ appear: t("app.appearances"), crew: t("app.crew_actions"), damage: t("app.damage"), threats: t("app.threat_actions"), computer: t("app.computer") }[resolution.step])}`}

${replayFrame !== null ? '" : ""}` + ? `

${resolution.outcome ? `${resolution.outcome.survived ? "✓" : "✕"} ${t("app.score")} : ${resolution.outcome.score} · ${resolution.outcome.threatPoints} ${t("app.threats_87b951")} + ${resolution.outcome.visual} ${t("app.visual")} − ${resolution.outcome.penalties} ${t("app.penalties")}` : resolution.turn > resolution.lastTurn ? t("app.final_threat_movement") : `${t("app.turn")} ${resolution.turn} · ${esc({ appear: t("app.appearances"), crew: t("app.crew_actions"), damage: t("app.damage"), threats: t("app.threat_actions"), computer: t("app.computer") }[resolution.step])}`}

${replayFrame !== null ? '" : ""}
` : ""; renderCampaign(g?.campaign); $("#announcements").innerHTML = resolution @@ -776,6 +776,8 @@ export function mountConsole(root, host = null) { `

${t("app.left_center_and_right_correspond_to_red_white")}

` + t("app.plan_choose_a_card_then_a_turn_click"); navigation.sync(); + // The guide follows the same frame as the ship, including scrubbing/reset. + host?.onDisplayedResolutionFrames?.(resolution?.frames.slice(0, (replayFrame ?? resolution.frames.length - 1) + 1) ?? []); effects.afterRender(resolution, replayFrame ?? (resolution?.frames.length ?? 0) - 1); } function calledHtml(data) { diff --git a/preview/icons.js b/preview/icons.js index 258945b..21ad54d 100644 --- a/preview/icons.js +++ b/preview/icons.js @@ -73,7 +73,8 @@ export const specializationIcons = { }; export function pictogram(name) { - return ``; + const action = { A: "fire", B: "energy", C: "systems" }[name]; + return ``; } // A miniature of the actual six-room plan, readable without colour. diff --git a/preview/locales/en.json b/preview/locales/en.json index c331ea9..42eef40 100644 --- a/preview/locales/en.json +++ b/preview/locales/en.json @@ -511,6 +511,7 @@ "tactical.show_my_cards": "Show my {value1} cards", "tactical.power": "Power", "tactical.fire": "Fire", + "tactical.weapon_power": "Weapon power: {power}", "tactical.firepower": "Firepower", "tactical.own_battery": "Own battery", "tactical.cost_1_energy": "Cost: 1 energy", @@ -589,6 +590,8 @@ "overview.lock_detail": "Each phase locks a group of turns.", "overview.play": "Play the whole mission", "overview.play_detail": "Every turn, in order. No more planning.", + "overview.turn_completed": "Turn {turn} completed", + "overview.turn_current": "Turn {turn} in progress", "overview.turns": "Full mission · 12 turns", "route.planned": "Planned position after turn {turn}: {room}", "route.assumption": "Intended route without disruptions: delays, threats or a busy lift may change it.", diff --git a/preview/locales/fr.json b/preview/locales/fr.json index a9bd720..9708cb2 100644 --- a/preview/locales/fr.json +++ b/preview/locales/fr.json @@ -511,6 +511,7 @@ "tactical.show_my_cards": "Voir mes cartes {value1}", "tactical.power": "Puissance", "tactical.fire": "Tirer", + "tactical.weapon_power": "Puissance de l’arme : {power}", "tactical.firepower": "Puissance de tir", "tactical.own_battery": "Batterie autonome", "tactical.cost_1_energy": "Coût : 1 énergie", @@ -589,6 +590,8 @@ "overview.lock_detail": "Chaque phase verrouille un groupe de tours.", "overview.play": "Exécuter toute la mission", "overview.play_detail": "Tous les tours, dans l’ordre. Plus de programmation.", + "overview.turn_completed": "Tour {turn} terminé", + "overview.turn_current": "Tour {turn} en cours", "overview.turns": "Mission complète · 12 tours", "route.planned": "Position prévue après le tour {turn} : {room}", "route.assumption": "Trajet prévu, sans perturbations : retards, menaces ou ascenseur occupé peuvent le modifier.", diff --git a/preview/resolution-effects.js b/preview/resolution-effects.js index 2c207b2..3a58656 100644 --- a/preview/resolution-effects.js +++ b/preview/resolution-effects.js @@ -69,6 +69,7 @@ export function createResolutionEffects(root, cue) { let previous = null, previousIndex = -1, busyUntil = 0, pendingFrame = null; let oldPawns = new Map(); let oldShip = null; + const movingPawns = new Map(); const animations = new Set(), timers = new Set(), restores = []; const q = selector => root.querySelector(selector); const threat = id => q(`[data-threat="${id}"] .threat-portrait`); @@ -84,13 +85,23 @@ export function createResolutionEffects(root, cue) { const id = win.setTimeout(() => { timers.delete(id); callback(); }, ms); timers.add(id); } - function animate(element, frames, duration, delay = 0, easing = "ease-out") { - if (!element?.animate) return; + function animate(element, frames, duration, delay = 0, easing = "ease-out", finish = () => {}) { + if (!element?.animate) { finish(); return; } const animation = element.animate(frames, { duration, delay, easing, fill: "both" }); animations.add(animation); - animation.finished.then(() => { animations.delete(animation); animation.cancel(); }, () => {}); + animation.finished.then(() => { + // clear() may have cancelled this animation after its promise resolved. + if (!animations.delete(animation)) return; + // Remove transient art / reveal the real pawn BEFORE releasing fill. A + // separate removal timer can otherwise paint the underlying source pose. + finish(); + animation.cancel(); + }, () => {}); busyUntil = Math.max(busyUntil, performance.now() + duration + delay); } + function animateTransient(element, frames, duration) { + animate(element, frames, duration, 0, "ease-out", () => element.remove()); + } function clear() { if (pendingFrame !== null) win.cancelAnimationFrame(pendingFrame); pendingFrame = null; @@ -99,6 +110,7 @@ export function createResolutionEffects(root, cue) { for (const animation of animations) animation.cancel(); animations.clear(); for (const restore of restores.splice(0)) restore(); + movingPawns.clear(); layer.replaceChildren(); busyUntil = 0; } @@ -112,14 +124,14 @@ export function createResolutionEffects(root, cue) { function burst(p, color, large = false) { if (!p) return; const ring = node("fx-ring", p, color); - animate(ring, [{ transform: `translate(-50%,-50%) scale(${reduced.matches ? 1 : .2})`, opacity: .9 }, + animateTransient(ring, [{ transform: `translate(-50%,-50%) scale(${reduced.matches ? 1 : .2})`, opacity: .9 }, { transform: `translate(-50%,-50%) scale(${reduced.matches ? 1 : large ? 3 : 1.5})`, opacity: 0 }], large ? 650 : 380); later(() => ring.remove(), 700); if (reduced.matches) return; for (let i = 0; i < (large ? 18 : 7); i++) { const spark = node("fx-spark", p, color); const angle = i * 2.39996, distance = (large ? 65 : 26) + (i % 4) * 9; - animate(spark, [{ transform: "translate(-50%,-50%) scale(1)", opacity: 1 }, + animateTransient(spark, [{ transform: "translate(-50%,-50%) scale(1)", opacity: 1 }, { transform: `translate(${Math.cos(angle) * distance}px,${Math.sin(angle) * distance}px) scale(.1)`, opacity: 0 }], large ? 700 : 400); later(() => spark.remove(), 750); } @@ -135,18 +147,15 @@ export function createResolutionEffects(root, cue) { beam.style.transform = `rotate(${Math.atan2(dy, dx)}rad)`; const bolt = doc.createElement("i"); beam.append(bolt); - animate(bolt, [{ transform: "translateX(0)", opacity: 1 }, + animateTransient(bolt, [{ transform: "translateX(0)", opacity: 1 }, { transform: `translateX(${Math.hypot(dx, dy)}px)`, opacity: 1 }], 300); later(() => beam.remove(), 310); } function delta(p, value, color, icon = "") { if (!p || !value) return; const n = node("fx-delta", p, color); - // Cancelling the finished animation restores the underlying style before - // the removal timer runs. Keep that style hidden to avoid a one-frame flash. - n.style.opacity = "0"; n.textContent = `${icon}−${value}`; - animate(n, [{ transform: "translate(-50%,-20%)", opacity: 1 }, + animateTransient(n, [{ transform: "translate(-50%,-20%)", opacity: 1 }, { transform: `translate(-50%,${reduced.matches ? "-20%" : "-140%"})`, opacity: 0 }], 750); later(() => n.remove(), 760); } @@ -179,10 +188,10 @@ export function createResolutionEffects(root, cue) { jumpSound("thruster"); for (const nozzle of vessel.querySelectorAll(".ship-stern i")) { animate(nozzle, [ - { transform: "translateY(12px) scaleY(1)", filter: "brightness(1)" }, - { transform: "translateY(12px) scaleY(2.5)", filter: "brightness(1.6)", offset: .5 }, - { transform: "translateY(12px) scaleY(5)", filter: "brightness(2.3)", offset: .76 }, - { transform: "translateY(12px) scaleY(5)", filter: "brightness(2.3)" }, + { background: "#526773", boxShadow: "none", transform: "translateY(12px) scaleY(1)", filter: "brightness(1)" }, + { background: "#95dfe7", boxShadow: "0 3px 7px #82eff04a", transform: "translateY(12px) scaleY(2.5)", filter: "brightness(1.6)", offset: .5 }, + { background: "#95dfe7", boxShadow: "0 3px 7px #82eff04a", transform: "translateY(12px) scaleY(5)", filter: "brightness(2.3)", offset: .76 }, + { background: "#95dfe7", boxShadow: "0 3px 7px #82eff04a", transform: "translateY(12px) scaleY(5)", filter: "brightness(2.3)" }, ], 1450, 0, "linear"); } animate(vessel, [ @@ -200,7 +209,7 @@ export function createResolutionEffects(root, cue) { x: p.x + ((i * .618034) % 1 - .5) * p.width, y: p.y + ((i * .381966) % 1 - .5) * p.height, }, "#a1f4ef", stage); - animate(star, [ + animateTransient(star, [ { transform: "scaleY(.2)", opacity: 0 }, { transform: "translateY(20px) scaleY(1)", opacity: .8, offset: .3 }, { transform: "translateY(90px) scaleY(2)", opacity: 0 }, @@ -215,7 +224,7 @@ export function createResolutionEffects(root, cue) { jumpSound("victory"); const seal = node("fx-jump-success", p, "#76e5c6", stage); seal.innerHTML = pictogram("check"); - animate(seal, [ + animateTransient(seal, [ { transform: `translate(-50%,-50%) scale(${reduced.matches ? 1 : .85})`, opacity: 0 }, { transform: "translate(-50%,-50%) scale(1)", opacity: 1, offset: .2 }, { transform: "translate(-50%,-50%) scale(1)", opacity: 1, offset: .7 }, @@ -240,21 +249,18 @@ export function createResolutionEffects(root, cue) { if (e.kind === "move" && !moved.has(e.crew)) { moved.add(e.crew); const pawn = q(`[data-crew="${e.crew}"]`), from = oldPawns.get(String(e.crew)), to = point(pawn); - if (!pawn || !from || !to) continue; + const moving = movingPawns.get(String(e.crew)); + if (!pawn || !from || !to) { moving?.finish(); continue; } sound("move", to); - if (reduced.matches) { flash(room(e.to), "#76e5c660"); continue; } - const clone = pawn.cloneNode(true); - clone.removeAttribute("data-crew"); - clone.classList.add("fx-pawn"); - clone.style.cssText += `;left:${from.x}px;top:${from.y}px;width:${from.width}px;height:${from.height}px`; - layer.append(clone); - pawn.style.visibility = "hidden"; - const restore = () => { pawn.style.visibility = ""; }; - restores.push(restore); + if (reduced.matches) { moving?.finish(); flash(room(e.to), "#76e5c660"); continue; } + if (!moving) continue; + const { clone, finish } = moving; + // Rebase after layout/scroll anchoring has settled, not before it. + clone.style.left = `${from.x}px`; + clone.style.top = `${from.y}px`; const path = events.filter(x => x.kind === "move" && x.crew === e.crew); const points = [from, ...path.slice(0, -1).map(x => point(room(x.to))).filter(Boolean), to]; - animate(clone, points.map(p => ({ transform: `translate(calc(-50% + ${p.x - from.x}px),calc(-50% + ${p.y - from.y}px))` })), 460); - later(() => { restore(); clone.remove(); }, 465); + animate(clone, points.map(p => ({ transform: `translate(calc(-50% + ${p.x - from.x}px),calc(-50% + ${p.y - from.y}px))` })), 460, 0, "ease-out", finish); } if (e.kind === "charge") { flash(weapon(e.station), "#8eeaff80"); @@ -322,11 +328,33 @@ export function createResolutionEffects(root, cue) { oldMeters.set(`damage-${zone}`, room(`${zone}-upper`)?.querySelector(".station-title")?.innerHTML); } } + function prepareMovement(events) { + if (reduced.matches) return; + for (const e of events) { + const id = String(e.crew); + if (e.kind !== "move" || movingPawns.has(id)) continue; + const pawn = q(`[data-crew="${e.crew}"]`), from = oldPawns.get(id); + if (!pawn || !from || !point(pawn)) continue; + const clone = pawn.cloneNode(true); + clone.removeAttribute("data-crew"); + clone.classList.add("fx-pawn"); + clone.style.cssText += `;left:${from.x}px;top:${from.y}px;width:${from.width}px;height:${from.height}px;transform:translate(-50%,-50%)`; + layer.append(clone); + const visibility = pawn.style.visibility; + pawn.style.visibility = "hidden"; + const finish = () => { pawn.style.visibility = visibility; clone.remove(); }; + restores.push(finish); + movingPawns.set(id, { clone, finish }); + } + } function afterRender(resolution, index) { const current = resolution?.frames[index]; if (current && previous && index === previousIndex + 1 && !doc.hidden) { const events = resolutionEffects(resolution, previous, current), before = previous; if (events.length) { + // afterRender runs in the render task: replace destination pawns before + // the first paint, while retaining the two-frame layout settling below. + prepareMovement(events); // Tutorial completion also updates the guide and removes controls. Let // layout and scroll anchoring settle before locating beams and targets. busyUntil = performance.now() + 1000; diff --git a/preview/style.css b/preview/style.css index de042a0..2423c10 100644 --- a/preview/style.css +++ b/preview/style.css @@ -8,6 +8,9 @@ --gold: #e8c984; --panel: #12232f; --cyan: #78cecf; + --action-fire: #ffad70; + --action-energy: #f4d66f; + --action-systems: #78d6cc; --red: #e2968d; --blue: #8ab4ec; --white: #d6d4b9; @@ -557,8 +560,36 @@ h2 { #transfer button { font-size: 11px; } +#replay .replay-toolbar { + display: grid; + gap: 12px; + padding-block: 4px 12px; +} +#replay .replay-review { + display: grid; + gap: 8px; + min-width: 0; + color: var(--muted); + font-size: 12px; +} #replay input { + display: block; width: 100%; + min-width: 0; + margin: 0; + accent-color: var(--cyan); +} +#replay .replay-actions { + display: flex; + flex-wrap: wrap; + align-items: stretch; + gap: 10px; +} +#replay .replay-actions button { + min-height: 44px; + padding: 10px 16px; + max-width: 100%; + line-height: 1.3; } #replay p { font-size: 12px; @@ -1222,21 +1253,13 @@ input:not([type="checkbox"]):not([type="range"]) { display: flex; flex-direction: column; padding: 7px 5px 5px; - border: 2px solid #5b7581; + border: 2px solid var(--zone); border-top: 3px solid var(--zone); border-radius: 9px 9px 5px 5px; - background: - linear-gradient( - 90deg, - transparent 49%, - #2c465240 49%, - #2c465240 51%, - transparent 51% - ), - #112330; + background: #101e29; } .station.selected-station { - background-color: #203744; + background-color: #172936; } .station-title { display: flex; @@ -1339,16 +1362,16 @@ input:not([type="checkbox"]):not([type="range"]) { display: none; } .power-value { - color: #ffe0a3; - font-size: 15px; + color: #eaf3f7; + font-size: 19px; font-weight: 700; } .power-value .symbol-stat { gap: 3px; } .power-value .pictogram { - width: 14px; - height: 14px; + width: 18px; + height: 18px; } .energy-system button { min-height: 55px; @@ -1356,8 +1379,8 @@ input:not([type="checkbox"]):not([type="range"]) { grid-template-columns: 48px minmax(0, 1fr); gap: 3px; padding: 2px 5px; - border-block: 1px solid #466979; - background: #1a3645; + border-block: 1px solid #344651; + background: #172936; } .energy-system .equipment-art { width: 44px; @@ -1573,9 +1596,9 @@ input:not([type="checkbox"]):not([type="range"]) { height: 14px; transform: translateY(12px); transform-origin: 50% 0; - background: #95dfe7; + background: #526773; border-radius: 0 0 6px 6px; - box-shadow: 0 3px 7px #82eff04a; + box-shadow: none; } .ship-key { display: flex; @@ -2415,7 +2438,9 @@ input:not([type="checkbox"]):not([type="range"]) { .native-guide .basics-stages { gap: 3px; } .native-guide .basics-stages button { flex-direction: column; gap: 6px; padding: 10px 4px; text-align: center; } } -.native-tutorial #basics-run { width: 64px; height: 48px; } +/* This control includes a translated label, not just an icon. */ +.native-tutorial #basics-run { width: auto; height: auto; min-height: 48px; flex: 0 1 auto; } +.native-tutorial #basics-run span { overflow-wrap: normal; word-break: normal; } .practice-readiness > span { display: inline-flex; align-items: center; gap: 6px; } .native-tutorial.learning-basics .flight-layout { display: grid !important; margin: 0; align-items: start; } .native-tutorial.learning-basics #planning { min-width: 0; } @@ -2450,7 +2475,6 @@ input:not([type="checkbox"]):not([type="range"]) { .native-tutorial.learning-basics #ship .station-title { visibility: hidden; } .native-tutorial.learning-basics[data-tutorial-stage="resolution"] #controls { display: flex !important; gap: 10px; } .native-tutorial.learning-basics[data-tutorial-stage="resolution"] #replay { display: block !important; } -.native-tutorial.learning-basics[data-tutorial-stage="resolution"] #replay label { display: block; } .native-tutorial.learning-basics[data-tutorial-step="3"] #controls { display: none !important; } .native-tutorial.learning-basics[data-tutorial-step="3"] #replay:not(:empty) { display: block !important; } @@ -2671,7 +2695,12 @@ input:not([type="checkbox"]):not([type="range"]) { .mission-timeline > svg { width: 22px; height: 22px; } .mission-group { display: flex; gap: 4px; padding-bottom: 5px; border-bottom: 2px solid var(--cyan); } .mission-group.later { opacity: .5; } +.mission-group.later.progressed { opacity: 1; } .mission-group span { display: grid; place-items: center; width: 23px; height: 28px; border: 1px solid #527181; border-radius: 4px; } +/* Static cues: fill + inset bottom rule for completed turns, double outline + for the displayed turn. No animation, including under reduced motion. */ +.mission-group span.completed { background: #264d55; color: #d1f6ef; border-color: #72c9bb; box-shadow: inset 0 -3px #72c9bb; } +.mission-group span.current { outline: 3px double var(--gold); outline-offset: 1px; color: var(--gold); font-weight: 700; } .lesson-scope { display: block; color: var(--muted); margin: -8px 0 10px; } .practice-clock.stopped > svg { width: 22px; height: 22px; color: var(--cyan); } .phase-lesson-controls { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; } @@ -2716,3 +2745,40 @@ input:not([type="checkbox"]):not([type="range"]) { .ship-jump-effects > span { position: absolute; } .fx-jump-success { display: grid; place-items: center; width: 80px; height: 80px; border: 2px solid var(--fx-color); border-radius: 50%; background: #102b32ee; color: var(--fx-color); box-shadow: 0 0 30px #76e5c650,inset 0 0 20px #76e5c620; } .fx-jump-success .pictogram { width: 44px; height: 44px; } + +/* Action colour belongs to the shared glyph/badge, never the whole card. */ +.pictogram.action-fire { color: var(--action-fire); } +.pictogram.action-energy { color: var(--action-energy); } +.pictogram.action-systems { color: var(--action-systems); } +.action-key:has(.action-fire) { --action-accent: var(--action-fire); } +.action-key:has(.action-energy) { --action-accent: var(--action-energy); } +.action-key:has(.action-systems) { --action-accent: var(--action-systems); } +.action-key { + background: #101e29; + border-color: var(--action-accent, #8296a0); +} +/* Continuous zone rails join both decks while the rooms stay dark. */ +.ship-zones { + position: absolute; + inset: 40px 14px 12px; + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 12px; + pointer-events: none; +} +.ship-zones > span { + border-inline: 2px solid var(--zone); + border-radius: 9px 9px 5px 5px; + background: color-mix(in srgb, var(--zone) 12%, #172c39); +} +.ship-hull::before { z-index: -1; } +.ship-hull { isolation: isolate; } +@container (max-width: 400px) { + .ship-zones { gap: 10px; } +} +@supports not (container-type: inline-size) { + @media (max-width: 760px) { .ship-zones { gap: 10px; } } +} +@media (max-width: 760px) { + .ship-zones { inset: 30px 9px 12px; } +} diff --git a/preview/tactical.js b/preview/tactical.js index 0b88e5b..a9fbb73 100644 --- a/preview/tactical.js +++ b/preview/tactical.js @@ -53,6 +53,7 @@ export function createTacticalView({ : light ? t("tactical.light_laser") : t("tactical.heavy_laser"); + const powerLabel = t("tactical.weapon_power", { power }); const weaponArt = pulse ? "pulse" : light ? "light-laser" : "laser"; const fireText = light ? t("tactical.the_light_laser_has_its_own_battery_it") @@ -76,7 +77,7 @@ export function createTacticalView({ const details = (key, art, text, extra = "") => ``; return `
-
${details("A", weaponArt, fireText, `
${symbol("laser", `${t("tactical.firepower")} ${power}`, power)}${symbol(light ? "check" : "reactor", light ? t("tactical.own_battery") : t("tactical.cost_1_energy"), light ? t("tactical.own_battery_defc21") : "−1")}
`)}
+
${details("A", weaponArt, fireText, `
${symbol("impact", powerLabel, power)}${symbol(light ? "check" : "reactor", light ? t("tactical.own_battery") : t("tactical.cost_1_energy"), light ? t("tactical.own_battery_defc21") : "−1")}
`)}
${details("B", system, chargeText, flow)}
${details("C", cIcon, cText)}
`; @@ -130,7 +131,7 @@ export function createTacticalView({ .join( "", )}${[1, 2].map((i) => `
${movementHelp(false)}
`).join("")}`; - return `
${deck("upper")}
${zones.map((z) => `
${movementHelp(true)}
`).join("")}
${deck("lower")}
${pictogram("A")}${t("tactical.fire")}${pictogram("B")}${t("app.energy")}${pictogram("C")}${t("app.systems")}
`; + return `
${deck("upper")}
${zones.map((z) => `
${movementHelp(true)}
`).join("")}
${deck("lower")}
${pictogram("A")}${t("tactical.fire")}${pictogram("B")}${t("app.energy")}${pictogram("C")}${t("app.systems")}
`; } function threatPortrait(th) { diff --git a/preview/tutorial-header.js b/preview/tutorial-header.js new file mode 100644 index 0000000..b754e31 --- /dev/null +++ b/preview/tutorial-header.js @@ -0,0 +1,65 @@ +import { translate } from "./i18n.js"; +import { pictogram } from "./icons.js"; + +// Shared by the embedded BGS tutorial and the standalone /learn guide. +// Keep both introductory overviews in place throughout planning and playback. +export function tutorialMissionHeader(chapter, step, locale) { + const t = (key, params) => translate(locale, key, params); + const overview = ["basics", "planning-phases"].includes(chapter) + ? missionOverview(t) + : ""; + const scope = ["basics", "first-shot", "energy"].includes(chapter) + ? `${t("timing.exercise", { turns: chapter === "energy" ? 4 : 3 })}` + : ""; + return overview + scope; +} + +function missionOverview(t) { + return `
${[ + ["clock", "plan"], + ["lock", "lock"], + ["step", "play"], + ] + .map( + ([icon, key], i) => + `${i ? `` : ""}
${pictogram(icon)}${t(`overview.${key}`)}${t(`overview.${key}_detail`)}
`, + ) + .join( + "", + )}
${t("overview.turns")}
${[ + { first: 1, last: 3 }, + { first: 4, last: 7 }, + { first: 8, last: 12 }, + ] + .map( + ({ first, last }, i) => + `
${Array.from({ length: last - first + 1 }, (_, n) => `${first + n}`).join("")}
`, + ) + .join("")}
${pictogram("step")}
`; +} + +// Frames describe the *next* resolution operation. Only a captured `appear` +// frame closes a whole turn (crew actions alone do not finish threat movement). +// Use the displayed prefix, never the live cursor, clock, or planned cards. +export function missionTurnProgress(frames = []) { + const completed = new Set(frames.filter((frame) => frame.step === "appear" && frame.turn > 0).map((frame) => frame.turn)); + const displayed = frames.at(-1); + return { completed, current: displayed && !completed.has(displayed.turn) ? displayed.turn : 0 }; +} + +export function updateTutorialMissionProgress(root, frames, locale) { + const { completed, current } = missionTurnProgress(frames); + for (const cell of root.querySelectorAll("[data-mission-turn]")) { + const turn = Number(cell.dataset.missionTurn); + const done = completed.has(turn); + const active = turn === current; + cell.classList.toggle("completed", done); + cell.classList.toggle("current", active); + if (active) cell.setAttribute("aria-current", "step"); + else cell.removeAttribute("aria-current"); + const label = translate(locale, done ? "overview.turn_completed" : active ? "overview.turn_current" : "program.selected_turn", { turn }); + cell.setAttribute("aria-label", label); + cell.setAttribute("title", label); + cell.parentElement.classList.toggle("progressed", [...cell.parentElement.children].some((sibling) => sibling.classList.contains("completed") || sibling.classList.contains("current"))); + } +} diff --git a/test/resolution-effects-lifecycle.test.js b/test/resolution-effects-lifecycle.test.js new file mode 100644 index 0000000..a37398a --- /dev/null +++ b/test/resolution-effects-lifecycle.test.js @@ -0,0 +1,147 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { createResolutionEffects } from "../preview/resolution-effects.js"; + +// A controlled rendering clock exposes paints between the two layout frames and +// the microtask at animation completion, independently of removal timers. +function fixture({ reduced = false, animate = true } = {}) { + const raf = new Map(), timers = new Map(), listeners = new Map(), animations = []; + let serial = 0; + const win = { + innerWidth: 1000, + matchMedia: () => ({ matches: reduced }), + requestAnimationFrame: fn => { raf.set(++serial, fn); return serial; }, + cancelAnimationFrame: id => raf.delete(id), + setTimeout: fn => { timers.set(++serial, fn); return serial; }, + clearTimeout: id => timers.delete(id), + addEventListener: (name, fn) => listeners.set(name, fn), + removeEventListener: name => listeners.delete(name), + }; + function element(x = 0) { + const el = { + style: { visibility: "", cssText: "" }, dataset: {}, children: [], x, + classList: { add() {} }, setAttribute() {}, removeAttribute() {}, + getClientRects: () => [1], + getBoundingClientRect() { return { left: this.x, top: 0, width: 20, height: 20 }; }, + append(child) { child.parent = this; this.children.push(child); }, + remove() { if (this.parent) this.parent.children = this.parent.children.filter(c => c !== this); this.removed = true; }, + replaceChildren() { for (const child of [...this.children]) child.remove(); }, + querySelector: () => null, + querySelectorAll: () => [], + cloneNode() { const clone = element(this.x); clone.style = { ...this.style }; return clone; }, + }; + if (animate) el.animate = (frames, options) => { + let resolve; + const animation = { element: el, frames, options, finished: new Promise(r => { resolve = r; }), + finish: () => resolve(), cancel() { this.cancelled = true; this.removedAtCancel = el.removed; } }; + animations.push(animation); + return animation; + }; + return el; + } + const layout = element(), ship = element(), pawn = element(100), room = element(200); + pawn.dataset.crew = "0"; + const doc = { defaultView: win, hidden: false, createElement: () => element(), + addEventListener: (name, fn) => listeners.set(name, fn), removeEventListener: name => listeners.delete(name) }; + const root = { ownerDocument: doc, + querySelector: selector => selector === ".flight-layout" ? layout : selector === ".ship-vessel" ? ship : selector.startsWith("[data-crew") ? pawn : selector.startsWith("[data-station") ? room : null, + querySelectorAll: selector => selector === "[data-crew]" ? [pawn] : [] }; + const effects = createResolutionEffects(root, () => {}); + const before = { logEnd: 0, turn: 1, ship: { crew: [{ id: 0, station: "white-upper" }] }, threats: [] }; + const after = { ...before, logEnd: 1, ship: { crew: [{ id: 0, station: "blue-upper" }] } }; + const resolution = { frames: [before, after], log: [{ type: "move", crew: 0, from: "white-upper", to: "blue-upper" }] }; + effects.afterRender(resolution, 0); + function render() { effects.beforeRender(); pawn.x = 300; effects.afterRender(resolution, 1); } + function frame() { const callbacks = [...raf.values()]; raf.clear(); callbacks.forEach(fn => fn()); } + return { effects, resolution, render, frame, pawn, ship, layer: layout.children[0], animations, raf, timers, listeners, win, doc }; +} + +test("moving pawn is replaced before the first paint, then atomically handed off at finish", async () => { + const f = fixture(); + f.pawn.style.visibility = "visible"; + f.render(); + assert.equal(f.pawn.style.visibility, "hidden"); + assert.equal(f.layer.children.length, 1, "source stand-in exists during layout settling"); + assert.match(f.layer.children[0].style.cssText, /transform:translate\(-50%,-50%\)/); + assert.equal(f.layer.children[0].style.visibility, "visible"); + assert.equal(f.animations.length, 0); + f.frame(); + assert.equal(f.pawn.style.visibility, "hidden"); + assert.equal(f.animations.length, 0, "retain double RAF for scroll anchoring"); + f.ship.x += 40; + f.frame(); + const animation = f.animations[0]; + assert.equal(animation.element.style.left, "150px", "source rebased to settled ship"); + assert.equal(animation.options.duration, 460); + animation.finish(); + await Promise.resolve(); + assert.equal(f.pawn.style.visibility, "visible", "restore exact inline visibility"); + assert.equal(f.layer.children.length, 0); + assert.equal(animation.removedAtCancel, true, "no source-pose paint when fill is released"); + assert.equal(f.timers.size, 0, "handoff is not a racing timeout"); +}); + +for (const phase of [0, 1, 2]) { + for (const cleanup of ["reset", "render", "resize", "hidden", "destroy"]) { + test(`${cleanup} restores moving pawn after ${phase} layout frames`, async () => { + const f = fixture(); + f.render(); + for (let i = 0; i < phase; i++) f.frame(); + // Also exercise a resolved-but-not-yet-delivered finished callback. + f.animations[0]?.finish(); + if (cleanup === "render") f.effects.beforeRender(); + else if (cleanup === "resize") { f.win.innerWidth--; f.listeners.get("resize")(); } + else if (cleanup === "hidden") { f.doc.hidden = true; f.listeners.get("visibilitychange")(); } + else f.effects[cleanup](); + await Promise.resolve(); + assert.equal(f.pawn.style.visibility, ""); + assert.equal(f.layer.children.length, 0); + assert.equal(f.raf.size, 0); + assert.equal(f.timers.size, 0); + assert.equal(f.effects.busy(), false); + }); + } +} + +test("height-only resize preserves movement and reduced motion never hides the pawn", () => { + const f = fixture(); + f.render(); + f.listeners.get("resize")(); + assert.equal(f.pawn.style.visibility, "hidden"); + assert.equal(f.raf.size, 1); + f.effects.destroy(); + const r = fixture({ reduced: true }); + r.render(); r.frame(); r.frame(); + assert.equal(r.pawn.style.visibility, ""); + assert.equal(r.layer.children.length, 0); + r.effects.destroy(); +}); + +test("without Web Animations support the destination is restored after settling", () => { + const f = fixture({ animate: false }); + f.render(); f.frame(); f.frame(); + assert.equal(f.pawn.style.visibility, ""); + assert.equal(f.layer.children.length, 0); + f.effects.destroy(); +}); + + +test("shared transient bursts and damage labels are removed before animation cancellation", async () => { + const f = fixture(); + f.resolution.log = [{ type: "ship-damage", zone: "blue", source: 42 }]; + f.resolution.frames[1].ship = f.resolution.frames[0].ship; + f.render(); f.frame(); f.frame(); + // Deliver the impact delay, but deliberately not the later removal timers. + for (const callback of [...f.timers.values()]) callback(); + const transient = f.animations.filter(a => /^fx-/.test(a.element.className)); + assert.ok(transient.some(a => a.element.className === "fx-ring")); + assert.ok(transient.some(a => a.element.className === "fx-spark")); + assert.ok(transient.some(a => a.element.className === "fx-delta")); + for (const animation of f.animations) animation.finish(); + await Promise.resolve(); + for (const animation of transient) assert.equal(animation.removedAtCancel, true); + const flash = f.animations.find(a => !/^fx-/.test(a.element.className)); + assert.equal(flash.cancelled, true); + assert.notEqual(flash.removedAtCancel, true, "persistent board elements are not removed"); + f.effects.destroy(); +}); diff --git a/test/resolution-effects.browser.mjs b/test/resolution-effects.browser.mjs new file mode 100644 index 0000000..ee08392 --- /dev/null +++ b/test/resolution-effects.browser.mjs @@ -0,0 +1,56 @@ +// Optional real-browser regression: PLAYWRIGHT_MODULE=/path/to/playwright/index.mjs +// node test/resolution-effects.browser.mjs (or install playwright externally). +// Uses an ephemeral preview server without storagePath; never touches .local. +import assert from "node:assert/strict"; +import { createPreviewServer } from "../preview/server.js"; +const { chromium } = await import(process.env.PLAYWRIGHT_MODULE || "playwright"); +const server = createPreviewServer(); +await new Promise(resolve => server.listen(0, "127.0.0.1", resolve)); +let browser; +try { +browser = await chromium.launch({headless:true}); +const page = await browser.newPage({viewport:{width:1100,height:800}}); +const origin = `http://127.0.0.1:${server.address().port}`; +await page.route(origin + "/", route => route.fulfill({ contentType: "text/html", body: '' })); +await page.goto(origin + "/"); +const result = await page.evaluate(async () => { + const {createResolutionEffects} = await import('/resolution-effects.js'); + document.body.innerHTML = `
A
`; + const root = document.querySelector('#fixture'), pawn=root.querySelector('[data-crew]'); + const before={logEnd:0,turn:1,ship:{crew:[{id:0,station:'white-upper'}]},threats:[]}; + const after={...before,logEnd:1,ship:{crew:[{id:0,station:'blue-upper'}]}}; + const resolution={frames:[before,after],log:[{type:'move',crew:0,from:'white-upper',to:'blue-upper'}]}; + const effects=createResolutionEffects(root,()=>{}); + const next=()=>new Promise(requestAnimationFrame); + let total=0; + const failures=[]; + for(let run=0;run<15;run++) { + effects.reset(); pawn.style.left='100px'; effects.afterRender(resolution,0); effects.beforeRender(); pawn.style.left='500px'; effects.afterRender(resolution,1); + let last=100, sawClone=false, finished=false; + for(let i=0;i<42;i++) { + const clone=root.querySelector('.fx-pawn'); + const visible=getComputedStyle(pawn).visibility !== 'hidden'; + if (clone) { + sawClone=true; + const x=clone.getBoundingClientRect().left-root.getBoundingClientRect().left; + if(visible) failures.push({run,i,error:'destination visible with clone'}); + if(x server.close(resolve)); +} diff --git a/test/tactical.test.js b/test/tactical.test.js new file mode 100644 index 0000000..269de2e --- /dev/null +++ b/test/tactical.test.js @@ -0,0 +1,41 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { pictogram } from "../preview/icons.js"; +import { createTacticalView } from "../preview/tactical.js"; +import { createLesson } from "../src/tutorials.js"; +import { loadLocale, translate } from "../preview/i18n.js"; +import { tutorialTextHtml } from "../preview/tutorial-text.js"; + +test("shared action glyphs have distinct accents without changing their silhouettes", () => { + for (const [action, accent, shape] of [["A", "fire", "laser"], ["B", "energy", "reactor"], ["C", "systems", "systems"]]) { + assert.match(pictogram(action), new RegExp(`action-${accent}`)); + assert.equal(pictogram(action).match(/