cornfield 0.50.0 → 0.51.0

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.
Files changed (67) hide show
  1. package/explorer/camera-frame.js +82 -0
  2. package/explorer/camera.js +7 -73
  3. package/explorer/check-model.js +3 -44
  4. package/explorer/cloud-model.js +2 -101
  5. package/explorer/cloud-panel.js +107 -0
  6. package/explorer/css/review.css +2 -0
  7. package/explorer/engine/connection.js +4 -1
  8. package/explorer/engine/map-rect.js +97 -0
  9. package/explorer/engine/player.js +2 -1
  10. package/explorer/engine/proposal.js +28 -7
  11. package/explorer/engine/server-load.js +64 -0
  12. package/explorer/engine/sheets.js +4 -86
  13. package/explorer/engine/source-address.js +58 -0
  14. package/explorer/engine/source.js +16 -45
  15. package/explorer/engine/theme-sheet.js +23 -1
  16. package/explorer/engine/topology.js +1 -1
  17. package/explorer/focus-room.js +1 -7
  18. package/explorer/focusables.js +1 -1
  19. package/explorer/forge-panel.js +36 -2630
  20. package/explorer/index.html +15 -147
  21. package/explorer/instance-state.js +0 -7
  22. package/explorer/instance.js +19 -2
  23. package/explorer/layer-model.js +1 -1
  24. package/explorer/outage-model.js +6 -76
  25. package/explorer/outage-scenario.js +83 -0
  26. package/explorer/page-pieces.js +21 -2
  27. package/explorer/page.js +3 -3
  28. package/explorer/panels.js +1 -5
  29. package/explorer/pieces/layers.js +1 -0
  30. package/explorer/pieces/node-panel.js +19 -8
  31. package/explorer/pieces/proposal.js +9 -0
  32. package/explorer/pieces/review-source.js +84 -0
  33. package/explorer/pieces/review.js +145 -12
  34. package/explorer/pieces/scope.js +23 -54
  35. package/explorer/pieces/status.js +5 -1
  36. package/explorer/pieces/work-agent.js +211 -0
  37. package/explorer/pieces/work-common.js +88 -0
  38. package/explorer/pieces/work-confirm.js +169 -0
  39. package/explorer/pieces/work-data.js +178 -0
  40. package/explorer/pieces/work-deploys.js +104 -0
  41. package/explorer/pieces/work-events.js +285 -0
  42. package/explorer/pieces/work-issues.js +43 -0
  43. package/explorer/pieces/work-markup.js +155 -0
  44. package/explorer/pieces/work-notes.js +177 -0
  45. package/explorer/pieces/work-paint.js +312 -0
  46. package/explorer/pieces/work-prs.js +253 -0
  47. package/explorer/pieces/work-runs.js +387 -0
  48. package/explorer/pieces/work-specs.js +71 -0
  49. package/explorer/pieces/work-threads.js +309 -0
  50. package/explorer/pieces/work.js +285 -0
  51. package/explorer/proposal-marks.js +220 -0
  52. package/explorer/proposal-model.js +23 -211
  53. package/explorer/proposal.js +1 -2
  54. package/explorer/runs-map.js +108 -103
  55. package/explorer/runs-view.js +8 -6
  56. package/explorer/scenario.js +2 -1
  57. package/explorer/scene.js +2 -2
  58. package/explorer/selection-model.js +2 -42
  59. package/explorer/selection-view.js +1 -1
  60. package/explorer/selection-words.js +52 -0
  61. package/explorer/strings.js +1 -1
  62. package/explorer/verdict-paint.js +51 -0
  63. package/explorer/waiting-model.js +12 -12
  64. package/explorer/waiting-view.js +6 -6
  65. package/package.json +1 -1
  66. package/explorer/feedback.js +0 -15
  67. package/explorer/waiting-line.js +0 -14
@@ -17,11 +17,13 @@
17
17
  * proposal:message { text, isError, ways } one line in the bar in place of a proposal: while one opens, or why it did not
18
18
  * proposal:pull-head sha the PR of the open proposal was read: the review column keys what was seen by its head
19
19
  * proposal:focus-title (none) the focus goes to the proposal's name (a Retry in the decision worked; the bar answers)
20
+ * proposal:failed { slug, source, status, notFound, message } a proposal asked for by name did not open, once, with the words the bar says (a host's `cornError`)
20
21
  * changes:peek text the review column's count line for the phone's peek, for the bar to show (pieces/changes.js)
21
22
  * What it asks (`inst.ask`; nobody answering is a no):
22
23
  * proposal:effective proposal -> proposal the proposal the map is drawn from (the what-if editor's, with the edits in); no answer: the proposal itself
23
24
  * proposal:before-close (none) -> false keeps the proposal open (the what-if editor is asking whether to keep its edits)
24
25
  * work:open-specs (none) -> true the Work panel's Specs tab is open for a bad link's way on; no answer: the bar opens its Proposals menu
26
+ * proposal:specs-list (none) -> false there is no list of specs to open here (the review in another app): a bad link's ways leave that button out; no answer: there is one
25
27
  * map:set { nodes, edges } -> true the page lays the map out again from these (view.js setMap, not yet an instance's)
26
28
  * And emits to the node panel: node:show-edge { edge }.
27
29
  *
@@ -32,8 +34,9 @@
32
34
  */
33
35
 
34
36
  import { edgePoint } from '../scene.js';
35
- import { frameNodes, largestGroup, READ_ZOOM, FRAME_ZOOM_MIN } from '../camera.js';
36
- import { PROPOSAL_VIEWS, MARK_WORDS, touchedIds, viewWords, jumpWords, notFoundWords, otherCopies } from '../proposal-model.js';
37
+ import { frameNodes } from '../camera.js';
38
+ import { largestGroup, READ_ZOOM, FRAME_ZOOM_MIN } from '../camera-frame.js';
39
+ import { PROPOSAL_VIEWS, MARK_WORDS, touchedIds, viewWords, jumpWords, notFoundWords, otherCopies, isProposalName, notANameWords } from '../proposal-model.js';
37
40
  import { applyProposal, edgeKey, proposalProblems } from '../../core/proposal.js';
38
41
  import { beginReview, endReview, redrawLayers, reviewLayersLine } from './layers.js';
39
42
  import { visibleMapRect, collapseSheet } from './sheets.js';
@@ -48,8 +51,8 @@ const memory = (inst) => inst.slot('proposal', () => ({ pinnedSource: false, lis
48
51
  /** The name the bar gives the open proposal */
49
52
  export const titleOf = (state) => (state.proposal && typeof state.proposal.title === 'string' && state.proposal.title) || state.proposalSlug || 'Proposal';
50
53
 
51
- /** The way on every bad link offers: the list of specs */
52
- const specsWay = (inst) => ({ label: t(inst, 'openSpecsList'), way: 'specs' });
54
+ /** The way on every bad link offers: the list of specs. Not where the instance says it has none to open (the review in another app asks `proposal:specs-list`: false), so a button never goes nowhere */
55
+ const specsWay = (inst) => (inst.ask('proposal:specs-list') === false ? null : { label: t(inst, 'openSpecsList'), way: 'specs' });
53
56
 
54
57
  // ---------------------------------------------------------------------------
55
58
  // The list the server gives
@@ -116,6 +119,14 @@ export const messageOf = (inst) => memory(inst).message;
116
119
  export async function openProposal(inst, slug, source = null) {
117
120
  const m = memory(inst);
118
121
  const token = ++m.openToken;
122
+ // A value that is not a proposal's name (`..`, a path, a URL, markup: a host's `proposal` or a link) is never put in a request: it would not stay one
123
+ // segment of `/proposals/<name>` (a decision's `/proposals/../review` is `/review`). Said in the bar, as a name that is not found is.
124
+ if (!isProposalName(slug)) {
125
+ const message = notANameWords(slug);
126
+ setMessage(inst, message, true, []);
127
+ inst.emit('proposal:failed', { slug, source, status: 0, notFound: false, message });
128
+ return false;
129
+ }
119
130
  setMessage(inst, `Opening ${slug} …`);
120
131
  try {
121
132
  let res;
@@ -123,8 +134,13 @@ export async function openProposal(inst, slug, source = null) {
123
134
  if (!res.ok) {
124
135
  let why = '';
125
136
  try { why = (await res.json()).error || ''; } catch { /* no body */ }
126
- const err = new Error(res.status === 404 ? notFoundWords(slug, source) : `${slug} could not be opened: ${why || `the server had a problem (error ${res.status}).`}`);
137
+ const refused = res.status === 401 || res.status === 403; // a session that ended, or a login that is not a maintainer's: the sign-in is what to do
138
+ if (refused) inst.emit('auth', { status: res.status, during: 'proposal' });
139
+ // The server's own words, as every other refusal is said (cornfield's answers 401 "Sign in first."); words of ours only when it gave none
140
+ const fallback = refused ? (res.status === 403 ? 'this is for the project\'s maintainers.' : 'you are not signed in.') : `the server had a problem (error ${res.status}).`;
141
+ const err = new Error(res.status === 404 ? notFoundWords(slug, source) : `${slug} could not be opened: ${typeof why === 'string' && why ? why : fallback}`);
127
142
  err.notFound = res.status === 404;
143
+ err.status = res.status;
128
144
  throw err;
129
145
  }
130
146
  const found = res.headers.get('X-Proposal-Source');
@@ -141,12 +157,17 @@ export async function openProposal(inst, slug, source = null) {
141
157
  console.error('Opening the proposal failed', err);
142
158
  // Said plainly, with the ways on: the Specs list, and the same name under another source when the list has one
143
159
  // (a failure that is not "no such proposal" can be asked for again, or let go of: Retry and Close)
144
- setMessage(inst, err.message || `${slug} could not be opened.`, true, err.notFound ? [specsWay(inst)] : [{ label: 'Retry', way: 'retry', slug, source }, { label: 'Close', way: 'close' }]);
160
+ let message = err.message || `${slug} could not be opened.`;
161
+ setMessage(inst, message, true, err.notFound ? [specsWay(inst)].filter(Boolean) : [{ label: 'Retry', way: 'retry', slug, source }, { label: 'Close', way: 'close' }]);
145
162
  if (err.notFound && token === m.openToken) {
146
163
  await loadProposalList(inst);
147
164
  const sources = new Set((Array.isArray(m.listing) ? m.listing : []).map((e) => e && e.source));
148
- if (token === m.openToken) setMessage(inst, notFoundWords(slug, source, sources), true, [...otherCopies(m.listing, slug, source).map((c) => ({ label: c.label, way: 'open', slug: c.slug, source: c.source })), specsWay(inst)]);
165
+ if (token === m.openToken) {
166
+ message = notFoundWords(slug, source, sources);
167
+ setMessage(inst, message, true, [...otherCopies(m.listing, slug, source).map((c) => ({ label: c.label, way: 'open', slug: c.slug, source: c.source })), specsWay(inst)].filter(Boolean));
168
+ }
149
169
  }
170
+ if (token === m.openToken) inst.emit('proposal:failed', { slug, source, status: err.status || 0, notFound: !!err.notFound, message });
150
171
  return false;
151
172
  }
152
173
  }
@@ -0,0 +1,64 @@
1
+ /**
2
+ * @module explorer/engine/server-load
3
+ *
4
+ * The load from a cornfield server and its theme, on one instance (spec 0011 D6, D7): what a scope (pieces/scope.js) and a review with a `src`
5
+ * (pieces/review-source.js) both start, written once. It makes the load (engine/source.js: the config and the map with the session, the states)
6
+ * and the server's theme (engine/theme-sheet.js: its tokens on `host`, its rules for the shadow roots that adopt it, light or dark as the element's
7
+ * `theme`, the page's `data-theme` or the system's say), and turns the instance's `source` and `theme` events into the callbacks a host hears.
8
+ *
9
+ * const link = connectServer(inst, { host, tokens, version, pageUrl, theme: () => choice, useTheme: () => on, onConfig, onReady, onAuth, onError, onMode, onSheet })
10
+ * -> { source, theme, follow, setUseTheme(on), destroy }
11
+ *
12
+ * `onReady()` the load is ready (each time it is); `onAuth({ status, signIn })` a sign-in is needed; `onError({ kind, message })` a state that is a
13
+ * failure (engine/source.js `errorOf`) or a theme that failed (`theme`); `onMode()` the light or dark the tokens are for changed; `onSheet(detail)` the
14
+ * theme's sheet came, went or failed (the instance's `theme` event). Ends with `destroy()`.
15
+ */
16
+
17
+ import { createSource, errorOf } from './source.js';
18
+ import { createServerTheme, modeOf, watchMode } from './theme-sheet.js';
19
+
20
+ /**
21
+ * @param {ReturnType<typeof import('../instance.js').createInstance>} inst
22
+ * @param {object} o see the top of this file
23
+ */
24
+ export function connectServer(inst, o) {
25
+ const call = (fn, ...args) => { if (!ended && typeof fn === 'function') fn(...args); };
26
+ let ended = false;
27
+ const theme = createServerTheme(inst, { defaults: o.tokens || '' });
28
+ theme.tokensOn(o.host);
29
+ const mode = () => modeOf(inst, o.theme());
30
+ /** The element's choice, the page's or the system's light and dark changed: the tokens follow */
31
+ const follow = () => { if (ended) return; theme.setMode(mode()); call(o.onMode); };
32
+ const source = createSource(inst, {
33
+ version: o.version || '',
34
+ pageUrl: o.pageUrl,
35
+ onConfig: (config) => { call(o.onConfig, config); if (!ended && o.useTheme()) theme.load(config); },
36
+ });
37
+ const offs = [
38
+ inst.on('source', (detail) => {
39
+ if (detail.state === 'ready') { call(o.onReady); return; }
40
+ if (detail.state === 'sign-in') { call(o.onAuth, { status: detail.status, signIn: detail.signIn }); return; }
41
+ const error = errorOf(detail);
42
+ if (error) call(o.onError, error);
43
+ }),
44
+ inst.on('theme', (detail) => {
45
+ call(o.onSheet, detail);
46
+ if (detail.state === 'failed') call(o.onError, { kind: 'theme', message: detail.reason });
47
+ }),
48
+ ];
49
+ watchMode(inst, follow);
50
+ theme.setMode(mode());
51
+ return {
52
+ source,
53
+ theme,
54
+ follow,
55
+ /** The server's theme on or off */
56
+ setUseTheme(on) { if (ended) return; if (on) { if (source.config) theme.load(source.config); } else theme.unload(); },
57
+ destroy() {
58
+ if (ended) return;
59
+ ended = true;
60
+ offs.forEach((off) => off());
61
+ theme.destroy();
62
+ },
63
+ };
64
+ }
@@ -19,45 +19,14 @@
19
19
  * take `inst` first. A node panel registers its own sheet (pieces/node-panel.js); explorer/sheets.js keeps the old names for the page.
20
20
  */
21
21
 
22
- import { createSheetModel, sheetCap } from '../sheet-model.js';
23
- import { freeRect } from '../camera.js';
22
+ import { sheetCap } from '../sheet-model.js';
23
+ import { PHONE_QUERY, sheetsOf, isPhone, stageOf, measureCovered, visibleMapRect } from './map-rect.js';
24
+
25
+ export { PHONE_QUERY, isPhone, measureCovered, visibleMapRect };
24
26
 
25
- /** The width below which the sheets apply (matches the CSS) */
26
- export const PHONE_QUERY = '(max-width: 767px)';
27
27
  /** A drag on the handle longer than this (px) is a swipe, not a tap */
28
28
  const SWIPE_PX = 20;
29
29
 
30
- /** What the instance keeps of its sheets */
31
- function sheetsOf(inst) {
32
- return inst.slot('sheets', () => ({
33
- model: createSheetModel(),
34
- elements: new Map(), // id -> the sheet's element
35
- options: new Map(), // id -> { stub?: () => { title: string, badge?: string, label?: string }, away?: () => void } what the sheet's owner gave it
36
- offs: new Map(), // id -> how to remove the listeners bound on the sheet and its handle
37
- away: new Set(), // sheets displaced by the other of their group: open on the page, hidden until opened again
38
- listeners: new Set(),
39
- dock: null,
40
- box: null, // the element whose width says phone, instead of the window's (setPhoneBox)
41
- lastCovered: 0,
42
- observers: [],
43
- wiredDock: null,
44
- documentWired: false,
45
- }));
46
- }
47
-
48
- /** The width of a box below which it is a phone's (the CSS's `@container corn-box (max-width: 767px)`) */
49
- const PHONE_WIDTH = 768;
50
-
51
- /**
52
- * Whether the instance is laid out as a phone: the window's width on cornfield's page (PHONE_QUERY), or, where the instance has a box of its own
53
- * (`setPhoneBox`: the one-tag review in another app's page), that box's width, which is what the stylesheets' container queries ask
54
- */
55
- export const isPhone = (inst) => {
56
- const { box } = sheetsOf(inst);
57
- if (box) return box.isConnected && box.clientWidth > 0 && box.clientWidth < PHONE_WIDTH;
58
- return !!(inst.win && typeof inst.win.matchMedia === 'function' && inst.win.matchMedia(PHONE_QUERY).matches);
59
- };
60
-
61
30
  /** Makes `el`'s width, not the window's, say whether the instance is a phone's (the review piece's box in another app's page); null goes back to the window's */
62
31
  export function setPhoneBox(inst, el) {
63
32
  sheetsOf(inst).box = el || null;
@@ -82,8 +51,6 @@ export function onPhoneChange(inst, fn) {
82
51
  return () => {};
83
52
  };
84
53
 
85
- const stageOf = (inst, S) => (S.dock && S.dock.parentElement) || (inst.state.canvas ? inst.state.canvas.parentElement : null);
86
-
87
54
  /** 'expanded', 'stub' or 'peek' for a registered sheet (a sheet that is not open is a peek, as it is when it opens); undefined for one that is not registered */
88
55
  export const sheetState = (inst, id) => { const st = sheetsOf(inst).model.stateOf(id); return st === 'hidden' ? 'peek' : st; };
89
56
  /** The id of the expanded sheet, or null */
@@ -237,55 +204,6 @@ function markLast(inst) {
237
204
  if (last) last.setAttribute('data-sheet-last', '');
238
205
  }
239
206
 
240
- /**
241
- * The height of the map the sheets hide, in px: the dock's height on a phone, 0 anywhere else.
242
- * Also written to `state.coveredBottom` and to `--hx-covered` on the stage. Without a dock on the
243
- * page it returns what `state.coveredBottom` holds.
244
- */
245
- export function measureCovered(inst) {
246
- const S = sheetsOf(inst);
247
- const { state } = inst;
248
- if (!S.dock || !S.dock.isConnected) return state.coveredBottom || 0;
249
- const covered = isPhone(inst) ? Math.round(S.dock.offsetHeight || 0) : 0;
250
- state.coveredBottom = covered;
251
- const stage = stageOf(inst, S);
252
- if (stage) stage.style.setProperty('--hx-covered', `${covered}px`);
253
- if (covered !== S.lastCovered) {
254
- S.lastCovered = covered;
255
- S.listeners.forEach((fn) => fn());
256
- }
257
- return covered;
258
- }
259
-
260
- /**
261
- * The part of the map nothing covers, in the canvas's own CSS px: what the camera should frame a node into.
262
- * On a phone the dock's sheets cover the bottom; from 768px the proposal bar covers the top (and the change list it grows to hold),
263
- * the node panel the right, the Work panel and the review column the left and the scenario player the bottom. Without a layout (no page) it is the whole canvas.
264
- * @returns {{ x: number, y: number, width: number, height: number }}
265
- */
266
- export function visibleMapRect(inst) {
267
- const { state } = inst;
268
- const covers = { top: 0, bottom: 0, left: 0, right: 0 };
269
- const canvas = state.canvas;
270
- const shown = (el) => !!el && !el.hidden && el.isConnected;
271
- if (isPhone(inst)) covers.bottom = measureCovered(inst) + 8;
272
- else if (canvas && typeof canvas.getBoundingClientRect === 'function') {
273
- const c = canvas.getBoundingClientRect();
274
- const bar = inst.el('proposal-bar');
275
- if (shown(bar)) covers.top = Math.max(0, bar.getBoundingClientRect().bottom - c.top) + 8;
276
- const drawer = inst.el('spec-drawer');
277
- if (shown(drawer) && drawer.classList.contains('drawer-open')) covers.right = drawer.offsetWidth; // its width, not its box: it slides in
278
- const forge = inst.el('forge-panel');
279
- if (shown(forge) && forge.classList.contains('forge-open')) covers.left = forge.offsetWidth;
280
- // the review column (review-column.js) is docked on the left under the bar: its right edge is what it covers, past the Work panel's when both are open
281
- const column = inst.el('review-column');
282
- if (shown(column)) covers.left = Math.max(covers.left, Math.max(0, column.getBoundingClientRect().right - c.left) + 8);
283
- const player = inst.root ? inst.root.querySelector('.hx-player') : null;
284
- if (shown(player)) covers.bottom = Math.max(0, c.bottom - player.getBoundingClientRect().top) + 8;
285
- }
286
- return freeRect(state.width || 0, state.height || 0, covers);
287
- }
288
-
289
207
  // ---------------------------------------------------------------------------
290
208
  // Registering and changing sheets
291
209
  // ---------------------------------------------------------------------------
@@ -0,0 +1,58 @@
1
+ /**
2
+ * @module explorer/engine/source-address
3
+ *
4
+ * The addresses of a cornfield server (spec 0011 D6), apart from the load that uses them (engine/source.js re-exports all of this): checking a `src`,
5
+ * the server's sign-in and the origin of a page. They are small and a piece that has a `src` needs them at once (the instance's base is made from
6
+ * the address), while the load itself, its states and the server's theme are a chunk that comes later (pieces/review-source.js, pieces/scope.js).
7
+ */
8
+
9
+ export const SIGN_IN_PATH = '/auth/start';
10
+
11
+ /** A control character, a space or a backslash (a browser reads `\` as `/`): never in an address */
12
+ const BAD_CHAR = /[\u0000- \u007f\\]/;
13
+
14
+ /**
15
+ * An address of a cornfield server, checked: an http(s) origin with an optional path, and nothing else (no user name, no query, no fragment).
16
+ * `base` is what the instance is made with: the origin and the path without a trailing slash.
17
+ * @param {unknown} src
18
+ * @returns {{ ok: true, base: string, origin: string } | { ok: false, problem: string }}
19
+ */
20
+ export function parseSource(src) {
21
+ if (typeof src !== 'string' || !src.trim()) return { ok: false, problem: 'is empty' };
22
+ const text = src.trim();
23
+ if (BAD_CHAR.test(text)) return { ok: false, problem: 'has a space, a control character or a backslash' };
24
+ let u;
25
+ try { u = new URL(text); } catch { return { ok: false, problem: 'is not an address (an http or https address, as the server is opened in a browser)' }; }
26
+ if (u.protocol !== 'https:' && u.protocol !== 'http:') return { ok: false, problem: 'is not http or https' };
27
+ if (!/^https?:\/\/[^/?#]/i.test(text)) return { ok: false, problem: 'has no host' };
28
+ if (u.username || u.password) return { ok: false, problem: 'has a user name or password' };
29
+ if (text.includes('?') || text.includes('#')) return { ok: false, problem: 'has a query or a fragment' };
30
+ return { ok: true, base: u.origin + u.pathname.replace(/\/+$/, ''), origin: u.origin };
31
+ }
32
+
33
+ /**
34
+ * The server's sign-in, which ends on the page it was asked from: `<base>/auth/start?returnTo=<page URL>` (docs/sign-in.md). The server follows
35
+ * `returnTo` only for an origin its `embed.origins` lists. A page that is not http(s) (a file, about:blank) has nothing to return to. A user name
36
+ * or password in the page's address (`https://user:pass@tasks.example.com/`) is never sent to the server: it is taken out (the server would refuse
37
+ * such a `returnTo` anyway).
38
+ * @param {string} base
39
+ * @param {string} pageUrl
40
+ */
41
+ export function signInUrl(base, pageUrl) {
42
+ let back = '';
43
+ if (typeof pageUrl === 'string' && /^https?:\/\//i.test(pageUrl)) {
44
+ try {
45
+ const u = new URL(pageUrl);
46
+ u.username = '';
47
+ u.password = '';
48
+ back = `?returnTo=${encodeURIComponent(u.href)}`;
49
+ } catch { back = ''; }
50
+ }
51
+ return `${base}${SIGN_IN_PATH}${back}`;
52
+ }
53
+
54
+ /** The origin of a page address, or '' */
55
+ export function originOf(url) {
56
+ try { return /^https?:/i.test(url) ? new URL(url).origin : ''; } catch { return ''; }
57
+ }
58
+
@@ -33,34 +33,31 @@ import { setStrings } from './strings.js';
33
33
  import { setProjectLayers } from './layers.js';
34
34
  import { mapStyleOf } from './map-style.js';
35
35
  import { sessionInit } from './connection.js';
36
+ import { parseSource, signInUrl, originOf, SIGN_IN_PATH } from './source-address.js';
37
+
38
+ export { parseSource, signInUrl, originOf, SIGN_IN_PATH };
36
39
 
37
40
  export const CONFIG_PATH = '/cornfield/config.json';
38
41
  export const TOPOLOGY_PATH = '/topology.json';
39
42
  /** A route that answers a listed origin without a session: the reach test for a fetch that got no answer */
40
43
  export const REACH_PATH = '/cornfield/theme.css';
41
- export const SIGN_IN_PATH = '/auth/start';
42
44
  export const SOURCE_STATES = Object.freeze(['loading', 'ready', 'sign-in', 'not-allowed', 'offline', 'server', 'address', 'version']);
43
45
 
44
- /** A control character, a space or a backslash (a browser reads `\` as `/`): never in an address */
45
- const BAD_CHAR = /[\u0000- \u007f\\]/;
46
-
47
46
  /**
48
- * An address of a cornfield server, checked: an http(s) origin with an optional path, and nothing else (no user name, no query, no fragment).
49
- * `base` is what the instance is made with: the origin and the path without a trailing slash.
50
- * @param {unknown} src
51
- * @returns {{ ok: true, base: string, origin: string } | { ok: false, problem: string }}
47
+ * What a state of the load tells a host as `cornError` (`{ kind, message? }`), or null for a state that is not a failure: the one place the states and the
48
+ * error kinds meet (pieces/scope.js and pieces/review-source.js both say them)
49
+ * @param {{ state: string, [key: string]: any }} detail a `source` event's detail
50
+ * @returns {{ kind: 'not-listed' | 'offline' | 'server' | 'address' | 'version', message?: string } | null}
52
51
  */
53
- export function parseSource(src) {
54
- if (typeof src !== 'string' || !src.trim()) return { ok: false, problem: 'is empty' };
55
- const text = src.trim();
56
- if (BAD_CHAR.test(text)) return { ok: false, problem: 'has a space, a control character or a backslash' };
57
- let u;
58
- try { u = new URL(text); } catch { return { ok: false, problem: 'is not an address (an http or https address, as the server is opened in a browser)' }; }
59
- if (u.protocol !== 'https:' && u.protocol !== 'http:') return { ok: false, problem: 'is not http or https' };
60
- if (!/^https?:\/\/[^/?#]/i.test(text)) return { ok: false, problem: 'has no host' };
61
- if (u.username || u.password) return { ok: false, problem: 'has a user name or password' };
62
- if (text.includes('?') || text.includes('#')) return { ok: false, problem: 'has a query or a fragment' };
63
- return { ok: true, base: u.origin + u.pathname.replace(/\/+$/, ''), origin: u.origin };
52
+ export function errorOf(detail) {
53
+ switch (detail.state) {
54
+ case 'not-allowed': return { kind: 'not-listed', message: detail.origin };
55
+ case 'offline': return { kind: 'offline' };
56
+ case 'server': return { kind: 'server', message: detail.message };
57
+ case 'address': return { kind: 'address', message: detail.problem };
58
+ case 'version': return { kind: 'version', message: `${detail.package} / ${detail.server}` };
59
+ default: return null;
60
+ }
64
61
  }
65
62
 
66
63
  /** The numbers of a version, or null */
@@ -84,27 +81,6 @@ export function compareVersions(a, b) {
84
81
  return x[2] !== y[2] ? 'patch' : 'same';
85
82
  }
86
83
 
87
- /**
88
- * The server's sign-in, which ends on the page it was asked from: `<base>/auth/start?returnTo=<page URL>` (docs/sign-in.md). The server follows
89
- * `returnTo` only for an origin its `embed.origins` lists. A page that is not http(s) (a file, about:blank) has nothing to return to. A user name
90
- * or password in the page's address (`https://user:pass@tasks.example.com/`) is never sent to the server: it is taken out (the server would refuse
91
- * such a `returnTo` anyway).
92
- * @param {string} base
93
- * @param {string} pageUrl
94
- */
95
- export function signInUrl(base, pageUrl) {
96
- let back = '';
97
- if (typeof pageUrl === 'string' && /^https?:\/\//i.test(pageUrl)) {
98
- try {
99
- const u = new URL(pageUrl);
100
- u.username = '';
101
- u.password = '';
102
- back = `?returnTo=${encodeURIComponent(u.href)}`;
103
- } catch { back = ''; }
104
- }
105
- return `${base}${SIGN_IN_PATH}${back}`;
106
- }
107
-
108
84
  /** Why a read failed: `auth` (401 or 403: sign in), `server` (it answered, and not with what was asked for) or `network` (no answer the page may read) */
109
85
  export class SourceError extends Error {
110
86
  /** @param {'auth' | 'server' | 'network'} kind @param {string} message @param {{ status?: number, cause?: unknown }} [extra] */
@@ -305,11 +281,6 @@ export function createSource(inst, { version = '', pageUrl = () => '', onConfig
305
281
  return source;
306
282
  }
307
283
 
308
- /** The origin of a page address, or '' */
309
- export function originOf(url) {
310
- try { return /^https?:/i.test(url) ? new URL(url).origin : ''; } catch { return ''; }
311
- }
312
-
313
284
  const holderOf = (inst) => inst.slot('source', () => ({ source: null }));
314
285
  /** The instance's source, if a scope or a map with a `src` made one (a piece that joins late reads what it has said); else null */
315
286
  export const sourceOf = (inst) => holderOf(inst).source;
@@ -247,6 +247,28 @@ export async function readCapped(res, max, what = 'the answer') {
247
247
  return text;
248
248
  }
249
249
 
250
+ /**
251
+ * The mode ('light' | 'dark') the server's tokens are for: the element's own `theme` choice, else the page's `data-theme`, else the system's.
252
+ * @param {ReturnType<typeof import('../instance.js').createInstance>} inst
253
+ * @param {unknown} choice 'light' | 'dark' | 'auto' (anything else is 'auto')
254
+ */
255
+ export function modeOf(inst, choice) {
256
+ if (choice === 'light' || choice === 'dark') return choice;
257
+ const root = inst.doc && inst.doc.documentElement;
258
+ const own = root ? root.getAttribute('data-theme') : null;
259
+ if (own === 'light' || own === 'dark') return own;
260
+ const query = inst.win && inst.win.matchMedia ? inst.win.matchMedia('(prefers-color-scheme: light)') : null;
261
+ return query && query.matches ? 'light' : 'dark';
262
+ }
263
+
264
+ /** Calls `onChange` when the page's own `data-theme` or the system's light and dark change (they are what `modeOf` reads); ends with the instance */
265
+ export function watchMode(inst, onChange) {
266
+ const watch = inst.win && inst.win.MutationObserver && inst.doc && inst.doc.documentElement ? new inst.win.MutationObserver(onChange) : null;
267
+ if (watch) { watch.observe(inst.doc.documentElement, { attributes: true, attributeFilter: ['data-theme'] }); inst.own(() => watch.disconnect()); }
268
+ const query = inst.win && inst.win.matchMedia ? inst.win.matchMedia('(prefers-color-scheme: light)') : null;
269
+ if (query && query.addEventListener) { query.addEventListener('change', onChange); inst.own(() => query.removeEventListener('change', onChange)); }
270
+ }
271
+
250
272
  /**
251
273
  * The server's theme for one scope.
252
274
  * @param {ReturnType<typeof import('../instance.js').createInstance>} inst
@@ -302,7 +324,7 @@ export function createServerTheme(inst, { defaults = '' } = {}) {
302
324
 
303
325
  const fetchText = async (path, signal) => {
304
326
  // The theme answers a listed origin without a session and without Allow-Credentials: asked for without credentials
305
- const res = await inst.fetch(path, { credentials: 'omit', signal });
327
+ const res = await inst.fetch(path, { credentials: 'omit', redirect: 'error', signal }); // and never elsewhere: a redirect is not followed
306
328
  if (!res.ok) throw new Error(`GET ${path} answered ${res.status}`);
307
329
  return readCapped(res, MAX_THEME_TEXT, path);
308
330
  };
@@ -18,7 +18,7 @@
18
18
  */
19
19
 
20
20
  import { buildDataFlow } from '../flow-build.js';
21
- import { orderAddedLast, pinLanes, placeAddedNodes } from '../proposal-model.js';
21
+ import { orderAddedLast, pinLanes, placeAddedNodes } from '../proposal-marks.js';
22
22
  import { computeDegreeCentrality, computeLaneLayout, layoutOrbit } from './layout.js';
23
23
 
24
24
  /** The nodes and edges of a topology that have what the engine needs (an id, and two ends), as arrays; anything else is dropped */
@@ -4,6 +4,7 @@
4
4
  * A control that is tabbed to inside a strip that scrolls sideways (the Work panel's tabs) is brought fully into view, ring and all
5
5
  * (CF review F54). A browser scrolls a focused control only until it is "mostly" visible, and the last tab was left a few pixels under
6
6
  * the strip's edge, with its focus ring cut. `scroll-padding-inline` in css/work.css says how much room to leave; this asks for the scroll.
7
+ * The Work piece (pieces/work.js) listens for focus in its own root and asks.
7
8
  */
8
9
 
9
10
  /** The strips: a scroll container whose children are tabbed to */
@@ -17,10 +18,3 @@ export function revealInStrip(el) {
17
18
  el.scrollIntoView({ block: 'nearest', inline: 'nearest' });
18
19
  return true;
19
20
  }
20
-
21
- /** Listens for focus on the whole page, once. Returns how to stop. */
22
- export function watchFocusRoom(doc = document) {
23
- const on = (event) => revealInStrip(event.target);
24
- doc.addEventListener('focusin', on);
25
- return () => doc.removeEventListener('focusin', on);
26
- }
@@ -28,7 +28,7 @@ export function trapTab(e, root) {
28
28
  const stops = focusableIn(root);
29
29
  e.preventDefault();
30
30
  if (!stops.length) return true;
31
- const at = stops.indexOf(document.activeElement);
31
+ const at = stops.indexOf(root.getRootNode().activeElement); // the focus in the dialog's own tree: a shadow root's, not the host's
32
32
  const next = e.shiftKey ? (at <= 0 ? stops.length - 1 : at - 1) : (at === -1 || at === stops.length - 1 ? 0 : at + 1);
33
33
  stops[next].focus();
34
34
  return true;