A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
#nullable enable
using System;
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.UIElements;
using Object = UnityEngine.Object;
/// <summary>#1170: sharing a post with a screenshot. The post text in both languages with the in-game date and turn, the
/// share links' encoding, the 1920 px cap on the picture, and the panel: it captures before it shows, previews the picture,
/// offers the browser's share sheet where files can be shared and otherwise the download, and the site buttons (#1237):
/// share links, and Instagram, which has none. Through ShareShot's injectable hooks, so nothing is captured, saved or
/// opened for real.</summary>
public class ShareShotTests
{
static readonly Content C = ContentLoader.Load(Paths.Content);
static UiText En => UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.Strings).text);
static UiText He => UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.StringsHebrew).text, "strings.he.yaml");
/// <summary>The post carries the itch page and the GitHub repository (owner, 24 Oct 2026: "when a user shares a post it
/// will include a link to the game on itch and to the github repo").</summary>
[Test]
public void ThePostNamesTheGameTheDateTheTurnTheItchPageAndTheRepository()
{
Assert.AreEqual("https://github.com/eyalgolan/statecraft-israel", ShareShot.Repo);
Assert.AreEqual("I'm playing Israel in 1948 in Statecraft: Israel, a free strategy game. 15 May 1948, turn 0. "
+ "Play: https://eyalgolan.itch.io/statecraft-israel · Code: https://github.com/eyalgolan/statecraft-israel",
ShareShot.Text(En, "15 May 1948", 0));
var he = ShareShot.Text(He, "15 במאי 1948", 3);
StringAssert.Contains("15 במאי 1948", he);
StringAssert.Contains("3", he);
StringAssert.Contains("https://eyalgolan.itch.io/statecraft-israel", he);
StringAssert.Contains("https://github.com/eyalgolan/statecraft-israel", he);
Assert.IsTrue(UiDirection.HasRightToLeft(he), "the Hebrew post is Hebrew");
}
/// <summary>Playtest, 25 Oct 2026: in the Hebrew panel "https://" ended one line and the rest of the URL began the next.
/// The label puts a word joiner after each break point inside a URL ('/', ':', '.', '-'), so no line break falls inside
/// it; English is shown as shared, and what is shared and copied never carries the joiners.</summary>
[Test]
public void TheHebrewPanelKeepsEachUrlOnOneLine()
{
var en = ShareShot.Text(En, "15 November 1948", 6);
Assert.AreEqual(en, ShareShot.Shown(en, false), "English unchanged");
var he = ShareShot.Text(He, "15 בנובמבר 1948", 6);
var shown = ShareShot.Shown(he, true);
var j = ShareShot.WordJoiner.ToString();
StringAssert.Contains($"https:{j}/{j}/{j}eyalgolan.{j}itch.{j}io/{j}statecraft-{j}israel", shown);
StringAssert.Contains($"https:{j}/{j}/{j}github.{j}com/{j}eyalgolan/{j}statecraft-{j}israel", shown);
Assert.AreEqual(he, shown.Replace(j, ""), "nothing else changes");
StringAssert.DoesNotContain(j, he, "the shared post carries no joiner");
}
/// <summary>X's limit is 280 by its own count (twitter-text v3): any URL is 23, a character in its light ranges (Latin,
/// Hebrew, most punctuation) is 1 and any other (the bidi marks Format puts round the URLs) is 2. The longest real post,
/// the last turn's longest date (rules.yaml ends the game on 15 January 1952), fits in both languages.</summary>
[Test]
public void TheLongestPostFitsInAPostOnX([Values(false, true)] bool hebrew)
{
var text = hebrew ? He : En;
var date = hebrew ? "30 בספטמבר 1951" : "30 September 1951";
var post = ShareShot.Text(text, date, 999);
StringAssert.Contains(date, post);
Assert.LessOrEqual(XLength(post), 280, post);
}
static int XLength(string post)
{
var parts = post.Split(new[] { ShareShot.Itch, ShareShot.Repo }, StringSplitOptions.None);
int n = 23 * (parts.Length - 1);
foreach (var c in string.Concat(parts)) n += c <= 4351 || (c >= 8192 && c <= 8205) || (c >= 8208 && c <= 8223) || (c >= 8242 && c <= 8247) ? 1 : 2;
return n;
}
/// <summary>Every share path carries both links where the site takes a text: the share sheet and Copy get the post (the
/// panel tests), X, WhatsApp and Telegram its text. Facebook and LinkedIn take only a URL, the itch page.</summary>
[Test]
public void TheTextLinksCarryTheItchPageAndTheRepository([Values(false, true)] bool hebrew)
{
var post = ShareShot.Text(hebrew ? He : En, "15 May 1948", 0);
foreach (var site in new[] { "x", "whatsapp", "telegram" })
{
var link = Uri.UnescapeDataString(ShareShot.IntentUrl(site, post));
StringAssert.Contains(ShareShot.Itch, link, site);
StringAssert.Contains(ShareShot.Repo, link, site);
}
var itch = Uri.EscapeDataString(ShareShot.Itch);
Assert.AreEqual("https://www.facebook.com/sharer/sharer.php?u=" + itch, ShareShot.IntentUrl("facebook", post));
Assert.AreEqual("https://www.linkedin.com/sharing/share-offsite/?url=" + itch, ShareShot.IntentUrl("linkedin", post));
}
[Test]
public void TheShareLinksCarryTheTextAndTheUrlEncoded()
{
const string text = "Play: a & b #1, 15 במאי";
var enc = Uri.EscapeDataString(text); var url = Uri.EscapeDataString(ShareShot.Itch);
Assert.AreEqual("https://x.com/intent/post?text=" + enc, ShareShot.IntentUrl("x", text));
Assert.AreEqual("https://www.facebook.com/sharer/sharer.php?u=" + url, ShareShot.IntentUrl("facebook", text));
Assert.AreEqual("https://wa.me/?text=" + enc, ShareShot.IntentUrl("whatsapp", text));
Assert.AreEqual("https://t.me/share/url?url=" + url + "&text=" + enc, ShareShot.IntentUrl("telegram", text));
Assert.AreEqual("https://www.linkedin.com/sharing/share-offsite/?url=" + url, ShareShot.IntentUrl("linkedin", text));
StringAssert.Contains("a%20%26%20b%20%231", enc, "'&' and '#' never end the query early");
}
/// <summary>#1237: the owner's list, in the owner's order; LinkedIn stays, at the end (owner, 21 Oct 2026). Instagram has
/// no web share link.</summary>
[Test]
public void TheSitesAreTheOwnersListInOrder()
{
CollectionAssert.AreEqual(new[] { "x", "facebook", "instagram", "whatsapp", "telegram", "linkedin" }, ShareShot.Sites);
Assert.Throws<ArgumentException>(() => ShareShot.IntentUrl("instagram", "a"), "Instagram has no share link");
using var ui = new UiTestKit();
var row = ui.Q<VisualElement>("share-x").parent;
CollectionAssert.AreEqual(Array.ConvertAll(ShareShot.Sites, s => "share-" + s), row.Children().Select(c => c.name).ToArray(),
"the panel shows the buttons in the list's order");
}
[Test]
public void ThePictureIsCappedAt1920OnTheLongSide()
{
Assert.AreEqual(new Vector2Int(1280, 720), ShareShot.Fit(1280, 720));
Assert.AreEqual(new Vector2Int(1920, 1080), ShareShot.Fit(3840, 2160));
Assert.AreEqual(new Vector2Int(887, 1920), ShareShot.Fit(1170, 2532), "a phone held upright, DPR 3");
var big = new Texture2D(3000, 1000, TextureFormat.RGB24, false);
try
{
var png = ShareShot.Encode(big);
var back = new Texture2D(2, 2);
Assert.IsTrue(back.LoadImage(png));
Assert.AreEqual(1920, back.width); Assert.AreEqual(640, back.height);
Object.DestroyImmediate(back);
}
finally { Object.DestroyImmediate(big); }
}
[Test]
public void TheDownloadIsNamedForTheInGameDate()
{
Assert.AreEqual("statecraft-1948-05-15.png", ShareShot.FileName(new DateTime(1948, 5, 15)));
}
/// <summary>The Settings Share button: the frame is captured before the panel shows, then kept for the browser; where it
/// can share files the panel offers Share (the share sheet gets the picture and post text, which carries both links), elsewhere the same
/// button downloads the picture and the "attach" note shows. The site buttons show either way. Esc closes it.</summary>
[Test]
public void SharingCapturesFirstAndOffersTheSheetOrTheFallback([Values(false, true)] bool canShareFiles, [Values(false, true)] bool hebrew)
{
var text = hebrew ? He : En;
var opened = new List<string>(); var kept = new List<string>(); var shared = new List<string>();
bool shownAtCapture = true;
ShareShot.Copy = _ => { };
ExternalLink.Opener = opened.Add;
ShareShot.Keep = (png, name) => kept.Add(name);
ShareShot.CanShareFiles = () => canShareFiles;
ShareShot.Share = post => shared.Add(post);
try
{
using var ui = new UiTestKit();
var bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), text);
SharePresenter? made = null;
using var share = made = new SharePresenter(ui.Root, bridge, text, done =>
{
shownAtCapture = made!.IsOpen;
done(new byte[] { 1, 2, 3 });
});
var button = ui.Q<Button>("settings-share");
Assert.AreEqual(text["share.open"], button.text);
UiTestKit.Press(button);
Assert.IsFalse(shownAtCapture, "the panel is not in the picture");
Assert.IsTrue(share.IsOpen);
CollectionAssert.AreEqual(new[] { "statecraft-1948-05-15.png" }, kept);
var post = ShareShot.Text(text, HudModel.From(bridge, text).Date, bridge.State.Turn);
Assert.AreEqual(ShareShot.Shown(post, hebrew), ui.Q<Label>("share-post").text, "the panel shows the post");
Assert.IsFalse(ui.Q<VisualElement>("screen-settings").enabledSelf, "out of Tab's reach under the panel");
var fallback = ui.Q<VisualElement>("share-fallback");
Assert.AreEqual(DisplayStyle.None, fallback.style.display.value, "no attach note before the press");
for (VisualElement? e = ui.Q<Button>("share-x"); e != null && e.name != "share-panel"; e = e.parent)
Assert.AreNotEqual(DisplayStyle.None, e.style.display.value, $"the site buttons show from the start ({e.name})");
Assert.AreEqual(canShareFiles ? text["share.native"] : text["share.download"], ui.Q<Button>("share-go").text);
SettingsScreenTests.PressWithPointer(ui.Q<Button>("share-go"));
CollectionAssert.AreEqual(new[] { post }, shared, "the press asks the browser once");
StringAssert.Contains(ShareShot.Repo, post, "the share sheet's text carries the repository too");
Assert.AreEqual(canShareFiles ? DisplayStyle.None : DisplayStyle.Flex, fallback.style.display.value,
"the attach note only where files cannot be shared");
var links = ShareShot.Sites.Where(s => s != "instagram").ToArray();
foreach (var site in links) UiTestKit.Press(ui.Q<Button>("share-" + site));
CollectionAssert.AreEqual(links.Select(s => ShareShot.IntentUrl(s, post)), opened);
Assert.AreEqual(text["share.attach"], ui.Q<Label>("share-attach").text);
var go = ui.Q<Button>("share-go");
using (var esc = NavigationCancelEvent.GetPooled()) { esc.target = go; go.SendEvent(esc); }
Assert.IsFalse(share.IsOpen, "Esc closes it");
Assert.IsTrue(ui.Q<VisualElement>("screen-settings").enabledSelf);
}
finally
{
ExternalLink.Opener = ExternalLink.Default; ShareShot.Copy = ShareShot.DefaultCopy;
ShareShot.Keep = ShareShot.DefaultKeep; ShareShot.CanShareFiles = ShareShot.DefaultCanShareFiles; ShareShot.Share = ShareShot.DefaultShare;
}
}
/// <summary>#1237: Instagram has no share link. Where the browser can share files its button opens the share sheet with
/// the picture, as Share does; elsewhere the same press downloads the picture and a note says to post it from the
/// Instagram app. On the press, as Share (the web build arms its one-shot release listener then); nothing opens before.</summary>
[Test]
public void InstagramOpensTheSheetOrDownloadsWithANote([Values(false, true)] bool canShareFiles, [Values(false, true)] bool hebrew,
[Values(false, true)] bool keyboard)
{
var text = hebrew ? He : En;
var opened = new List<string>(); var shared = new List<string>();
ExternalLink.Opener = opened.Add;
ShareShot.Keep = (png, name) => { };
ShareShot.CanShareFiles = () => canShareFiles;
ShareShot.Share = post => shared.Add(post);
try
{
using var ui = new UiTestKit();
var bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), text);
using var share = new SharePresenter(ui.Root, bridge, text, done => done(new byte[] { 1 }));
UiTestKit.Press(ui.Q<Button>("settings-share"));
var button = ui.Q<Button>("share-instagram");
var note = ui.Q<Label>("share-instagram-note");
Assert.AreEqual("Instagram", button.text, "a brand, the same in every language");
Assert.AreEqual(DisplayStyle.None, note.style.display.value, "no note before the press");
CollectionAssert.IsEmpty(shared, "nothing is shared before the press");
if (keyboard) UiTestKit.Press(button); else SettingsScreenTests.PressWithPointer(button);
var post = ShareShot.Text(text, HudModel.From(bridge, text).Date, bridge.State.Turn);
CollectionAssert.AreEqual(new[] { post }, shared, "the share sheet, or the download, once");
CollectionAssert.IsEmpty(opened, "no web page: Instagram has no share link");
Assert.AreEqual(canShareFiles ? DisplayStyle.None : DisplayStyle.Flex, note.style.display.value,
"the note only where the picture downloaded");
Assert.AreEqual(text["share.instagram"], note.text);
Assert.AreEqual(DisplayStyle.None, ui.Q<VisualElement>("share-fallback").style.display.value, "not the other sites' note");
}
finally
{
ExternalLink.Opener = ExternalLink.Default;
ShareShot.Keep = ShareShot.DefaultKeep; ShareShot.CanShareFiles = ShareShot.DefaultCanShareFiles; ShareShot.Share = ShareShot.DefaultShare;
}
}
/// <summary>#1237: the panel previews the picture it shares, from the captured PNG. The texture is released when the
/// panel closes, so none is left over between opens; a PNG that does not decode shows no preview.</summary>
[Test]
public void ThePanelPreviewsThePictureAndReleasesItOnClose()
{
ShareShot.Keep = (png, name) => { };
var frame = new Texture2D(64, 36, TextureFormat.RGB24, false);
var real = frame.EncodeToPNG();
Object.DestroyImmediate(frame);
byte[] png = real;
try
{
using var ui = new UiTestKit();
var bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), En);
var share = new SharePresenter(ui.Root, bridge, En, done => done(png));
var preview = ui.Q<VisualElement>("share-preview");
UiTestKit.Press(ui.Q<Button>("settings-share"));
var first = preview.style.backgroundImage.value.texture;
Assert.IsNotNull(first, "the preview shows the picture");
Assert.AreEqual(64, first.width); Assert.AreEqual(36, first.height);
Assert.AreEqual(DisplayStyle.Flex, preview.style.display.value);
UiTestKit.Press(ui.Q<Button>("share-close"));
Assert.IsTrue(first == null, "released on Close");
Assert.IsNull(preview.style.backgroundImage.value.texture);
UiTestKit.Press(ui.Q<Button>("settings-share"));
var second = preview.style.backgroundImage.value.texture;
Assert.IsNotNull(second, "a new picture on the next open");
share.Dispose();
Assert.IsTrue(second == null, "released when the UI is rebuilt with the panel open");
png = new byte[] { 1, 2, 3 };
using var again = new SharePresenter(ui.Root, bridge, En, done => done(png));
UiTestKit.Press(ui.Q<Button>("settings-share"));
Assert.IsTrue(again.IsOpen, "the panel still opens");
Assert.AreEqual(DisplayStyle.None, preview.style.display.value, "no preview for a picture that does not decode");
Assert.IsNull(preview.style.backgroundImage.value.texture);
}
finally { ShareShot.Keep = ShareShot.DefaultKeep; }
}
/// <summary>With the unit fixture's injected ScreenNav hook, Esc in the share panel closes the panel only:
/// ScreenNav's Cancel handler trickles down from the root before the panel's own and asks the panel first.</summary>
[Test]
public void AnInjectedScreenNavHookLeavesSettingsUnderTheSharePanelOpen()
{
ShareShot.Keep = (png, name) => { };
try
{
using var ui = new UiTestKit();
var bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), En);
using var nav = new ScreenNav(ui.Root);
using var share = new SharePresenter(ui.Root, bridge, En, done => done(new byte[] { 1 }));
nav.TakesEscape = share.Escape;
nav.Open("settings");
UiTestKit.Press(ui.Q<Button>("settings-share"));
Assert.IsTrue(share.IsOpen);
var go = ui.Q<Button>("share-go");
using (var esc = NavigationCancelEvent.GetPooled()) { esc.target = go; go.SendEvent(esc); }
Assert.IsFalse(share.IsOpen, "Esc closes the panel");
Assert.AreEqual("settings", nav.Current, "and only the panel");
}
finally { ShareShot.Keep = ShareShot.DefaultKeep; }
}
/// <summary>A share sheet the browser refused on the release (not a cancel): the picture downloaded instead, and the
/// note to attach it shows (ShareShot.Failed, polled by the panel's scheduler). A failed capture opens nothing and leaves
/// Share working.</summary>
[UnityEngine.TestTools.UnityTest]
public System.Collections.IEnumerator ARefusedShareSheetShowsTheShareLinks()
{
bool failed = false, broken = true;
ShareShot.Keep = (png, name) => { }; ShareShot.CanShareFiles = () => true; ShareShot.Share = _ => { };
ShareShot.Failed = () => failed;
var ui = new UiTestKit();
try
{
var bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), En);
using var share = new SharePresenter(ui.Root, bridge, En, done => done(broken ? null : new byte[] { 1 }));
UiTestKit.Press(ui.Q<Button>("settings-share"));
Assert.IsFalse(share.IsOpen, "no picture, no panel");
broken = false;
UiTestKit.Press(ui.Q<Button>("settings-share"));
Assert.IsTrue(share.IsOpen, "the next press works");
SettingsScreenTests.PressWithPointer(ui.Q<Button>("share-go"));
var fallback = ui.Q<VisualElement>("share-fallback");
Assert.AreEqual(DisplayStyle.None, fallback.style.display.value, "the sheet is open: no note yet");
failed = true;
var until = Time.realtimeSinceStartup + 5f; // the panel looks every 250 ms
while (fallback.style.display.value != DisplayStyle.Flex && Time.realtimeSinceStartup < until) yield return null;
Assert.AreEqual(DisplayStyle.Flex, fallback.style.display.value, "refused: the attach note shows");
}
finally
{
ui.Dispose();
ShareShot.Keep = ShareShot.DefaultKeep; ShareShot.CanShareFiles = ShareShot.DefaultCanShareFiles;
ShareShot.Share = ShareShot.DefaultShare; ShareShot.Failed = ShareShot.DefaultFailed;
}
}
/// <summary>#1238: Copy asks the browser once, on the player's press, to copy the picture; the browser falls back to the
/// post text (with the itch link) and reports which one landed, or that neither did (ShareShot.jslib, in that order).
/// The panel says which, in both languages, polling ShareShot.Copied as it polls Failed; nothing shows while the copy
/// is still pending, and on a failure the Share or Download button stays where it was. The order itself (picture, then
/// text, then the error) lives in the jslib's promises, which an edit-mode test cannot run; the PR's browser check
/// covers it.</summary>
[UnityEngine.TestTools.UnityTest]
public System.Collections.IEnumerator CopySaysWhetherThePictureOrTheTextWasCopied(
[Values(ShareShot.CopyResult.Picture, ShareShot.CopyResult.Text, ShareShot.CopyResult.Failed)] ShareShot.CopyResult result,
[Values(false, true)] bool hebrew)
{
var text = hebrew ? He : En;
var copies = new List<string>();
var copied = ShareShot.CopyResult.Pending;
ShareShot.Keep = (png, name) => { }; ShareShot.Share = _ => { };
ShareShot.Copy = copies.Add; ShareShot.Copied = () => copied;
var ui = new UiTestKit();
try
{
var bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), text);
using var share = new SharePresenter(ui.Root, bridge, text, done => done(new byte[] { 1 }));
UiTestKit.Press(ui.Q<Button>("settings-share"));
var copy = ui.Q<Button>("share-copy");
var said = ui.Q<Label>("share-copied");
Assert.IsNotNull(copy, "the panel has a Copy button");
Assert.AreEqual(text["share.copy"], copy.text);
Assert.AreEqual(DisplayStyle.None, said.style.display.value, "nothing to say before the press");
SettingsScreenTests.PressWithPointer(copy);
CollectionAssert.AreEqual(new[] { ShareShot.Text(text, HudModel.From(bridge, text).Date, bridge.State.Turn) }, copies,
"one copy, of the post (not the label's joiners), on the press");
StringAssert.Contains(ShareShot.Itch, copies[0], "the copied text links the itch page");
StringAssert.Contains(ShareShot.Repo, copies[0], "and the repository");
// The batch editor idles between frames unless asked for one, and the panel's scheduler runs on those frames.
var until = Time.realtimeSinceStartup + 0.6f;
while (Time.realtimeSinceStartup < until) { EditorApplication.QueuePlayerLoopUpdate(); yield return null; }
Assert.AreEqual(DisplayStyle.None, said.style.display.value, "still pending after a few looks: nothing yet");
copied = result;
until = Time.realtimeSinceStartup + 4f; // the panel looks every 250 ms
while (said.style.display.value != DisplayStyle.Flex && Time.realtimeSinceStartup < until) { EditorApplication.QueuePlayerLoopUpdate(); yield return null; }
Assert.AreEqual(DisplayStyle.Flex, said.style.display.value);
var key = result switch { ShareShot.CopyResult.Picture => "share.copied_picture", ShareShot.CopyResult.Text => "share.copied_text", _ => "share.copy_failed" };
Assert.AreEqual(text[key], said.text);
var go = ui.Q<Button>("share-go");
Assert.IsTrue(go.enabledInHierarchy && go.style.display.value != DisplayStyle.None, "the Share or Download button stays available");
UiTestKit.Press(ui.Q<Button>("share-close"));
UiTestKit.Press(ui.Q<Button>("settings-share"));
Assert.AreEqual(DisplayStyle.None, said.style.display.value, "a new picture, a new copy: the old message goes");
}
finally
{
ui.Dispose();
ShareShot.Keep = ShareShot.DefaultKeep; ShareShot.Share = ShareShot.DefaultShare;
ShareShot.Copy = ShareShot.DefaultCopy; ShareShot.Copied = ShareShot.DefaultCopied;
}
}
/// <summary>A Copy press whose release never reached the browser stays Pending; after a few seconds the panel says
/// the copy failed instead of staying silent.</summary>
[UnityEngine.TestTools.UnityTest]
public System.Collections.IEnumerator ACopyThatNeverAnswersSaysItFailed()
{
ShareShot.Keep = (png, name) => { };
ShareShot.Copy = t => { }; ShareShot.Copied = () => ShareShot.CopyResult.Pending;
var ui = new UiTestKit();
try
{
var bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), En);
using var share = new SharePresenter(ui.Root, bridge, En, done => done(new byte[] { 1 }));
UiTestKit.Press(ui.Q<Button>("settings-share"));
SettingsScreenTests.PressWithPointer(ui.Q<Button>("share-copy"));
var said = ui.Q<Label>("share-copied");
var until = Time.realtimeSinceStartup + 7f;
while (said.style.display.value != DisplayStyle.Flex && Time.realtimeSinceStartup < until) { EditorApplication.QueuePlayerLoopUpdate(); yield return null; }
Assert.AreEqual(DisplayStyle.Flex, said.style.display.value);
Assert.AreEqual(En["share.copy_failed"], said.text);
}
finally
{
ui.Dispose();
ShareShot.Keep = ShareShot.DefaultKeep; ShareShot.Copy = ShareShot.DefaultCopy; ShareShot.Copied = ShareShot.DefaultCopied;
}
}
/// <summary>The turn report's Share opens the same panel over the report.</summary>
[Test]
public void TheTurnReportHasAShareButton()
{
ShareShot.Keep = (png, name) => { };
try
{
using var ui = new UiTestKit();
var bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), En);
using var share = new SharePresenter(ui.Root, bridge, En, done => done(new byte[] { 1 }));
Assert.AreEqual(En["share.open"], ui.Q<Button>("turn-report-share").text);
UiTestKit.Press(ui.Q<Button>("turn-report-share"));
Assert.IsTrue(share.IsOpen);
UiTestKit.Press(ui.Q<Button>("share-close"));
Assert.IsFalse(share.IsOpen);
}
finally { ShareShot.Keep = ShareShot.DefaultKeep; }
}
// #1653: the native/editor seam verifies ordering and honest notes; real browser activation stays a separate gate.
[UnityEngine.TestTools.UnityTest]
public System.Collections.IEnumerator SitesCopyBeforeOpeningAndReportTheActualResult(
[Values("x", "facebook", "whatsapp", "telegram", "linkedin")] string site,
[Values(false, true)] bool hebrew,
[Values(false, true)] bool canShareFiles,
[Values(false, true)] bool keyboard,
[Values(ShareShot.CopyResult.Picture, ShareShot.CopyResult.Text, ShareShot.CopyResult.Failed, ShareShot.CopyResult.Downloaded)] ShareShot.CopyResult result)
{
var text = hebrew ? He : En;
var calls = new List<string>();
var answer = ShareShot.CopyResult.Pending;
ShareShot.Keep = (_, __) => { };
ShareShot.Copy = post => calls.Add((result == ShareShot.CopyResult.Downloaded ? "download:" : "copy:") + post);
ShareShot.Copied = () => answer;
ShareShot.CanShareFiles = () => canShareFiles;
ExternalLink.Opener = url => calls.Add("open:" + url);
var ui = new UiTestKit();
try
{
var bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), text);
using var share = new SharePresenter(ui.Root, bridge, text, done => done(new byte[] { 1 }));
UiTestKit.Press(ui.Q<Button>("settings-share"));
var button = ui.Q<Button>("share-" + site);
var post = ShareShot.Text(text, HudModel.From(bridge, text).Date, bridge.State.Turn);
Assert.AreEqual(ShareShot.Shown(post, hebrew), ui.Q<Label>("share-post").text,
"only the display label carries Hebrew URL joiners");
StringAssert.DoesNotContain(ShareShot.WordJoiner.ToString(), post, "outgoing text has no display-only joiner");
Assert.AreEqual(text[canShareFiles ? "share.native" : "share.download"], ui.Q<Button>("share-go").text);
if (keyboard) UiTestKit.Press(button); else SettingsScreenTests.PressWithPointer(button);
CollectionAssert.AreEqual(new[] { (result == ShareShot.CopyResult.Downloaded ? "download:" : "copy:") + post, "open:" + ShareShot.IntentUrl(site, post) }, calls,
"copy or blocked-clipboard download starts before opening; native seam, not browser activation proof");
var note = ui.Q<Label>("share-copied");
Assert.AreEqual(DisplayStyle.None, note.style.display.value, "do not claim that a pending copy succeeded");
if (site == "x" && !hebrew && !canShareFiles && keyboard && result == ShareShot.CopyResult.Picture)
{
var wait = Time.realtimeSinceStartup + 5.6f; // the site may hold focus longer than the old polling window
while (Time.realtimeSinceStartup < wait) { EditorApplication.QueuePlayerLoopUpdate(); yield return null; }
Assert.AreEqual(DisplayStyle.None, note.style.display.value, "a pending site copy is not a false success or failure");
}
answer = result;
var until = Time.realtimeSinceStartup + 4f;
while (note.style.display.value != DisplayStyle.Flex && Time.realtimeSinceStartup < until)
{ EditorApplication.QueuePlayerLoopUpdate(); yield return null; }
var key = result == ShareShot.CopyResult.Picture ? "share.site_picture" :
result == ShareShot.CopyResult.Text ? "share.site_text" :
result == ShareShot.CopyResult.Downloaded ? "share.site_downloaded" : "share.site_failed";
Assert.AreEqual(text[key], note.text);
if (result == ShareShot.CopyResult.Downloaded)
{
StringAssert.Contains(hebrew ? "התמונה שהורדה" : "downloaded picture", note.text);
StringAssert.DoesNotContain(text["share.site_picture"], note.text, "download must not claim clipboard success");
}
else if (result != ShareShot.CopyResult.Picture)
StringAssert.Contains(hebrew ? "התמונה עדיין זמינה לשיתוף או להורדה" :
"Use Share or Download the picture", note.text,
"the note must fit both Share and Download, including a refused share sheet");
Assert.AreEqual(DisplayStyle.Flex, note.style.display.value);
share.Close();
UiTestKit.Press(button);
Assert.AreEqual(2, calls.Count, "closing unbinds site actions");
}
finally
{
ui.Dispose(); ExternalLink.Opener = ExternalLink.Default;
ShareShot.Keep = ShareShot.DefaultKeep; ShareShot.Copy = ShareShot.DefaultCopy; ShareShot.Copied = ShareShot.DefaultCopied;
ShareShot.CanShareFiles = ShareShot.DefaultCanShareFiles;
}
}
// #1653: C# lifetime/bridge regressions only. No DOM, native sheet or promise is exercised here.
sealed class ShareAttemptUi : IDisposable
{
public readonly UiTestKit Ui = new UiTestKit();
public readonly List<Action> Checks = new List<Action>();
public readonly List<IVisualElementScheduledItem> Polls = new List<IVisualElementScheduledItem>();
public readonly List<int> Cancelled = new List<int>();
public readonly List<string> Calls = new List<string>();
public readonly SharePresenter Presenter;
public bool Failed;
public int Reads, Ticket;
readonly Action<byte[], string> keep = ShareShot.Keep;
readonly Func<bool> can = ShareShot.CanShareFiles, failed = ShareShot.Failed;
readonly Action<string> share = ShareShot.Share, copy = ShareShot.Copy, open = ExternalLink.Opener;
readonly Action invalidate = ShareShot.Invalidate;
readonly Func<int> armTicket = ShareShot.ArmTicket;
readonly Action<int> cancelArm = ShareShot.CancelArm;
readonly Func<ShareShot.CopyResult> copied = ShareShot.Copied;
public ShareAttemptUi()
{
SharePresenter? presenter = null;
try
{
ShareShot.Invalidate = () => Calls.Add("invalidate");
ShareShot.ArmTicket = () => Ticket;
ShareShot.CancelArm = Cancelled.Add;
ShareShot.Keep = (_, __) => Calls.Add("keep");
ShareShot.CanShareFiles = () => true;
ShareShot.Share = _ => { Calls.Add("share"); Ticket++; Failed = false; };
ShareShot.Copy = _ => { Calls.Add("copy"); Ticket++; };
ShareShot.Copied = () => ShareShot.CopyResult.Pending;
ShareShot.Failed = () => { Reads++; return Failed; };
ExternalLink.Opener = _ => Calls.Add("open");
var bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), En);
presenter = new SharePresenter(Ui.Root, bridge, En, done => done(new byte[] { 1 }), check =>
{
Checks.Add(check);
var poll = Ui.Q<Button>("share-go").schedule.Execute(check);
Polls.Add(poll);
return poll;
});
Presenter = presenter;
Presenter.Open();
}
catch
{
Cleanup(presenter);
throw;
}
}
public void Press(string name) => UiTestKit.Press(Ui.Q<Button>("share-" + name));
public DisplayStyle Note(string name) => Ui.Q<VisualElement>(name).style.display.value;
public void Dispose() => Cleanup(Presenter);
void Cleanup(SharePresenter? presenter)
{
try
{
if (presenter != null) presenter.Dispose();
}
finally
{
try { Ui.Dispose(); }
finally
{
ShareShot.Keep = keep; ShareShot.CanShareFiles = can; ShareShot.Failed = failed;
ShareShot.Share = share; ShareShot.Copy = copy; ShareShot.Copied = copied; ExternalLink.Opener = open;
ShareShot.Invalidate = invalidate; ShareShot.ArmTicket = armTicket; ShareShot.CancelArm = cancelArm;
}
}
}
}
[UnityEngine.TestTools.UnityTest]
public System.Collections.IEnumerator MainShareStillObservesFailureAfterThreeSeconds()
{
using var attempt = new ShareAttemptUi();
attempt.Press("go");
var until = Time.realtimeSinceStartup + 3.6f;
while (Time.realtimeSinceStartup < until) { EditorApplication.QueuePlayerLoopUpdate(); yield return null; }
Assert.AreEqual(DisplayStyle.None, attempt.Note("share-fallback"), "false Failed stays silent");
Assert.IsTrue(attempt.Polls.Single().isActive, "success/cancel cannot be distinguished by Failed alone");
attempt.Failed = true;
until = Time.realtimeSinceStartup + 2f;
while (attempt.Note("share-fallback") != DisplayStyle.Flex && Time.realtimeSinceStartup < until)
{ EditorApplication.QueuePlayerLoopUpdate(); yield return null; }
Assert.AreEqual(DisplayStyle.Flex, attempt.Note("share-fallback"));
Assert.IsFalse(attempt.Polls.Single().isActive, "failure stops the owned poll");
var reads = attempt.Reads;
attempt.Checks.Single()();
Assert.AreEqual(reads, attempt.Reads, "even a queued callback after failure is inert");
}
[Test]
public void OldShareObserverCannotSurviveCloseReopenOrDispose()
{
using var attempt = new ShareAttemptUi();
attempt.Press("go");
var old = attempt.Checks.Single();
attempt.Presenter.Close();
Assert.IsFalse(attempt.Polls.Single().isActive);
attempt.Presenter.Open(); // deliberately no new Send
attempt.Failed = true;
var reads = attempt.Reads;
old();
Assert.AreEqual(reads, attempt.Reads);
Assert.AreEqual(DisplayStyle.None, attempt.Note("share-fallback"));
attempt.Press("instagram");
var current = attempt.Checks.Last();
attempt.Presenter.Dispose();
reads = attempt.Reads;
current(); old();
Assert.AreEqual(reads, attempt.Reads, "disposed callbacks must not even read the bridge");
Assert.IsTrue(attempt.Polls.All(p => !p.isActive));
var calls = attempt.Calls.Count;
attempt.Press("go"); attempt.Press("instagram"); attempt.Press("copy");
attempt.Presenter.Open(); attempt.Presenter.Close(); attempt.Presenter.Dispose();
Assert.AreEqual(calls, attempt.Calls.Count, "disposal unbinds the controls, and Open, Close and a second Dispose are inert");
}
[Test]
public void EveryNewActionInvalidatesTheOldObserver(
[Values("go", "instagram")] string first,
[Values("go", "instagram", "copy", "x", "facebook", "whatsapp", "telegram", "linkedin")] string next)
{
using var attempt = new ShareAttemptUi();
attempt.Press(first);
var old = attempt.Checks.Single();
attempt.Press(next);
Assert.IsFalse(attempt.Polls.First().isActive);
attempt.Failed = true;
var reads = attempt.Reads;
old(); // model a callback already queued before Pause
Assert.AreEqual(reads, attempt.Reads, "generation must reject it before querying Failed");
Assert.AreEqual(DisplayStyle.None, attempt.Note("share-fallback"));
Assert.AreEqual(DisplayStyle.None, attempt.Note("share-instagram-note"));
if (next == "go" || next == "instagram")
{
attempt.Checks.Last()();
Assert.AreEqual(DisplayStyle.Flex, attempt.Note(next == "go" ? "share-fallback" : "share-instagram-note"));
Assert.AreEqual(DisplayStyle.None, attempt.Note(next == "go" ? "share-instagram-note" : "share-fallback"));
}
}
/// <summary>The C# half only: focus-out hands JS the ticket this control stored, not the current one. That JS cancels
/// nothing but a still-armed matching ticket (StatecraftShareCancelArm) is outside what this fake can check; it is in
/// the manual record (docs/share-1653-manual-checks.md, step 5).</summary>
[Test]
public void LifecycleInvalidatesBeforeKeepAndActionsAndFocusOutPassesItsOwnTicket(
[Values("go", "instagram", "copy")] string control)
{
using var attempt = new ShareAttemptUi();
CollectionAssert.AreEqual(new[] { "invalidate", "keep" }, attempt.Calls);
attempt.Calls.Clear();
attempt.Press(control);
CollectionAssert.AreEqual(new[] { "invalidate", control == "copy" ? "copy" : "share" }, attempt.Calls);
var owner = attempt.Ticket;
attempt.Ticket++; // a newer browser ticket can now belong to a site
var count = attempt.Calls.Count;
var button = attempt.Ui.Q<Button>("share-" + control);
button.Focus(); button.Blur();
CollectionAssert.AreEqual(new[] { owner }, attempt.Cancelled, "focus-out passes the stored ticket, not the newer one");
Assert.AreEqual(count, attempt.Calls.Count, "focus-out must not invalidate a released native promise");
attempt.Presenter.Close();
Assert.AreEqual("invalidate", attempt.Calls.Last());
attempt.Calls.Clear();
attempt.Presenter.Open();
CollectionAssert.AreEqual(new[] { "invalidate", "keep" }, attempt.Calls);
attempt.Presenter.Dispose();
Assert.AreEqual("invalidate", attempt.Calls.Last());
}
}