Files
gods-eye-view/src/ui/shareButton.test.mjs
T
Sameh Khamis da02fd8645 feat(share): short /share/<code> links with a compact versioned view format (#1418)
* feat(share): add compact versioned share-view codec

Add a standalone codec for `#s=<base64url>` share links: a version byte
followed by protobuf-style tag-length-value fields. Settings equal to
their default are omitted and refilled from the same table on decode;
unknown fields are skipped by wire type, so new fields never break
older apps. Views are a place (camera) or a thing (an aircraft,
military aircraft, vessel or satellite to follow, with camera offset
and last-known fix); an unknown kind falls back to the camera.

The decoder bounds its input and rejects malformed payloads with a
reason instead of throwing. A converter maps the long form's parsed
state to and from the codec state; the long form is unchanged.

* fix(share): tighten codec decoding after review

Unknown detection mode and allocation names now fall back to their
defaults instead of reaching the lenient long-form migration. Future
panel values and style-parameter tokens are skipped rather than applied
or rejected, and layer options are accepted only under their owner
layer. Wrap longitudes before scaling, normalize negative zero, reuse
the layer-state tracking ID grammar, and align the format doc with the
decoder.

* feat(share): let a host share the link its own way

ShareLinkManager.buildLink() returns the current share link without
copying it, and copyLink() now copies exactly that. The share button
passes the link to an optional services.shareLink(url), which resolves
to 'shared', 'copied', 'cancelled' or false; 'cancelled' shows no toast
and 'shared' shows the new "Link shared" (es, ru, zh-CN). Without the
service the button copies as before.

* feat(share): open and make short /share/<code> links

The share button now makes `<app>/share/<code>` links with the compact
share-view code, and the app opens them at start-up through the same
restore pipeline as long links. Once the app next writes the address, the
share path is replaced (no new history entry) by the app's own address and
the live long-form hash, so a reload follows the live view. A host can pass
the code as `initialShareCode` instead. A code that fails to decode restores
nothing and shows "This share link can't be opened".

The code gains a trailing CRC-8 check byte, so any single mistyped
character is rejected instead of opening a different view. Thing views no
longer store a camera: it is derived from the entity's last-known fix and
the follow offset on a sphere, the entity kind is implied by the id's
field, and the followed entity's layer bit is implied; an aircraft followed
from the app's own camera is a 42-character code. The `#s=` hash form is
gone.

While the camera follows an aircraft, military aircraft or satellite, the
link is a thing view with the camera's offset and the entity's position.
Opening one turns the layer on and follows the entity through the existing
shared-follow restore, then swings the camera round to the shared offset; a
vessel view selects the vessel once the vessel feed has it. If the entity
is not reporting within its window, the view stays at its last-known fix
and says so. The panel and style-parameter tables now come from the codec,
and a host share hook that returns a plain value or throws still gets a
toast.

* fix(share): encode style settings against the style's own look

Settings a style applies when selected (bloom, sharpen, HUD, detection,
celestial ring and the style's shader parameters) now default, per field,
to what that style applies in a fresh session, read from the tables the
app applies (the first-load baseline, the style presets and the shader
defaults). The encoder compares against the view's style and the decoder
fills omitted settings from the decoded style, so a view that keeps its
style's look costs only its camera and style. The previous defaults did not
match a fresh session (sharpen, HUD and detection were off), so every link
paid for them, and a style's own shader parameters were always written.

A test pins the per-style defaults as frozen v1 meanings. A followed
aircraft in Noir is now 44 characters and the real long-link example 39.

* docs: changelog for #1418
2026-10-26 15:31:51 -07:00

161 lines
5.0 KiB
JavaScript

// The share button copies by default; a host's `services.shareLink` shares the
// link its own way and reports how it went.
import test from 'node:test';
import assert from 'node:assert/strict';
import { StyleManager } from './applicationShell.js';
import { ShareLinkManager } from '../sharelink.js';
import { parseSharePath } from '../share/shareLinkPath.js';
import { decodeShareView } from '../share/viewCodec.js';
/** The decoded view of a `/share/<code>` link. */
const sharedState = (href) =>
decodeShareView(parseSharePath(new URL(href).pathname).code).state;
const SHARE_LINK = /^https:\/\/gev\.example\/share\/[A-Za-z0-9_-]+$/;
function makeManager(href, { positioned = true } = {}) {
globalThis.window = { location: { href, hash: new URL(href).hash } };
globalThis.history = { replaceState() {} };
const viewer = {
camera: {
changed: { addEventListener() {} },
positionCartographic: positioned
? { latitude: 0, longitude: 0, height: 1000 }
: undefined,
heading: 0,
pitch: -Math.PI / 2,
roll: 0,
},
};
return new ShareLinkManager(viewer);
}
function installClipboard(writeText) {
Object.defineProperty(globalThis, 'navigator', {
configurable: true,
value: { clipboard: { writeText } },
});
}
/** Wire the real share button handler onto a minimal shell; return a click. */
function shell({ manager, services = {} }) {
const toasts = [];
let click;
const owner = {
services,
shareLinkManager: manager,
_shareBtn: {},
_disposed: false,
_lifetime: { listen: (_el, _type, handler) => (click = handler) },
_showToast: (message) => toasts.push(message),
};
StyleManager.prototype._initShareButton.call(owner);
return { toasts, click: () => click() };
}
test('buildLink is a /share link stamped with its creation time, without ?lang', () => {
const manager = makeManager('https://gev.example/?lang=ru#v=2&lat=10&lon=20');
const href = manager.buildLink({ nowMs: 5_000_000 });
assert.match(href, SHARE_LINK);
const link = new URL(href);
assert.equal(link.searchParams.get('lang'), null);
assert.equal(link.hash, '');
assert.equal(sharedState(href).sharedAtMs, 5_000_000);
// The camera is the live one, not the address bar's.
assert.equal(sharedState(href).lat, 0);
assert.equal(
makeManager('https://gev.example/', { positioned: false }).buildLink(),
null,
);
});
test('copyLink copies exactly what buildLink builds', async () => {
let copied = null;
installClipboard(async (url) => {
copied = url;
});
const manager = makeManager('https://gev.example/#v=2');
assert.equal(await manager.copyLink({ nowMs: 7_000_000 }), true);
assert.equal(copied, manager.buildLink({ nowMs: 7_000_000 }));
});
test('without a host hook the button copies the link', async () => {
let copied = null;
installClipboard(async (url) => {
copied = url;
});
const { toasts, click } = shell({
manager: makeManager('https://gev.example/#v=2'),
});
await click();
assert.match(copied, SHARE_LINK);
assert.deepEqual(toasts, ['Link copied!']);
installClipboard(async () => {
throw new Error('denied');
});
await click();
assert.deepEqual(toasts, ['Link copied!', 'Copy failed']);
});
test('a host hook receives the link and its result picks the toast', async () => {
installClipboard(async () => assert.fail('the host shares instead'));
const shared = [];
const results = ['shared', 'copied', 'cancelled', false];
const { toasts, click } = shell({
manager: makeManager('https://gev.example/#v=2'),
services: {
shareLink: async (url) => {
shared.push(url);
return results.shift();
},
},
});
for (let i = 0; i < 4; i++) await click();
assert.equal(shared.length, 4);
assert.match(shared[0], SHARE_LINK);
// 'cancelled' (the user closed the sheet) shows nothing.
assert.deepEqual(toasts, ['Link shared', 'Link copied!', 'Copy failed']);
});
test('a failing host hook, or no camera position, reports a failure', async () => {
const failing = shell({
manager: makeManager('https://gev.example/#v=2'),
services: { shareLink: async () => Promise.reject(new Error('no sheet')) },
});
await failing.click();
assert.deepEqual(failing.toasts, ['Copy failed']);
let called = false;
const unpositioned = shell({
manager: makeManager('https://gev.example/', { positioned: false }),
services: {
shareLink: async () => {
called = true;
return 'shared';
},
},
});
await unpositioned.click();
assert.equal(called, false);
assert.deepEqual(unpositioned.toasts, ['Copy failed']);
});
test('a host hook that answers without a promise, or throws, still gets a toast', async () => {
for (const [shareLink, toast] of [
[() => 'shared', 'Link shared'],
[
() => {
throw new Error('no sheet');
},
'Copy failed',
],
]) {
const { toasts, click } = shell({
manager: makeManager('https://gev.example/#v=2'),
services: { shareLink },
});
await click();
assert.deepEqual(toasts, [toast]);
}
});