Skip to content

A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.

Add share and copy-link controls to the bilingual website (#1348)

Aviel Cohen2046150f8099
diff --git a/.github/workflows/site.yml b/.github/workflows/site.yml
index b8a2985fc..5e24444cf 100644
--- a/.github/workflows/site.yml
+++ b/.github/workflows/site.yml
@@ -38,6 +38,9 @@ jobs:
- name: Install
working-directory: site
run: npm ci --ignore-scripts --no-audit --no-fund
+ - name: Test
+ working-directory: site
+ run: node --test tests/*.test.mjs
- name: Build and check
working-directory: site
env:
diff --git a/site/src/components/ShareControls.astro b/site/src/components/ShareControls.astro
new file mode 100644
index 000000000..40c213571
--- /dev/null
+++ b/site/src/components/ShareControls.astro
@@ -0,0 +1,67 @@
+---
+import { type Lang, t } from '../i18n/ui';
+interface Props { lang: Lang; url: string }
+const { lang, url } = Astro.props;
+---
+<div class="share-tools" role="group" aria-label={t(lang, 'share.label')} data-site-share
+ data-url={url} data-title={t(lang, 'site.name')} data-copied={t(lang, 'share.copied')}
+ data-unavailable={t(lang, 'share.unavailable')} data-manual={t(lang, 'share.manual')}>
+ <div class="share-actions">
+ <button class="btn" type="button" data-share-native hidden>{t(lang, 'share.native')}</button>
+ <button class="btn" type="button" data-share-copy hidden>{t(lang, 'share.copy')}</button>
+ </div>
+ <p class="share-status" role="status" aria-live="polite" aria-atomic="true" data-share-status></p>
+ <div class="share-manual" data-share-manual hidden>
+ <label>{t(lang, 'share.url')}<input type="url" dir="ltr" readonly value={url} data-share-url /></label>
+ </div>
+ <noscript><p>{t(lang, 'share.manual')} <a href={url} dir="ltr">{url}</a></p></noscript>
+</div>
+
+<script>
+ import { createSharing } from '../lib/share.mjs';
+
+ for (const root of document.querySelectorAll<HTMLElement>('[data-site-share]')) {
+ const native = root.querySelector<HTMLButtonElement>('[data-share-native]');
+ const copy = root.querySelector<HTMLButtonElement>('[data-share-copy]');
+ const status = root.querySelector<HTMLElement>('[data-share-status]');
+ const manual = root.querySelector<HTMLElement>('[data-share-manual]');
+ const input = root.querySelector<HTMLInputElement>('[data-share-url]');
+ if (!native || !copy || !status || !manual || !input) continue;
+
+ const controller = createSharing({
+ url: root.dataset.url,
+ title: root.dataset.title,
+ secure: window.isSecureContext,
+ share: navigator.share?.bind(navigator),
+ writeText: navigator.clipboard?.writeText?.bind(navigator.clipboard),
+ }, (state) => {
+ const busy = state === 'sharing' || state === 'copying';
+ native.setAttribute('aria-disabled', String(busy));
+ copy.setAttribute('aria-disabled', String(busy));
+ status.textContent = state === 'copied' ? root.dataset.copied ?? ''
+ : state === 'share-unavailable' ? root.dataset.unavailable ?? ''
+ : state === 'manual-copy' ? root.dataset.manual ?? '' : '';
+ if (state === 'manual-copy') {
+ manual.hidden = false;
+ input.value = controller.url;
+ input.focus();
+ input.select();
+ }
+ });
+ native.hidden = !controller.canShare;
+ copy.hidden = false;
+ native.addEventListener('click', () => { void controller.share(); });
+ copy.addEventListener('click', () => { void controller.copy(); });
+ }
+</script>
+
+<style>
+ .share-tools { margin-block-start: 1.25rem; }
+ .share-actions { display: flex; flex-wrap: wrap; justify-content: center; gap: .75rem; }
+ .share-actions .btn { font-family: inherit; font-size: inherit; cursor: pointer; }
+ .share-actions [hidden], .share-manual[hidden] { display: none; }
+ .share-status { min-block-size: 1.5em; margin-block: .5rem 0; text-align: center; }
+ .share-manual { text-align: center; }
+ .share-manual label { display: grid; justify-items: center; gap: .35rem; }
+ .share-manual input { inline-size: min(100%, 36rem); padding: .5rem; font: inherit; }
+</style>
diff --git a/site/src/i18n/ui.ts b/site/src/i18n/ui.ts
index e10d5a3d1..48c39b143 100644
--- a/site/src/i18n/ui.ts
+++ b/site/src/i18n/ui.ts
@@ -12,6 +12,13 @@ export type Page = (typeof pages)[number];
const en = {
'site.name': 'Statecraft: Israel',
+ 'share.label': 'Share this game',
+ 'share.native': 'Share',
+ 'share.copy': 'Copy link',
+ 'share.copied': 'Link copied.',
+ 'share.unavailable': 'Sharing is unavailable. Use Copy link instead.',
+ 'share.manual': 'Copy this link manually.',
+ 'share.url': 'Page link',
'site.tagline': 'A turn-based strategy game about governing Israel from 15 May 1948. Open source, with a source for every historical fact.',
'lang.other': 'עברית',
'lang.other.label': 'Hebrew version of this page',
@@ -74,6 +81,13 @@ type Dict = Record<keyof typeof en, string>;
const he: Dict = {
'site.name': 'Statecraft: Israel',
+ 'share.label': 'שיתוף המשחק',
+ 'share.native': 'שיתוף',
+ 'share.copy': 'העתקת קישור',
+ 'share.copied': 'הקישור הועתק.',
+ 'share.unavailable': 'השיתוף אינו זמין. השתמשו בהעתקת קישור.',
+ 'share.manual': 'העתיקו את הקישור ידנית.',
+ 'share.url': 'קישור לעמוד',
'site.tagline': 'משחק אסטרטגיה מבוסס־תורות על ניהול מדינת ישראל מ־15 במאי 1948. קוד פתוח, ולכל עובדה היסטורית יש מקור.',
'lang.other': 'English',
'lang.other.label': 'הגרסה האנגלית של העמוד',
diff --git a/site/src/lib/share.mjs b/site/src/lib/share.mjs
new file mode 100644
index 000000000..a692ccb77
--- /dev/null
+++ b/site/src/lib/share.mjs
@@ -0,0 +1,46 @@
+// Share only a rendered canonical: never the visitor's query or fragment.
+export function createSharing({ url, title, share, writeText, secure = true }, onState = () => {}) {
+ const canonical = new URL(url);
+ if (!['https:', 'http:'].includes(canonical.protocol)) throw new TypeError('Expected an HTTP canonical URL');
+ canonical.search = '';
+ canonical.hash = '';
+ const payload = { url: canonical.href, title };
+ const canShare = secure && typeof share === 'function';
+ let busy = false;
+
+ return {
+ url: payload.url,
+ canShare,
+ get busy() { return busy; },
+ async share() {
+ if (busy || !canShare) return;
+ busy = true;
+ onState('sharing');
+ let result = 'idle';
+ try {
+ await share(payload);
+ } catch (error) {
+ // AbortError also covers no available targets; don't claim a reason or copy automatically.
+ if (error?.name !== 'AbortError') result = 'share-unavailable';
+ } finally {
+ busy = false;
+ onState(result);
+ }
+ },
+ async copy() {
+ if (busy) return;
+ if (!secure || typeof writeText !== 'function') { onState('manual-copy'); return; }
+ busy = true;
+ onState('copying');
+ let result = 'copied';
+ try {
+ await writeText(payload.url);
+ } catch {
+ result = 'manual-copy';
+ } finally {
+ busy = false;
+ onState(result);
+ }
+ },
+ };
+}
diff --git a/site/src/pages/[lang]/index.astro b/site/src/pages/[lang]/index.astro
index a2a1ba116..04c60e27e 100644
--- a/site/src/pages/[lang]/index.astro
+++ b/site/src/pages/[lang]/index.astro
@@ -5,6 +5,7 @@ import Figure from '../../components/Figure.astro';
import VideoFacade from '../../components/VideoFacade.astro';
import MediaLabel from '../../components/MediaLabel.astro';
import ContributorsGrid from '../../components/ContributorsGrid.astro';
+import ShareControls from '../../components/ShareControls.astro';
import { type Lang, languages, href, t, REPO, formatDate, asset } from '../../i18n/ui';
import { capture, concept, flythrough, trailer, gameplay, gameplayVideo, captureDateIso, heroShot } from '../../lib/media';
import { posts } from '../../lib/devlog';
@@ -137,6 +138,7 @@ const features = [
? 'המשחק עוסק במלחמה, בטרור ובשואה כאירועים היסטוריים. המסגור שלו ישראלי, ואף ציטוט אינו בדוי. זה אב־טיפוס מוקדם.'
: 'The game deals with war, terror and the Holocaust as historical events. Its framing is Israeli, and no quotes are invented. It is an early prototype.'}
{' '}<a href={href(lang, 'history/sources')}>{t(lang, 'nav.sources')}</a></p>
+ <ShareControls lang={lang} url={abs(href(lang))} />
</div></section>
{/* The real gameplay clip, behind a click: the hero is a clean still, so the first screen loads no video. */}
diff --git a/site/tests/share.test.mjs b/site/tests/share.test.mjs
new file mode 100644
index 000000000..c98169a3a
--- /dev/null
+++ b/site/tests/share.test.mjs
@@ -0,0 +1,124 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { createSharing } from '../src/lib/share.mjs';
+
+const title = 'Statecraft: Israel';
+const canonical = 'https://example.test/statecraft-israel/en/';
+const deferred = () => {
+ let resolve, reject;
+ const promise = new Promise((yes, no) => { resolve = yes; reject = no; });
+ return { promise, resolve, reject };
+};
+const namedError = (name) => Object.assign(new Error(name), { name });
+
+for (const url of [
+ 'https://example.test/statecraft-israel/en/',
+ 'https://example.test/statecraft-israel/he/',
+ 'https://example.test/en/',
+ 'https://example.test/he/',
+]) {
+ test(`canonical language/base path retained without query or fragment: ${url}`, () => {
+ const controller = createSharing({ url: `${url}?token=private-sentinel#private-fragment`, title });
+ assert.equal(controller.url, url);
+ assert.ok(!controller.url.includes('private-sentinel'));
+ assert.ok(!controller.url.includes('private-fragment'));
+ });
+}
+
+test('rejects a non-HTTP canonical instead of putting it into a share payload', () => {
+ assert.throws(() => createSharing({ url: 'javascript:alert(1)', title }), TypeError);
+});
+
+test('native sharing receives the existing canonical and title once, and is available only with an API', async () => {
+ const payloads = [], states = [];
+ const controller = createSharing({ url: canonical, title, share: async (payload) => payloads.push(payload) }, (state) => states.push(state));
+ assert.equal(controller.canShare, true);
+ await controller.share();
+ assert.deepEqual(payloads, [{ url: canonical, title }]);
+ assert.deepEqual(states, ['sharing', 'idle']);
+ assert.equal(controller.busy, false);
+ assert.equal(createSharing({ url: canonical, title }).canShare, false);
+});
+
+test('a pending native request prevents a second share and returns to idle on resolution', async () => {
+ const pending = deferred(); let calls = 0;
+ const controller = createSharing({ url: canonical, title, share: () => { calls++; return pending.promise; } });
+ const first = controller.share();
+ assert.equal(controller.busy, true);
+ await controller.share();
+ assert.equal(calls, 1);
+ pending.resolve(); await first;
+ assert.equal(controller.busy, false);
+});
+
+test('AbortError stays quiet and never automatically copies or reports success', async () => {
+ let copies = 0; const states = [];
+ const controller = createSharing({ url: canonical, title, share: async () => { throw namedError('AbortError'); }, writeText: async () => { copies++; } }, (state) => states.push(state));
+ await controller.share();
+ assert.deepEqual(states, ['sharing', 'idle']);
+ assert.equal(copies, 0);
+ assert.equal(controller.busy, false);
+});
+
+for (const name of ['NotAllowedError', 'DataError']) {
+ test(`native ${name} leaves an explicit copy action usable without auto-copy`, async () => {
+ const copied = [], states = [];
+ const controller = createSharing({ url: canonical, title, share: () => { throw namedError(name); }, writeText: async (url) => copied.push(url) }, (state) => states.push(state));
+ await controller.share();
+ assert.deepEqual(states, ['sharing', 'share-unavailable']);
+ assert.deepEqual(copied, []);
+ assert.equal(controller.busy, false);
+ await controller.copy();
+ assert.deepEqual(copied, [canonical]);
+ assert.equal(states.at(-1), 'copied');
+ });
+}
+
+test('Copied is emitted only after clipboard resolves, with the sanitized canonical', async () => {
+ const pending = deferred(), copied = [], states = [];
+ const controller = createSharing({ url: `${canonical}?token=private-sentinel#fragment`, title, writeText: (url) => { copied.push(url); return pending.promise; } }, (state) => states.push(state));
+ const copying = controller.copy();
+ assert.deepEqual(copied, [canonical]);
+ assert.ok(!states.includes('copied'));
+ assert.equal(controller.busy, true);
+ pending.resolve(); await copying;
+ assert.equal(states.at(-1), 'copied');
+ assert.equal(controller.busy, false);
+});
+
+test('denied clipboard selects a manual-copy state without a false success', async () => {
+ const states = [];
+ const controller = createSharing({ url: canonical, title, writeText: async () => { throw namedError('NotAllowedError'); } }, (state) => states.push(state));
+ await controller.copy();
+ assert.equal(states.at(-1), 'manual-copy');
+ assert.ok(!states.includes('copied'));
+ assert.equal(controller.url, canonical);
+ assert.equal(controller.busy, false);
+});
+
+test('missing clipboard keeps the canonical available for manual selection', async () => {
+ const states = [];
+ const controller = createSharing({ url: canonical, title }, (state) => states.push(state));
+ await controller.copy();
+ assert.deepEqual(states, ['manual-copy']);
+ assert.equal(controller.url, canonical);
+});
+
+test('insecure contexts do not invoke restricted APIs and retain manual selection', async () => {
+ let shares = 0, copies = 0; const states = [];
+ const controller = createSharing({ url: canonical, title, secure: false, share: async () => { shares++; }, writeText: async () => { copies++; } }, (state) => states.push(state));
+ assert.equal(controller.canShare, false);
+ await controller.share(); await controller.copy();
+ assert.equal(shares, 0); assert.equal(copies, 0);
+ assert.equal(states.at(-1), 'manual-copy');
+});
+
+test('a pending copy prevents duplicate writes and is recoverable after failure', async () => {
+ const pending = deferred(); let writes = 0; const states = [];
+ const controller = createSharing({ url: canonical, title, writeText: () => { writes++; return pending.promise; } }, (state) => states.push(state));
+ const copying = controller.copy(); await controller.copy();
+ assert.equal(writes, 1);
+ pending.reject(namedError('NotAllowedError')); await copying;
+ assert.equal(controller.busy, false);
+ assert.equal(states.at(-1), 'manual-copy');
+});