A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
ui: keyboard focus scrolls its ScrollView to the focused element (refs #41) (#526)
Eyal Golan2d438a0e392f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ca077a659..a2205efe1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -390,6 +390,9 @@ adds a line under **Unreleased**; CI's `Changelog` job checks this (see `CONTRIBCabinet's "Ordered:" line wraps, and on short windows the Prime Minister's portrait gives way, framed again for its newheight, so the candidate list keeps two rows; at 32:9 the list's floor follows the room left (M7). Presentation only:no golden moves.+- Keyboard focus that lands on something scrolled out of view, such as a Cabinet card below the first row or a+ candidate far down the list, now scrolls its list to it (accessibility audit H1, refs #41). Focus that follows a mouse+ press leaves the list where it is. Presentation only: no golden moves.- "The Mediator Assassinated" cites the Official Gazette text of the Prevention of Terrorism Ordinance for its number,No. 33 of 1948, which no source on the card gave. Comment and source row only (refs #442).- Five recorded contradictions settled from primary sources. "The Second Truce": the Acting Mediator's report ofdiff --git a/unity/Assets/Scripts/UI/FocusScroll.cs b/unity/Assets/Scripts/UI/FocusScroll.csnew file mode 100644index 000000000..0304aee3c--- /dev/null+++ b/unity/Assets/Scripts/UI/FocusScroll.cs@@ -0,0 +1,88 @@+#nullable enable+using UnityEngine;+using UnityEngine.UIElements;++namespace Statecraft.Game.UI+{+ /// <summary>Keeps keyboard focus in sight (accessibility audit H1, #41). The Cabinet's cards and candidates and the+ /// Budget's rows are ScrollViews, and Tab moved focus onto rows below the visible area without moving the view. One+ /// FocusInEvent callback at the UI root scrolls the focused element's nearest ScrollView to it when it is not wholly+ /// inside the viewport: every ScrollView, the ones added later included. Focus that follows a pointer press is left+ /// alone, so a click on a half-visible card never jolts the list: a pointer-down marks the press, and the next key or+ /// navigation event clears the mark. Programmatic focus (a card taking focus, focus returned after a screen closes)+ /// scrolls as keyboard focus does, unless the last input was a pointer press: a mouse player's lists never move. A target with no layout yet (rows just rebuilt) is checked again once it is+ /// laid out.</summary>+ public sealed class FocusScroll : System.IDisposable+ {+ readonly VisualElement root;+ readonly EventCallback<PointerDownEvent> onDown;+ readonly EventCallback<KeyDownEvent> onKey;+ readonly EventCallback<NavigationMoveEvent> onMove;+ readonly EventCallback<FocusInEvent> onFocus;+ bool pointer;++ public FocusScroll(VisualElement root)+ {+ this.root = root;+ onDown = _ => pointer = true;+ onKey = _ => pointer = false;+ onMove = _ => pointer = false;+ onFocus = e => { if (!pointer && e.target is VisualElement t) Follow(t); };+ root.RegisterCallback(onDown, TrickleDown.TrickleDown);+ root.RegisterCallback(onKey, TrickleDown.TrickleDown);+ root.RegisterCallback(onMove, TrickleDown.TrickleDown);+ root.RegisterCallback(onFocus, TrickleDown.TrickleDown);+ }++ public void Dispose()+ {+ root.UnregisterCallback(onDown, TrickleDown.TrickleDown);+ root.UnregisterCallback(onKey, TrickleDown.TrickleDown);+ root.UnregisterCallback(onMove, TrickleDown.TrickleDown);+ root.UnregisterCallback(onFocus, TrickleDown.TrickleDown);+ }++ /// <summary>Scrolls the target's nearest ScrollView to it when it is not wholly in view. When that can't be settled+ /// at once (no layout yet, or ScrollTo clamped by a scroll range that lags a layout that just grew the list), checks+ /// again whenever the target, the view's content or its viewport is laid out again (registered after the+ /// ScrollView's own callbacks, so its range is up to date by then), and on each of the next few updates, until the+ /// target is in view or loses the focus.</summary>+ static void Follow(VisualElement target)+ {+ if (Settled(target)) return;+ var view = target.GetFirstAncestorOfType<ScrollView>()!;+ var watched = new[] { target, view.contentContainer, view.contentViewport };+ int ticks = 0, layouts = 0; bool done = false;+ EventCallback<GeometryChangedEvent>? onLayout = null;+ void Stop() { done = true; foreach (var e in watched) e.UnregisterCallback(onLayout!); }+ void Check(bool tick)+ {+ if (done) return;+ if (tick && ++ticks > TickRetries) return; // the per-update backup is spent; layouts still count+ if (!tick && ++layouts > LayoutRetries) { Stop(); return; }+ if (target.focusController?.focusedElement != target || Settled(target)) Stop();+ }+ onLayout = _ => Check(false);+ foreach (var e in watched) e.RegisterCallback(onLayout);+ target.schedule.Execute(() => Check(true)).Every(0).Until(() => done || ticks > TickRetries);+ }++ /// <summary>How many updates, and how many layouts of the watched elements, Follow keeps checking.</summary>+ const int TickRetries = 10, LayoutRetries = 20;++ /// <summary>True when there is nothing (more) to do: the target has no ScrollView, or it is wholly in view. Otherwise+ /// scrolls to it if it and its view are laid out, and returns false so the caller checks again.</summary>+ static bool Settled(VisualElement target)+ {+ var view = target.GetFirstAncestorOfType<ScrollView>();+ if (view == null) return true;+ Rect r = target.worldBound, v = view.contentViewport.worldBound;+ if (!LaidOut(r) || !LaidOut(v)) return false;+ if (r.yMin >= v.yMin - 0.5f && r.yMax <= v.yMax + 0.5f && r.xMin >= v.xMin - 0.5f && r.xMax <= v.xMax + 0.5f) return true;+ view.ScrollTo(target);+ return false;+ }++ static bool LaidOut(Rect r) => !float.IsNaN(r.width) && !float.IsNaN(r.height) && r.width > 0f && r.height > 0f;+ }+}diff --git a/unity/Assets/Scripts/UI/FocusScroll.cs.meta b/unity/Assets/Scripts/UI/FocusScroll.cs.metanew file mode 100644index 000000000..b08589d01--- /dev/null+++ b/unity/Assets/Scripts/UI/FocusScroll.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: ef40dd4ba3fba400cb1ae3dff81f28b6\ No newline at end of filediff --git a/unity/Assets/Scripts/UI/GameRoot.cs b/unity/Assets/Scripts/UI/GameRoot.csindex 87eeca0c8..f61d47132 100644--- a/unity/Assets/Scripts/UI/GameRoot.cs+++ b/unity/Assets/Scripts/UI/GameRoot.cs@@ -144,6 +144,7 @@ namespace Statecraft.Game.UIOwn(new HudPresenter(root, bridge, text));nav = Own(new ScreenNav(root)); // every screen starts hidden (USS); ScreenNav opens one at a timeOwn(new PointerBlur(root)); // a mouse click leaves no focus fill behind (keyboard keeps it)+ Own(new FocusScroll(root)); // keyboard focus scrolls its ScrollView to it (a11y H1)Own(new NavigationGuard(root)); // the camera keys (WASD, arrows) never move UI focus (B6)if (DiagLog.Nav) Own(new NavEventLog(root)); // ?navlog: every UI pointer/submit event (playtest 2, P2-4)// The Illustration switch's silent loops (event-videos.yaml, Resources): none in the automated runs (CardVideo.ForcedOff).diff --git a/unity/Assets/Tests/EditMode/FocusScrollTests.cs b/unity/Assets/Tests/EditMode/FocusScrollTests.csnew file mode 100644index 000000000..a316f67bd--- /dev/null+++ b/unity/Assets/Tests/EditMode/FocusScrollTests.cs@@ -0,0 +1,174 @@+#nullable enable+using System;+using System.Collections;+using System.Collections.Generic;+using System.Linq;+using NUnit.Framework;+using Statecraft.Game;+using Statecraft.Game.UI;+using Statecraft.Sim;+using UnityEditor;+using UnityEngine;+using UnityEngine.TestTools;+using UnityEngine.UIElements;+using Object = UnityEngine.Object;++/// <summary>Accessibility audit H1 (#41): keyboard focus that lands on an element scrolled out of a ScrollView brings it into+/// view (FocusScroll); focus that follows a pointer press leaves the scroll position alone, so a click never jolts a list.</summary>+public class FocusScrollTests+{+ static readonly Content C = ContentLoader.Load(Paths.Content);+ static UiText Text => UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.Strings).text);++ /// <summary>A real panel of w x h pixels, with the game's UXML (or an empty tree) and a FocusScroll at its root.</summary>+ sealed class Rig : IDisposable+ {+ public readonly VisualElement Root;+ readonly GameObject go; readonly PanelSettings ps; readonly RenderTexture rt;+ readonly List<IDisposable> owned = new List<IDisposable>();++ public Rig(int w, int h, bool game = true)+ {+ rt = new RenderTexture(w, h, 0);+ ps = Object.Instantiate(AssetDatabase.LoadAssetAtPath<PanelSettings>(UiPaths.Panel));+ ps.targetTexture = rt;+ go = new GameObject("FocusScrollTest");+ go.SetActive(false);+ var doc = go.AddComponent<UIDocument>();+ doc.panelSettings = ps;+ if (game) doc.visualTreeAsset = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(UiPaths.GameUxml);+ go.SetActive(true);+ Root = doc.rootVisualElement;+ Root.Q("root")?.RemoveFromClassList("loading");+ Own(new FocusScroll(Root));+ }++ public T Own<T>(T d) where T : IDisposable { owned.Add(d); return d; }++ public Focusable? Focused => Root.panel.focusController.focusedElement;++ public void Dispose()+ {+ for (int i = owned.Count - 1; i >= 0; i--) owned[i].Dispose();+ Object.DestroyImmediate(go); Object.DestroyImmediate(ps); rt.Release(); Object.DestroyImmediate(rt);+ }+ }++ /// <summary>The historical game on 26 February 1950 (as CabinetScreenTests): a full cabinet, more cards than one row.</summary>+ static SimBridge In1950()+ {+ var g = GameSession.New(C, GoldenRun.Seed, Mode.Historical);+ while (g.State.Date < new DateTime(1950, 2, 1)) g.Step(HistoricalAI.Commands(C, g.State));+ return new SimBridge(g, Text);+ }++ static IEnumerator Frames(int n) { for (int i = 0; i < n; i++) yield return null; }++ static bool Inside(VisualElement e, ScrollView view)+ {+ Rect r = e.worldBound, v = view.contentViewport.worldBound;+ return r.yMin >= v.yMin - 0.5f && r.yMax <= v.yMax + 0.5f;+ }++ static void Tab(VisualElement from)+ {+ using (var e = NavigationMoveEvent.GetPooled(NavigationMoveEvent.Direction.Next)) { e.target = from; from.SendEvent(e); }+ }++ /// <summary>The Cabinet open in the playtest window (1568x752), its cards laid out, and the first card below the view.</summary>+ static IEnumerator OpenCabinet(Rig r, List<Button> cards, Action<int> below)+ {+ var bridge = In1950();+ var nav = r.Own(new ScreenNav(r.Root));+ r.Own(new CabinetPresenter(r.Root, bridge, Text, null));+ nav.Open("cabinet");+ yield return Frames(4);+ var seats = r.Root.Q<ScrollView>("cabinet-seats");+ cards.AddRange(seats.contentContainer.Query<Button>().Where(b => b.canGrabFocus).ToList());+ int k = cards.FindIndex(b => !Inside(b, seats));+ Assert.Greater(k, 0, "precondition: the first row shows and a later card is below the view");+ Assert.Less(k + 1, cards.Count, "precondition: a card after the first hidden one");+ Assert.AreEqual(0f, seats.scrollOffset.y, "precondition: the list starts at the top");+ below(k);+ }++ [UnityTest]+ public IEnumerator TabOntoACardBelowTheViewScrollsTheCardsToIt()+ {+ using var r = new Rig(1568, 752);+ var cards = new List<Button>(); int k = -1;+ yield return OpenCabinet(r, cards, i => k = i);+ var seats = r.Root.Q<ScrollView>("cabinet-seats");+ cards[k - 1].Focus();+ yield return Frames(2);+ Assert.AreSame(cards[k - 1], r.Focused, "precondition: the last card in view has the focus");+ Assert.AreEqual(0f, seats.scrollOffset.y, "focus on a card already in view does not scroll");++ Tab(cards[k - 1]);+ yield return Frames(3);+ Assert.AreSame(cards[k], r.Focused, "Tab moves on to the first card below the view");+ Assert.Greater(seats.scrollOffset.y, 0f, "the cards scrolled");+ Assert.IsTrue(Inside(cards[k], seats), $"the focused card {cards[k].worldBound} is inside the view {seats.contentViewport.worldBound}");+ }++ [UnityTest]+ public IEnumerator FocusAfterAPointerPressLeavesTheCardsWhereTheyAre()+ {+ using var r = new Rig(1568, 752);+ var cards = new List<Button>(); int k = -1;+ yield return OpenCabinet(r, cards, i => k = i);+ var seats = r.Root.Q<ScrollView>("cabinet-seats");+ var card = cards[k];+ using (var down = PointerDownEvent.GetPooled(new Event { type = EventType.MouseDown, button = 0, mousePosition = card.worldBound.center }))+ { down.target = card; card.SendEvent(down); }+ card.Focus();+ yield return Frames(3);+ Assert.AreSame(card, r.Focused, "precondition: the pressed card has the focus");+ Assert.AreEqual(0f, seats.scrollOffset.y, "a pointer press does not scroll the list");++ // The next key press is the keyboard again: Tab on to the next card scrolls to it.+ Tab(card);+ yield return Frames(3);+ Assert.AreSame(cards[k + 1], r.Focused, "precondition: Tab moved on");+ Assert.IsTrue(Inside(cards[k + 1], seats), "after a key, focus scrolls again");+ }++ [UnityTest]+ public IEnumerator FocusOnTheLastCandidateScrollsTheCandidateList()+ {+ using var r = new Rig(1920, 1080);+ var bridge = In1950();+ var nav = r.Own(new ScreenNav(r.Root));+ var cabinet = r.Own(new CabinetPresenter(r.Root, bridge, Text, null));+ nav.Open("cabinet");+ cabinet.Select("finance_minister");+ yield return Frames(4);+ var list = r.Root.Q<ScrollView>("cabinet-candidates");+ Assert.Greater(list.contentViewport.worldBound.height, 40f, "precondition: the candidate list has room to show a row");+ var last = list.contentContainer.Query<Button>().Where(b => b.canGrabFocus).Last();+ Assert.IsFalse(Inside(last, list), "precondition: the last candidate that can be appointed is below the view");+ last.Focus();+ yield return Frames(3);+ Assert.AreSame(last, r.Focused, "precondition: focused");+ Assert.IsTrue(Inside(last, list), $"the candidate {last.worldBound} is inside the view {list.contentViewport.worldBound}");+ }++ /// <summary>Focus given in the same frame the rows are made (before any layout) still scrolls, once they are laid out.</summary>+ [UnityTest]+ public IEnumerator FocusBeforeLayoutScrollsOnceLaidOut()+ {+ using var r = new Rig(800, 600, game: false);+ var view = new ScrollView { style = { height = 100, width = 200 } };+ r.Root.Add(view);+ yield return Frames(2);+ int focusIns = 0;+ r.Root.RegisterCallback<FocusInEvent>(_ => focusIns++);+ Button? last = null;+ for (int i = 0; i < 20; i++) view.Add(last = new Button { text = "row " + i, style = { height = 30 } });+ last!.Focus();+ for (int i = 0; i < 30 && !(r.Focused == last && Inside(last, view)); i++) yield return null;+ Assert.AreSame(last, r.Focused, "precondition: focused");+ Assert.IsTrue(Inside(last, view), $"the row {last.worldBound} is inside the view {view.contentViewport.worldBound} " ++ $"(offset {view.scrollOffset.y}, range {view.verticalScroller.lowValue} to {view.verticalScroller.highValue}, {focusIns} focus-in)");+ }+}diff --git a/unity/Assets/Tests/EditMode/FocusScrollTests.cs.meta b/unity/Assets/Tests/EditMode/FocusScrollTests.cs.metanew file mode 100644index 000000000..532612cee--- /dev/null+++ b/unity/Assets/Tests/EditMode/FocusScrollTests.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 9fae763517f0d4aee9d0e751336cd9fd\ No newline at end of file