@popcorn245/cornfield 0.50.1 → 0.51.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,83 @@
1
+ /**
2
+ * @module explorer/outage-scenario
3
+ *
4
+ * What the scenario player does with an outage (spec 0031 section 8, CLOUD-07): the Layers keys an outage is drawn on (`outageLayers`) and the
5
+ * Play button's scenario for one cloud node (`outageScenario`), made from outage-model.js's blast radius. Only the player and cornfield's page
6
+ * play one, so a map alone, which paints an outage scenario's radius (scene.js, `outageFor`, `paintOutage`), does not carry this (the
7
+ * components' size budget, spec 0011 D11). Pure: no DOM, no state.
8
+ */
9
+
10
+ import { externalLayer } from './cloud-model.js';
11
+ import { cloudUsedBy, nounOf } from './cloud-panel.js';
12
+ import { blastRadius, typeRank } from './outage-model.js';
13
+
14
+ /** The Layers keys the down nodes and the hits are drawn on (layers.js), each once: what the player turns on */
15
+ export function outageLayers(radius, nodes) {
16
+ if (!radius) return [];
17
+ const byId = new Map(nodes.map((n) => [n.id, n]));
18
+ const keys = new Set();
19
+ for (const id of [...radius.down, ...radius.hits.keys()]) {
20
+ const n = byId.get(id);
21
+ if (n) keys.add(n.type === 'external' ? externalLayer(n) : n.type);
22
+ }
23
+ return [...keys];
24
+ }
25
+
26
+ // ---------------------------------------------------------------------------
27
+ // The generated scenario
28
+ // ---------------------------------------------------------------------------
29
+ /** Up to this many of one kind are named; more are counted */
30
+ const NAME_AT = 3;
31
+ const BROWSER = ' (in the visitor\'s browser)';
32
+
33
+ /** "a, b and c"; parts that hold an "and" of their own are kept apart with a comma ("the apps a and b, and the container c") */
34
+ function andList(words) {
35
+ if (words.length < 2) return words.join('');
36
+ const glue = words.some((w) => w.includes(' and ')) ? ', and ' : ' and ';
37
+ return `${words.slice(0, -1).join(', ')}${glue}${words[words.length - 1]}`;
38
+ }
39
+
40
+ /** Hits of one group as words: "the container cloudflared and the machine server-1", "13 containers and 2 apps" */
41
+ function describe(items) {
42
+ const byType = new Map();
43
+ for (const it of items) { if (!byType.has(it.type)) byType.set(it.type, []); byType.get(it.type).push(it); }
44
+ const parts = [...byType].sort(([ta, a], [tb, b]) => b.length - a.length || typeRank(ta) - typeRank(tb) || ta.localeCompare(tb)).map(([type, list]) => {
45
+ const noun = nounOf(type, list.length);
46
+ if (list.length > NAME_AT) {
47
+ const browsers = list.filter((i) => i.browser).length;
48
+ return `${list.length} ${noun}${browsers === list.length ? BROWSER : browsers ? ` (${browsers} in the visitor's browser)` : ''}`;
49
+ }
50
+ return `the ${noun} ${andList(list.map((i) => `${i.label}${i.browser ? BROWSER : ''}`))}`;
51
+ });
52
+ return andList(parts);
53
+ }
54
+
55
+ /**
56
+ * The Play button's scenario for one cloud node (spec 0031 section 8): it takes the node down; the first step is
57
+ * on the node with its `breaks` line; then one step per hit group, strongest first, on a call from one of the
58
+ * node's own users when the group has one (else on its first hit), naming the direct users and then what breaks
59
+ * through them. Validates as a proposal scenario on any map that has the node (its steps are the map's own).
60
+ * @returns {{ id: string, title: string, down: string[], steps: object[] }}
61
+ */
62
+ export function outageScenario(node, nodes, edges) {
63
+ const byId = new Map(nodes.map((n) => [n.id, n]));
64
+ const name = String(node.label || node.id);
65
+ const radius = blastRadius([node.id], nodes, edges);
66
+ const hitAs = (when) => (i) => radius.hits.has(i.id) && radius.hits.get(i.id).when === when; // a user with a stronger path elsewhere is listed there
67
+ const direct = new Map(cloudUsedBy(node, nodes, edges).map((g) => [g.when, g.types.flatMap((t) => t.items).filter(hitAs(g.when)).map((i) => ({ ...i, browser: radius.hits.get(i.id).browser }))]));
68
+ const opening = [`${name} is down.`, node.breaks ? String(node.breaks) : '', radius.groups.length ? '' : 'Nothing on the map uses it.'].filter(Boolean).join(' ');
69
+ const steps = [{ node: node.id, text: opening }];
70
+ for (const group of radius.groups) {
71
+ const own = direct.get(group.when) || [];
72
+ const ownIds = new Set(own.map((i) => i.id));
73
+ const through = group.ids.filter((id) => !ownIds.has(id)).map((id) => {
74
+ const n = byId.get(id);
75
+ return { id, label: String(n.label || id), type: n.type, browser: radius.hits.get(id).browser };
76
+ });
77
+ let text;
78
+ if (own.length) text = `${group.title}: ${describe(own)}.${through.length ? ` Through ${own.length === 1 ? 'it' : 'them'}: ${describe(through)}.` : ''}`;
79
+ else text = `${group.title}, through what uses it: ${describe(through)}.`;
80
+ steps.push(own.length ? { edge: { from: own[0].id, to: node.id, kind: 'calls' }, text } : { node: group.ids[0], text });
81
+ }
82
+ return { id: `outage-${node.id}`, title: `${name} is down`, down: [node.id], steps };
83
+ }
@@ -28,14 +28,15 @@ import { flowSummary } from '../engine/flow-ui.js';
28
28
  import { kindOfMark, fieldRows, MARK_WORDS, proposalPanelHtml } from '../proposal-model.js';
29
29
  import { nodeMockupsHtml } from '../mockups-model.js';
30
30
  import { collapseSheet, initSheets, isPhone, measureCovered, onCoveredChange, registerSheet, unregisterSheet, showSheet, onBackdrop } from '../engine/sheets.js';
31
- import { panIntoView } from '../camera.js';
32
- import { cloudPanelHtml } from '../cloud-model.js';
31
+ import { panIntoView } from '../camera-frame.js';
32
+ import { cloudPanelHtml } from '../cloud-panel.js';
33
33
  import { t } from '../engine/strings.js';
34
34
  import { markStateAttr, markState } from '../corn-state.js';
35
35
  import { fileUrl } from '../file-url.js';
36
36
  import { capped, toggleCapped } from '../capped.js';
37
37
  import { sayResult, clearResult, showResultIn, RESULT_MS } from '../engine/feedback.js';
38
- import { activeSubgraph, connectedLine, farEnds, kindPanelWord, linesByKind } from '../selection-model.js';
38
+ import { activeSubgraph } from '../selection-model.js';
39
+ import { connectedLine, farEnds, kindPanelWord, linesByKind } from '../selection-words.js';
39
40
  import { reach } from '../selection-view.js';
40
41
  import { announce, frameThem } from '../engine/keyboard.js';
41
42
  import { selectNode, clearSelection } from '../engine/selection.js';
@@ -0,0 +1,84 @@
1
+ /**
2
+ * @module explorer/pieces/review-source
3
+ *
4
+ * What a review with a `src` brings (spec 0011 D1, D5, D6, D7, D9): the load from a cornfield server and the states it shows, and the server's theme.
5
+ * It is the review's own side of what pieces/scope.js does for a scope, on the review's own instance, started by the same function (engine/server-load.js
6
+ * `connectServer`) and with the same engine: engine/source.js
7
+ * reads `/cornfield/config.json` and `/topology.json` (`credentials: 'include'`, only to the base's origin), pieces/status.js shows where the load is in
8
+ * the review's stage (the same card, words, hooks and parts a map with a `src` has), and engine/theme-sheet.js gives the server's theme to the review's
9
+ * shadow root when asked. Nothing here is a second copy of loading.
10
+ *
11
+ * It is a chunk of its own (pieces/review.js imports it the first time a review has a `src`): a review that is handed its data never loads it.
12
+ *
13
+ * const link = attachSource(inst, options) -> { source, provide, setUseTheme, setTheme, showSignIn, clearSignIn, destroy }
14
+ *
15
+ * Options: `root` (the review's shadow root, or the element it is in) and `stage` (where the status card goes), `parsed` (engine/source-address.js
16
+ * `parseSource` of `src`), `tokens` (the default tokens, for the theme's derived ones), `version`, `pageUrl`, `useTheme`, `theme` ('light' | 'dark' | 'auto'),
17
+ * the host's `topology`, `config` and `strings` to hand in, and the callbacks the review gives: `onTopology(topology)` (it is there: read, or handed in),
18
+ * `onConfig(config)` (the words, layers and the map's theme are applied: the review draws them again), `onAuth({ status, signIn, during })`,
19
+ * `onError({ kind, message })`, `onMode()` (the tokens changed: the map reads them again) and `focusMap()`.
20
+ */
21
+
22
+ import { connectServer } from '../engine/server-load.js';
23
+ import { mount as mountStatus } from './status.js';
24
+
25
+ /**
26
+ * @param {ReturnType<typeof import('../instance.js').createInstance>} inst the review's own instance (its base is the server's)
27
+ * @param {object} options see the top of this file
28
+ */
29
+ export function attachSource(inst, options) {
30
+ const { root, stage, parsed } = options;
31
+ const host = root.nodeType === 11 ? /** @type {ShadowRoot} */ (root).host : root;
32
+ let useTheme = !!options.useTheme;
33
+ let choice = options.theme;
34
+ let signInShown = false;
35
+ let ended = false;
36
+
37
+ // -- the load and the server's theme, as a scope starts them (engine/server-load.js): the theme's tokens onto the review's element -----------
38
+ const link = connectServer(inst, {
39
+ host, tokens: options.tokens, version: options.version, pageUrl: options.pageUrl,
40
+ theme: () => choice, useTheme: () => useTheme,
41
+ onConfig: (config) => options.onConfig(config),
42
+ onReady: () => { signInShown = false; if (link.source.topology) options.onTopology(link.source.topology); },
43
+ onAuth: ({ status, signIn }) => options.onAuth({ status, signIn, during: 'load' }),
44
+ onError: (error) => options.onError(error),
45
+ onMode: () => options.onMode(),
46
+ onSheet: () => options.onMode(), // the sheet is in, or out: the map reads its tokens again
47
+ });
48
+ const { source } = link;
49
+ const offs = [];
50
+ // Its rules reach only this shadow root: never the document
51
+ if (root.nodeType === 11) offs.push(link.theme.adopt(root));
52
+ const status = mountStatus(stage, inst, { onRetry: () => source.load(), focusMap: options.focusMap });
53
+
54
+ source.provide({ topology: options.topology || undefined, config: options.config || undefined, strings: options.strings || undefined });
55
+ // After what the host handed in, so the card stays: a review with no server to ask cannot open a proposal or decide, whatever map it draws
56
+ if (parsed && !parsed.ok) source.say({ state: 'address', problem: parsed.problem });
57
+ else if (parsed) source.load();
58
+
59
+ return {
60
+ source,
61
+ /** Takes what the host fetched for itself (a key that is `undefined` is left as it was, `null` takes the host's back: engine/source.js `provide`) */
62
+ provide: (what) => source.provide(what),
63
+ /** The server's theme on or off */
64
+ setUseTheme(next) {
65
+ next = !!next;
66
+ if (next === useTheme) return;
67
+ useTheme = next;
68
+ link.setUseTheme(useTheme);
69
+ },
70
+ /** The review's `theme` choice changed: the tokens follow */
71
+ setTheme(next) { choice = next; link.follow(); },
72
+ /** A decision the server refused for want of a sign-in: the same card the load shows, with the server's sign-in */
73
+ showSignIn(detail) { signInShown = true; status.show({ state: 'sign-in', status: detail.status, signIn: detail.signIn }); },
74
+ /** The card a refused decision put up goes (a decision was taken, or another proposal opened): the load's own state, if it has one, stays */
75
+ clearSignIn() { if (!signInShown) return; signInShown = false; status.clear(); },
76
+ destroy() {
77
+ if (ended) return;
78
+ ended = true;
79
+ offs.forEach((off) => off());
80
+ status.destroy();
81
+ link.destroy();
82
+ },
83
+ };
84
+ }
@@ -27,7 +27,23 @@
27
27
  * base, fetch, tokens, renderer, onSelect, onReady as pieces/map.js; `renderer` is read at mount only (a canvas that is replaced loses the edge picking)
28
28
  * label the box's accessible name (a region; 'Proposal review' by default), read at mount
29
29
  *
30
- * What a host hears is on the instance already (instance.js): `selection`, `proposal`, `decision`, `auth`, `scenario:player`. This piece adds nothing.
30
+ * From a server (spec 0011 D1, D6): with `src` (the base address of a cornfield server) and no instance handed in, the piece makes its own over that base and
31
+ * LOADS what it was not handed: `/cornfield/config.json` and `/topology.json` through engine/source.js, with the maintainer's session (the base's own origin
32
+ * only: engine/connection.js), the words, layers and the map's theme from the config, then the proposal by name. Where the load is shows in the box as the
33
+ * status card a map with a `src` has (pieces/status.js): loading, signed out, not a maintainer, not listed, offline, a server error, a bad address, and the
34
+ * version notice. A decision the server refuses for want of a sign-in shows the same card with the same link. The load and the card are a chunk of their own
35
+ * (pieces/review-source.js), imported the first time a review has a `src`; what is handed in (`topology`, `config`, `strings`) goes to the same load, and a host that
36
+ * handed a topology and a config in is asked for nothing. A proposal that cannot be opened is said in the bar, with no way on that goes nowhere here (no Specs list).
37
+ * src, useTheme, version, pageUrl the server's address; whether the box wears its theme (its rules in this shadow root, its `--corn-*` tokens on the host element);
38
+ * the package's version, compared with the server's; the page's address, for the sign-in's way back. Read at mount: a new server is a new piece
39
+ * onNavigate ({ proposal, source, view, change }) the open proposal or its view changed: what cornfield's page puts in its address bar (`proposal` is the name,
40
+ * `source` only when it was asked for by name with one, `view` is null once closed), for the host to answer or not; `change`: 'opened' | 'view' | 'closed'
41
+ * onDecision ({ outcome, proposal, source, open, review }) the server took a review (the instance's `decision`, said once, after the answer)
42
+ * onAuth ({ status, signIn, during }) a sign-in is needed: `during` is 'load', 'proposal', 'facts', 'review', 'send' or 'landing'; `signIn` is the server's sign-in
43
+ * onError ({ kind, message }) `not-listed`, `offline`, `server`, `address`, `version`, `theme` (engine/source.js `errorOf`) or `proposal` (it did not open)
44
+ * onReady (above) is said once, with the first frame of the map that shows the proposal asked for open, or the bar saying why it is not.
45
+ *
46
+ * What a host hears is on the instance too (instance.js): `selection`, `proposal`, `decision`, `auth`, `scenario:player`; the callbacks above are those, made plain.
31
47
  *
32
48
  * Where it lives. The box declares itself the query container its stylesheets ask (`container: corn-box corn-page / size`, css/review.css) and is the
33
49
  * containing block of its own `position: fixed` descendants (`contain: layout`), so it needs a host that gives it a height (it fills 100% of it and is never
@@ -52,12 +68,13 @@ import { mount as mountProposal } from './proposal.js';
52
68
  import { mount as mountChanges } from './changes.js';
53
69
  import { mount as mountDecision } from './decision.js';
54
70
  import { setTopology, layoutMap, setMap } from '../engine/topology.js';
55
- import { closeProposal, rebuildProposalMap } from '../engine/proposal.js';
71
+ import { closeProposal, rebuildProposalMap, setMessage } from '../engine/proposal.js';
56
72
  import { measureCovered, setPhoneBox } from '../engine/sheets.js';
57
73
  import { setProjectLayers } from '../engine/layers.js';
58
74
  import { applyStrings, setStrings } from '../engine/strings.js';
59
75
  import { withParts } from '../engine/piece.js';
60
- import { PROPOSAL_VIEWS } from '../proposal-model.js';
76
+ import { PROPOSAL_VIEWS, isProposalName, notANameWords } from '../proposal-model.js';
77
+ import { parseSource, signInUrl } from '../engine/source-address.js';
61
78
  import { NOTHING_TO_DECIDE } from '../decision-model.js';
62
79
 
63
80
  /**
@@ -113,12 +130,38 @@ export function mount(root, inst, options = {}) {
113
130
  root.append(box);
114
131
 
115
132
  const ownsInstance = !inst;
116
- if (ownsInstance) inst = createInstance({ root: box, base: options.base || '', fetch: options.fetch, strings: options.strings });
133
+ // A `src` (only for a piece that makes its own instance: a scope's is the scope's) is the server: its base is the instance's, a bad one is none and says so
134
+ const srcGiven = ownsInstance && typeof options.src === 'string' ? options.src !== '' : ownsInstance && options.src !== undefined && options.src !== null;
135
+ const parsed = srcGiven ? parseSource(options.src) : null;
136
+ /** A `src` that is not an address is no server: nothing is asked of the page's own origin in its place (a path with no base is the host's own) */
137
+ const blocked = !!parsed && !parsed.ok;
138
+ const nowhere = () => Promise.reject(new TypeError('The review has no server: its src is not an address.'));
139
+ if (ownsInstance) inst = createInstance({ root: box, base: parsed ? (parsed.ok ? parsed.base : '') : options.base || '', fetch: blocked ? nowhere : options.fetch, strings: options.strings });
117
140
  else if (options.strings !== undefined) setStrings(inst, options.strings);
118
141
  const { state } = inst;
119
142
  setPhoneBox(inst, box); // a phone is a narrow box, whatever the window is (engine/sheets.js)
120
143
  applyStrings(inst, box);
121
144
  let ended = false;
145
+ /** `onReady`: the map is drawn and the proposal asked for is open (or has said why it is not): once */
146
+ let mapDrawn = false;
147
+ let settled = true;
148
+ let readyFired = false;
149
+ let readyWaiting = false;
150
+ /** Said with the frame that shows it: the map's next paint after the proposal opened (or said why not), so what the bar says is what the map shows */
151
+ const sayReady = () => {
152
+ if (readyFired || readyWaiting || ended || !mapDrawn || !settled) return;
153
+ const map = inst.map;
154
+ if (!map || typeof map.onPaint !== 'function') { readyFired = true; if (options.onReady) options.onReady(); return; }
155
+ readyWaiting = true;
156
+ const off = map.onPaint(() => {
157
+ off();
158
+ readyWaiting = false;
159
+ if (readyFired || ended || !settled) return; // another proposal was asked for since: it says ready when it is there
160
+ readyFired = true;
161
+ if (options.onReady) options.onReady();
162
+ });
163
+ map.render();
164
+ };
122
165
 
123
166
  // -- the pieces, in the order the page mounts them: the map first, the node panel, the bar, the column, the decision in the column's foot -----
124
167
  const at = markersIn(doc, box);
@@ -130,7 +173,7 @@ export function mount(root, inst, options = {}) {
130
173
  theme: options.theme,
131
174
  tokens: options.tokens,
132
175
  onSelect: options.onSelect,
133
- onReady: options.onReady,
176
+ onReady: () => { mapDrawn = true; sayReady(); },
134
177
  });
135
178
  const nodePanel = mountNodePanel(box, inst, { slots: { drawer: at['node-panel/drawer'], backdrop: at['node-panel/backdrop'] } });
136
179
  const proposalPiece = mountProposal(box, inst, { slots: { bar: at['proposal/bar'], menu: at['proposal/menu'] }, edit: false });
@@ -143,7 +186,7 @@ export function mount(root, inst, options = {}) {
143
186
 
144
187
  // -- what the host asked for ---------------------------------------------------------------------------------------------------------------
145
188
  /** What has been handed in, so an `update` that repeats a value changes nothing */
146
- const serverless = !options.base && !options.fetch;
189
+ const serverless = !options.base && !options.fetch && !(parsed && parsed.ok);
147
190
  const current = { topology: undefined, proposal: null, source: null, slug: null, sha256: null, proposalView: null, shown: null, hasTopology: false, held: false };
148
191
 
149
192
  const redraw = () => { proposalPiece.update(); changesPiece.update(); decisionPiece.update(); nodePanel.update(); };
@@ -155,23 +198,49 @@ export function mount(root, inst, options = {}) {
155
198
  if (wanted === null || wanted === undefined || wanted === '') {
156
199
  current.held = false;
157
200
  current.shown = null;
201
+ settled = true;
158
202
  if (state.proposal) closeProposal(inst);
203
+ sayReady();
159
204
  return undefined;
160
205
  }
161
- if (!current.hasTopology) { current.held = true; return undefined; } // a proposal is laid over a map: it opens when there is one
206
+ if (!current.hasTopology) { current.held = true; settled = false; return undefined; } // a proposal is laid over a map: it opens when there is one
162
207
  current.held = false;
163
208
  const view = current.proposalView;
209
+ if (typeof wanted === 'string' && blocked) { settled = true; sayReady(); return undefined; } // there is no server to ask
210
+ if (typeof wanted === 'string' && serverless) {
211
+ // No server at all (no `src`, `base` or `fetch`): a name is never asked of the page's own origin in its place. Said in the bar, as a name not found is.
212
+ const message = isProposalName(wanted) ? `${wanted} cannot be opened here: there is no cornfield server to read it from (the review has no src).` : notANameWords(wanted);
213
+ current.shown = null;
214
+ setMessage(inst, message, true, []);
215
+ inst.emit('proposal:failed', { slug: wanted, source: current.source, status: 0, notFound: false, message });
216
+ settled = true;
217
+ sayReady();
218
+ return undefined;
219
+ }
164
220
  if (typeof wanted === 'string') {
221
+ // The proposal that is open already, asked for again by its name (a host that heard `cornNavigate` and set what it said): nothing opens again, and the copy
222
+ // the server found is the same one whether or not the name carries it
223
+ if (state.proposal && state.proposalSlug === wanted && (!current.source || current.source === state.proposalSource)) {
224
+ current.shown = `${wanted}\u0000${current.source || ''}`;
225
+ if (PROPOSAL_VIEWS.includes(view) && state.proposalView !== view) proposalPiece.update({ view });
226
+ settled = true;
227
+ return undefined;
228
+ }
165
229
  const key = `${wanted}\u0000${current.source || ''}`;
166
230
  if (current.shown === key && state.proposal) return undefined; // already open (the piece answers true too)
167
231
  current.shown = key;
168
- return proposalPiece.update({ proposal: wanted, source: current.source, view });
232
+ settled = false;
233
+ const opening = proposalPiece.update({ proposal: wanted, source: current.source, view });
234
+ Promise.resolve(opening).then(() => { if (current.shown === key) { settled = true; sayReady(); } }); // opened, or said why not
235
+ return opening;
169
236
  }
170
237
  if (current.shown === wanted && state.proposal) return undefined;
171
238
  current.shown = wanted;
172
239
  // With no server to ask (no `base`, no `fetch`) the object is all there is: its name and source would only send the pieces to the host's own origin for a PR's checks and reviews
173
240
  const named = serverless ? {} : { source: current.source, slug: current.slug, sha256: current.sha256 };
174
241
  proposalPiece.update({ proposal: wanted, ...named, view });
242
+ settled = true;
243
+ sayReady();
175
244
  return undefined;
176
245
  }
177
246
 
@@ -220,6 +289,58 @@ export function mount(root, inst, options = {}) {
220
289
  if (config.theme) mapPiece.applyTheme(config.theme);
221
290
  }
222
291
 
292
+ /** A topology the host handed in, or the server's: laid out once per object */
293
+ function takeTopology(topology) {
294
+ if (topology === current.topology) return;
295
+ current.topology = topology;
296
+ applyTopology(topology);
297
+ }
298
+
299
+ // -- the server: with a `src` the review loads what it was not handed (pieces/review-source.js, a chunk of its own) ----------------------------------
300
+ /** What the host handed in before that chunk came: given to the load as soon as it is there */
301
+ const queued = {};
302
+ let link = null;
303
+ const hand = (what) => { if (link) link.provide(what); else if (srcGiven) Object.assign(queued, what); };
304
+ current.useTheme = !!options.useTheme;
305
+ current.theme = options.theme;
306
+ if (srcGiven && options.strings !== undefined) hand({ strings: options.strings }); // the host's words win over the server's
307
+ /** What a decision or a read the server refused tells a host, with the server's sign-in; the card is the load's own */
308
+ const signInOf = () => (inst.base ? signInUrl(inst.base, typeof options.pageUrl === 'function' ? options.pageUrl() : '') : '');
309
+ const offs = [];
310
+ /** The facts are read again every half minute: a sign-in that is still needed is said once, not every time (a press, or a decision taken, is said each time) */
311
+ let factsRefused = '';
312
+ offs.push(inst.on('auth', ({ status, during }) => {
313
+ const signIn = signInOf();
314
+ if (link) link.showSignIn({ status, signIn });
315
+ if (during === 'facts') { if (factsRefused === `${status}`) return; factsRefused = `${status}`; } else factsRefused = '';
316
+ if (options.onAuth) options.onAuth({ status, signIn, during });
317
+ }));
318
+ offs.push(inst.on('decision', () => { factsRefused = ''; if (link) link.clearSignIn(); }));
319
+ if (options.onDecision) offs.push(inst.on('decision', ({ outcome, review, slug, source, open }) => options.onDecision({ outcome, proposal: slug, source, open, review })));
320
+ if (options.onNavigate) {
321
+ offs.push(inst.on('proposal', ({ change, slug, source, pinSource, view }) => options.onNavigate({ proposal: slug, source: pinSource ? source : null, view: change === 'closed' ? null : view, change })));
322
+ }
323
+ if (options.onError) offs.push(inst.on('proposal:failed', ({ message }) => options.onError({ kind: 'proposal', message })));
324
+ // There is no list of specs to open in another app's page: a bad link's ways leave that button out (engine/proposal.js)
325
+ offs.push(inst.on('proposal:specs-list', () => false));
326
+
327
+ if (srcGiven) {
328
+ import('./review-source.js').then(({ attachSource }) => {
329
+ if (ended) return;
330
+ link = attachSource(inst, {
331
+ root, stage: box.querySelector('[data-corn="stage"]'), parsed, tokens: options.tokens, version: options.version, pageUrl: options.pageUrl,
332
+ useTheme: current.useTheme, theme: current.theme,
333
+ topology: queued.topology, config: queued.config, strings: queued.strings,
334
+ onTopology: (topology) => takeTopology(topology),
335
+ onConfig: () => { applyStrings(inst, box); redraw(); }, // the config's words and layers are on the instance: the pieces say them
336
+ onAuth: (detail) => { if (options.onAuth) options.onAuth(detail); },
337
+ onError: (detail) => { if (options.onError) options.onError(detail); },
338
+ onMode: () => mapPiece.refresh(),
339
+ focusMap: () => { if (state.canvas) state.canvas.focus(); },
340
+ });
341
+ }, (err) => { if (!ended && options.onError) options.onError({ kind: 'offline', message: `the review's loader did not load: ${err && err.message ? err.message : err}` }); });
342
+ }
343
+
223
344
  /**
224
345
  * Applies what changed in `next` (the options above). Only the keys present are looked at.
225
346
  * @returns {Promise<boolean>|undefined} when a proposal is fetched: whether it opened
@@ -227,11 +348,15 @@ export function mount(root, inst, options = {}) {
227
348
  function update(next = {}) {
228
349
  if (ended) return undefined;
229
350
  let again = false;
230
- if ('strings' in next) { setStrings(inst, next.strings); applyStrings(inst, box); again = true; }
231
- if ('config' in next) applyConfig(next.config);
232
- if ('theme' in next) mapPiece.update({ theme: next.theme });
351
+ if ('strings' in next) { setStrings(inst, next.strings); applyStrings(inst, box); again = true; hand({ strings: next.strings }); }
352
+ if ('useTheme' in next) { current.useTheme = !!next.useTheme; if (link) link.setUseTheme(current.useTheme); }
353
+ if ('config' in next) { if (srcGiven) hand({ config: next.config || null }); else applyConfig(next.config); }
354
+ if ('theme' in next) { mapPiece.update({ theme: next.theme }); current.theme = next.theme; if (link) link.setTheme(next.theme); }
233
355
  if ('checker' in next) changesPiece.update({ checker: next.checker });
234
- if ('topology' in next && next.topology !== current.topology) { current.topology = next.topology; applyTopology(next.topology); }
356
+ if ('topology' in next) {
357
+ if (srcGiven) hand({ topology: next.topology || null }); // the load takes it, and says it is ready: takeTopology
358
+ else takeTopology(next.topology);
359
+ }
235
360
  let result;
236
361
  const asked = ['proposal', 'source', 'slug', 'sha256'].some((k) => k in next);
237
362
  if (asked) {
@@ -253,6 +378,9 @@ export function mount(root, inst, options = {}) {
253
378
  if (ended) return;
254
379
  ended = true;
255
380
  stopAsking();
381
+ offs.forEach((off) => off());
382
+ if (link) link.destroy();
383
+ link = null;
256
384
  for (const piece of [decisionPiece, changesPiece, proposalPiece, nodePanel, mapPiece]) piece.destroy();
257
385
  setPhoneBox(inst, null);
258
386
  box.remove();
@@ -262,6 +390,7 @@ export function mount(root, inst, options = {}) {
262
390
  // What was handed in at mount is applied as an update, in the order update() keeps (strings, theme and the checker were taken above)
263
391
  const first = {};
264
392
  for (const key of ['config', 'topology', 'proposal', 'source', 'slug', 'sha256', 'view', 'node']) if (options[key] !== undefined) first[key] = options[key];
393
+ if (srcGiven) { for (const key of ['topology', 'config']) if (key in first) { hand({ [key]: first[key] || null }); delete first[key]; } } // the load takes them
265
394
  update(first);
266
395
 
267
396
  return {
@@ -276,5 +405,9 @@ export function mount(root, inst, options = {}) {
276
405
  destroy,
277
406
  /** The whole map in view */
278
407
  fit: () => mapPiece.fit(),
408
+ /** Selects a node by id and brings it into view; false when there is none */
409
+ focusNode: (id) => mapPiece.focusNode(id),
410
+ /** Reads the tokens again and draws: for a change the style cannot see (the host's `<html>`, a stylesheet in its head) */
411
+ refresh: () => mapPiece.refresh(),
279
412
  };
280
413
  }
@@ -31,10 +31,9 @@
31
31
 
32
32
  import { createInstance } from '../instance.js';
33
33
  import { adoptDefaultTokens } from './adopt-tokens.js';
34
- import { createSource, parseSource } from '../engine/source.js';
35
- import { createServerTheme } from '../engine/theme-sheet.js';
34
+ import { parseSource } from '../engine/source.js';
35
+ import { connectServer } from '../engine/server-load.js';
36
36
  import { keepLayersIn } from '../engine/layers.js';
37
- import { resolveTheme } from '../theme-model.js';
38
37
  import { mount as mountStatus } from './status.js';
39
38
  import { CHANGED, REQUEST, infoOf } from './scope-link.js';
40
39
 
@@ -65,6 +64,8 @@ export function mountScope(host, options = {}) {
65
64
  let inst = null;
66
65
  let source = null;
67
66
  let serverTheme = null;
67
+ /** The load and the theme of the instance (engine/server-load.js) */
68
+ let serverLink = null;
68
69
  let readyFired = false;
69
70
  let ended = false;
70
71
 
@@ -91,18 +92,9 @@ export function mountScope(host, options = {}) {
91
92
  }
92
93
 
93
94
  // -- the mode (light or dark) the server's tokens are for ------------------------------------------------------------------------------
94
- function modeNow() {
95
- const choice = THEMES.includes(props.theme) ? props.theme : 'auto';
96
- if (choice === 'light' || choice === 'dark') return choice;
97
- const root = inst.doc && inst.doc.documentElement;
98
- const own = root ? root.getAttribute('data-theme') : null;
99
- if (own === 'light' || own === 'dark') return own;
100
- const query = inst.win && inst.win.matchMedia ? inst.win.matchMedia('(prefers-color-scheme: light)') : null;
101
- return resolveTheme('system', !!(query && query.matches));
102
- }
95
+ /** The scope's `theme` changed: the tokens follow (the page's own light and dark, and the system's, the link follows by itself) */
103
96
  function followMode() {
104
- if (serverTheme) serverTheme.setMode(modeNow());
105
- if (inst) inst.emit('scope:theme');
97
+ if (serverLink) serverLink.follow();
106
98
  }
107
99
 
108
100
  // -- one instance per server ---------------------------------------------------------------------------------------------------------------
@@ -113,21 +105,25 @@ export function mountScope(host, options = {}) {
113
105
  const info = infoOf(inst);
114
106
  info.host = host;
115
107
  info.theme = THEMES.includes(props.theme) ? props.theme : 'auto';
116
- const st = createServerTheme(inst, { defaults: options.tokens || '' });
108
+ const mine = inst;
109
+ // The load and the server's theme, as a review with a src starts them (engine/server-load.js): the theme's tokens onto the scope's element
110
+ const link = connectServer(inst, {
111
+ host, tokens: options.tokens, version: options.version, pageUrl,
112
+ theme: () => (THEMES.includes(props.theme) ? props.theme : 'auto'), useTheme: () => props.useTheme,
113
+ onReady: () => { if (!readyFired && inst === mine) { readyFired = true; if (options.onReady) options.onReady(); } },
114
+ onAuth: (detail) => { if (options.onAuth) options.onAuth(detail); },
115
+ onError: (error) => { if (options.onError) options.onError(error); },
116
+ onMode: () => mine.emit('scope:theme'),
117
+ });
118
+ serverLink = link;
119
+ const st = link.theme;
117
120
  serverTheme = st;
118
121
  info.serverTheme = st;
119
- st.tokensOn(host);
120
- inst.own(() => st.destroy());
121
- source = createSource(inst, {
122
- version: options.version || '',
123
- pageUrl,
124
- onConfig: (config) => { if (props.useTheme) st.load(config); },
125
- });
122
+ inst.own(() => link.destroy());
123
+ source = link.source;
126
124
  info.source = source;
127
125
  info.mountStatus = mountStatus;
128
126
  readyFired = false;
129
- inst.on('source', onSource);
130
- inst.on('theme', onTheme);
131
127
  // A second map waits: when the one that has the instance's root gives it back, the first that waits and is still in the page asks again
132
128
  // (after the leaving map has finished ending, so the two never hold the instance's state at once)
133
129
  const waiting = [];
@@ -135,7 +131,6 @@ export function mountScope(host, options = {}) {
135
131
  if (d.host && !waiting.includes(d.host)) waiting.push(d.host);
136
132
  if (options.onError) options.onError({ kind: d.reason, message: d.message });
137
133
  });
138
- const mine = inst;
139
134
  inst.on('attach:released', () => {
140
135
  Promise.resolve().then(() => {
141
136
  if (ended || inst !== mine) return;
@@ -145,44 +140,18 @@ export function mountScope(host, options = {}) {
145
140
  }
146
141
  });
147
142
  });
148
- // The host's own light and dark and the system's: the tokens follow
149
- const watch = inst.win && inst.win.MutationObserver && inst.doc && inst.doc.documentElement ? new inst.win.MutationObserver(followMode) : null;
150
- if (watch) { watch.observe(inst.doc.documentElement, { attributes: true, attributeFilter: ['data-theme'] }); inst.own(() => watch.disconnect()); }
151
- const query = inst.win && inst.win.matchMedia ? inst.win.matchMedia('(prefers-color-scheme: light)') : null;
152
- if (query && query.addEventListener) { query.addEventListener('change', followMode); inst.own(() => query.removeEventListener('change', followMode)); }
153
- serverTheme.setMode(modeNow());
154
143
  if (parsed && !parsed.ok) source.say({ state: 'address', problem: parsed.problem });
155
144
  source.provide({ topology: props.topology || undefined, config: props.config || undefined, strings: props.strings || undefined });
156
145
  if (parsed && parsed.ok) source.load();
157
146
  }
158
147
 
159
- function onSource(detail) {
160
- if (ended) return;
161
- switch (detail.state) {
162
- case 'ready':
163
- if (!readyFired) { readyFired = true; if (options.onReady) options.onReady(); }
164
- break;
165
- case 'sign-in':
166
- if (options.onAuth) options.onAuth({ status: detail.status, signIn: detail.signIn });
167
- break;
168
- case 'not-allowed': if (options.onError) options.onError({ kind: 'not-listed', message: detail.origin }); break;
169
- case 'offline': if (options.onError) options.onError({ kind: 'offline' }); break;
170
- case 'server': if (options.onError) options.onError({ kind: 'server', message: detail.message }); break;
171
- case 'address': if (options.onError) options.onError({ kind: 'address', message: detail.problem }); break;
172
- case 'version': if (options.onError) options.onError({ kind: 'version', message: `${detail.package} / ${detail.server}` }); break;
173
- default:
174
- }
175
- }
176
- function onTheme(detail) {
177
- if (!ended && detail.state === 'failed' && options.onError) options.onError({ kind: 'theme', message: detail.reason });
178
- }
179
-
180
148
  function release() {
181
149
  tellPieces(); // they leave this instance (and ask again) before it ends
182
150
  if (inst) inst.destroy();
183
151
  inst = null;
184
152
  source = null;
185
153
  serverTheme = null;
154
+ serverLink = null;
186
155
  }
187
156
 
188
157
  const api = {
@@ -198,12 +167,12 @@ export function mountScope(host, options = {}) {
198
167
  }
199
168
  if ('useTheme' in next && !!next.useTheme !== props.useTheme) {
200
169
  props.useTheme = !!next.useTheme;
201
- if (props.useTheme) { if (source.config) serverTheme.load(source.config); } else serverTheme.unload();
170
+ serverLink.setUseTheme(props.useTheme);
202
171
  }
203
172
  if (rebuild) {
204
173
  // The new instance is made first, the pieces are told to take it, and the old one ends once they have gone
205
174
  const previous = inst;
206
- serverTheme.destroy(); // its tokens leave this element before the new server's are put on it
175
+ serverLink.destroy(); // its theme's tokens leave this element before the new server's are put on it, and its load says nothing more
207
176
  build();
208
177
  tellPieces();
209
178
  previous.destroy();
@@ -7,7 +7,7 @@
7
7
  * map piece inside its stage (pieces/map.js); a shell holds none of it. Words are `strings` keys (core/strings.js), each element has a `data-corn`
8
8
  * hook and so a `part`, and nothing here is built from data except through `escapeHtml`, `textContent` and a link checked to be http(s).
9
9
  *
10
- * const status = mount(container, inst, { onRetry }) -> { destroy, refuse }
10
+ * const status = mount(container, inst, { onRetry }) -> { destroy, refuse, show, clear }
11
11
  *
12
12
  * It follows the instance's `source` event (engine/source.js) and reads where the load is now from `sourceOf(inst)`, so a piece that joins late
13
13
  * shows the right thing. A polite live region, apart from the card, says each state once (a second `server` error says itself again: it is a
@@ -131,6 +131,10 @@ export function mount(container, inst, { onRetry = () => {}, focusMap = () => {}
131
131
  return {
132
132
  /** Says that this piece cannot have the scope it is in (a second map): the card says why, and the piece draws nothing */
133
133
  refuse(why = 'second-map') { render({ state: why }); },
134
+ /** Shows a state the load did not say (a decision the server refused for want of a sign-in: `{ state: 'sign-in', status, signIn }`), in the same card */
135
+ show(detail) { render(detail); },
136
+ /** Takes what `show` put up away: the card shows where the load is now (nothing, once it is ready) */
137
+ clear() { const now = source ? source.state() : null; render(now && now.state !== 'ready' ? now : { state: 'ready' }); },
134
138
  destroy() {
135
139
  if (ended) return;
136
140
  ended = true;