roamwright 0.61.16 → 0.61.17
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.
- package/README.md +25 -24
- package/examples/world-map.html +162 -0
- package/examples/world-map.js +475 -0
- package/index.js +67 -0
- package/package.json +1 -1
- package/rendering/map-glyphs.js +494 -0
- package/rendering/map-input.js +143 -0
- package/rendering/map-labels.js +181 -0
- package/rendering/map-relief.js +330 -0
- package/rendering/map-signs.js +124 -0
- package/rendering/place-names.js +408 -0
- package/rendering/portrait-studio.js +213 -0
- package/rendering/screen-pick.js +75 -0
- package/runtime/build-freshness.js +133 -0
- package/runtime/compass-strip.js +232 -0
- package/runtime/context-lost.js +108 -0
- package/runtime/doorways.js +98 -0
- package/runtime/hud-frame.js +74 -0
- package/runtime/map-relief.js +236 -0
- package/runtime/map-spot.js +120 -0
- package/runtime/map-view.js +229 -0
- package/runtime/panel-shell.js +90 -0
- package/runtime/relation-graph.js +163 -0
- package/runtime/stage-frame.js +263 -0
- package/runtime/url-router.js +162 -0
- package/runtime/way-back.js +71 -0
- package/runtime/whereabouts.js +210 -0
- package/runtime/world-controls.js +265 -0
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Clustered SVG relationship graph renderer with separating-axis oriented bounding box (OBB)
|
|
3
|
+
* collision avoidance for rotated edge labels and an accessible collapsible connection list.
|
|
4
|
+
* Worker-safe: returns pure SVG/HTML markup with zero DOM or Three.js dependencies.
|
|
5
|
+
* @module
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Tests whether two centred, optionally rotated 2D boxes overlap via the separating-axis theorem.
|
|
10
|
+
*
|
|
11
|
+
* @param {{ x: number, y: number, w: number, h: number, angle?: number }} a First box (`w`, `h` are half-extents).
|
|
12
|
+
* @param {{ x: number, y: number, w: number, h: number, angle?: number }} b Second box (`w`, `h` are half-extents).
|
|
13
|
+
* @returns {boolean} True if the two boxes intersect.
|
|
14
|
+
*/
|
|
15
|
+
export function boxesOverlapOBB(a, b) {
|
|
16
|
+
const angleA = a.angle ?? 0;
|
|
17
|
+
const angleB = b.angle ?? 0;
|
|
18
|
+
return [angleA, angleA + Math.PI / 2, angleB, angleB + Math.PI / 2].every(axis => {
|
|
19
|
+
const extent = (box, angle) => box.w * Math.abs(Math.cos(axis - angle)) + box.h * Math.abs(Math.sin(axis - angle));
|
|
20
|
+
const distance = (a.x - b.x) * Math.cos(axis) + (a.y - b.y) * Math.sin(axis);
|
|
21
|
+
return Math.abs(distance) < extent(a, angleA) + extent(b, angleB);
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Computes clipped arrow endpoints (clear of node circles and captions below them) and places an
|
|
27
|
+
* edge label parallel to the arrow without overlapping existing obstacle boxes. Appends the
|
|
28
|
+
* chosen label box to `obstacles`.
|
|
29
|
+
*
|
|
30
|
+
* @param {{ x: number, y: number, nameWidth: number, cluster: number }} from
|
|
31
|
+
* @param {{ x: number, y: number, nameWidth: number, cluster: number }} to
|
|
32
|
+
* @param {string} verb Short label text drawn along the arrow.
|
|
33
|
+
* @param {Array<{ x: number, y: number, w: number, h: number, angle?: number }>} obstacles Existing obstacle boxes (mutated in place).
|
|
34
|
+
* @param {object} [options]
|
|
35
|
+
* @param {number} [options.radius=23] Node avatar radius in SVG units.
|
|
36
|
+
* @param {number} [options.labelHeight=21] Caption height below each node in SVG units.
|
|
37
|
+
* @returns {{ x1: number, y1: number, x2: number, y2: number, angle: number, label: { x: number, y: number, w: number, h: number, angle: number } }}
|
|
38
|
+
*/
|
|
39
|
+
export function placeLinkLabel(from, to, verb, obstacles, { radius = 23, labelHeight = 21 } = {}) {
|
|
40
|
+
const dx = to.x - from.x;
|
|
41
|
+
const dy = to.y - from.y;
|
|
42
|
+
const length = Math.hypot(dx, dy);
|
|
43
|
+
const ux = dx / length;
|
|
44
|
+
const uy = dy / length;
|
|
45
|
+
const nameDepth = node => Math.min((radius + labelHeight) / Math.abs(uy), node.nameWidth / Math.abs(ux));
|
|
46
|
+
const start = dy > 0 && radius * Math.abs(ux / uy) < from.nameWidth ? nameDepth(from) : radius;
|
|
47
|
+
const end = dy < 0 && radius * Math.abs(ux / uy) < to.nameWidth ? nameDepth(to) : radius;
|
|
48
|
+
const x1 = from.x + ux * start;
|
|
49
|
+
const y1 = from.y + uy * start;
|
|
50
|
+
const x2 = to.x - ux * end;
|
|
51
|
+
const y2 = to.y - uy * end;
|
|
52
|
+
const angle = Math.atan2(dy * Math.sign(dx || 1), Math.abs(dx));
|
|
53
|
+
const w = verb.length * 3.25 + 3;
|
|
54
|
+
const h = 8;
|
|
55
|
+
const center = { x: (x1 + x2) / 2, y: (y1 + y2) / 2, w, h, angle };
|
|
56
|
+
const candidates = [];
|
|
57
|
+
for (const offset of [0, -10, 10, -17, 17, -24, 24]) {
|
|
58
|
+
for (const t of [0, -0.12, 0.12, -0.24, 0.24]) {
|
|
59
|
+
candidates.push({
|
|
60
|
+
x: center.x + (x2 - x1) * t - offset * Math.sin(angle),
|
|
61
|
+
y: center.y + (y2 - y1) * t + offset * Math.cos(angle),
|
|
62
|
+
w,
|
|
63
|
+
h,
|
|
64
|
+
angle,
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
const label = candidates.find(candidate => !obstacles.some(box => boxesOverlapOBB(candidate, box))) ?? center;
|
|
69
|
+
obstacles.push(label);
|
|
70
|
+
return { x1, y1, x2, y2, angle, label };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Renders a clustered relationship graph as an SVG diagram followed by a collapsible HTML list
|
|
75
|
+
* of all connections.
|
|
76
|
+
*
|
|
77
|
+
* @param {object} options
|
|
78
|
+
* @param {ReadonlyArray<{ title: string, people: ReadonlyArray<string> }>} options.clusters Node groups.
|
|
79
|
+
* @param {ReadonlyArray<{ title: string, rows: ReadonlyArray<[string, string, string, string?]> }>} options.links Plotted relationship groups.
|
|
80
|
+
* @param {ReadonlyArray<{ title: string, rows: ReadonlyArray<[string, string, string]> }>} [options.listOnly=[]] Extra connections shown only in the text list.
|
|
81
|
+
* @param {ReadonlyArray<{ color: string, box: [number, number, number, number], titleOffset?: number, spots: ReadonlyArray<[number, number]> }>} options.layout Fixed cluster frames and node coordinates.
|
|
82
|
+
* @param {(id: string) => string} options.getName Resolves a node id to its display name.
|
|
83
|
+
* @param {(id: string, name: string, small: boolean) => string} options.renderAvatar Renders node avatar HTML.
|
|
84
|
+
* @param {number} [options.radius=23]
|
|
85
|
+
* @param {number} [options.labelHeight=21]
|
|
86
|
+
* @param {readonly [number, number]} [options.viewBox=[1000, 603]]
|
|
87
|
+
* @param {string} [options.ariaLabel='Character relationships']
|
|
88
|
+
* @param {string} [options.listSummary='Read the connections']
|
|
89
|
+
* @returns {string} SVG diagram + `<details>` connection list markup.
|
|
90
|
+
*/
|
|
91
|
+
export function renderRelationGraph({
|
|
92
|
+
clusters,
|
|
93
|
+
links,
|
|
94
|
+
listOnly = [],
|
|
95
|
+
layout,
|
|
96
|
+
getName,
|
|
97
|
+
renderAvatar,
|
|
98
|
+
radius = 23,
|
|
99
|
+
labelHeight = 21,
|
|
100
|
+
viewBox = [1000, 603],
|
|
101
|
+
ariaLabel = 'Character relationships',
|
|
102
|
+
listSummary = 'Read the connections',
|
|
103
|
+
}) {
|
|
104
|
+
const nodes = new Map();
|
|
105
|
+
const obstacles = [];
|
|
106
|
+
const clusterSvg = clusters.map((cluster, index) => {
|
|
107
|
+
const spec = layout[index];
|
|
108
|
+
cluster.people.forEach((id, i) => {
|
|
109
|
+
const [x, y] = spec.spots[i];
|
|
110
|
+
const nameWidth = getName(id).length * 3.8 + 4;
|
|
111
|
+
nodes.set(id, { x, y, nameWidth, cluster: index });
|
|
112
|
+
obstacles.push({ x, y, w: radius, h: radius }, { x, y: y + radius + 8, w: nameWidth, h: 9 });
|
|
113
|
+
});
|
|
114
|
+
const [x, y, width, height] = spec.box;
|
|
115
|
+
const titleOffset = spec.titleOffset ?? 25;
|
|
116
|
+
return `<g style="--cluster:${spec.color}">
|
|
117
|
+
<rect class="pweb-cluster" x="${x}" y="${y}" width="${width}" height="${height}" rx="16"/>
|
|
118
|
+
<text class="pweb-title" x="${x + 17}" y="${y + titleOffset}">${cluster.title}</text>
|
|
119
|
+
<marker id="pweb-arrow-${index}" viewBox="0 0 8 8" refX="8" refY="4" markerWidth="8" markerHeight="8" markerUnits="userSpaceOnUse" orient="auto">
|
|
120
|
+
<path d="M0 0L8 4L0 8L2 4Z" fill="${spec.color}"/>
|
|
121
|
+
</marker>
|
|
122
|
+
</g>`;
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
const linkParts = links.flatMap(({ rows }) =>
|
|
126
|
+
rows.map(([fromId, verb, toId, short]) => {
|
|
127
|
+
const from = nodes.get(fromId);
|
|
128
|
+
const to = nodes.get(toId);
|
|
129
|
+
const placed = placeLinkLabel(from, to, short || verb, obstacles, { radius, labelHeight });
|
|
130
|
+
const description = `${getName(fromId)} ${verb} ${getName(toId)}`;
|
|
131
|
+
return {
|
|
132
|
+
line: `<path d="M${placed.x1} ${placed.y1}L${placed.x2} ${placed.y2}" stroke="${layout[from.cluster].color}" marker-end="url(#pweb-arrow-${from.cluster})" role="img" aria-label="${description}"/>`,
|
|
133
|
+
label: `<text transform="translate(${placed.label.x} ${placed.label.y}) rotate(${(placed.angle * 180) / Math.PI})" dominant-baseline="central">${short || verb}</text>`,
|
|
134
|
+
};
|
|
135
|
+
}),
|
|
136
|
+
);
|
|
137
|
+
|
|
138
|
+
const peopleSvg = Array.from(
|
|
139
|
+
nodes,
|
|
140
|
+
([id, node]) => `<foreignObject x="${node.x - 65}" y="${node.y - radius}" width="130" height="66">
|
|
141
|
+
<button class="pweb-person" data-actor="${id}">${renderAvatar(id, getName(id), true)}<b>${getName(id)}</b></button>
|
|
142
|
+
</foreignObject>`,
|
|
143
|
+
);
|
|
144
|
+
|
|
145
|
+
const listHtml = [...links, ...listOnly]
|
|
146
|
+
.map(
|
|
147
|
+
({ title, rows }) =>
|
|
148
|
+
`<h4>${title}</h4><ul>${rows
|
|
149
|
+
.map(
|
|
150
|
+
([from, verb, to]) =>
|
|
151
|
+
`<li><button data-actor="${from}">${getName(from)}</button> ${verb} <button data-actor="${to}">${getName(to)}</button></li>`,
|
|
152
|
+
)
|
|
153
|
+
.join('')}</ul>`,
|
|
154
|
+
)
|
|
155
|
+
.join('');
|
|
156
|
+
|
|
157
|
+
return `<svg class="pweb" viewBox="0 0 ${viewBox[0]} ${viewBox[1]}" xmlns="http://www.w3.org/2000/svg" role="group" aria-label="${ariaLabel}">
|
|
158
|
+
<g aria-hidden="true">${clusterSvg.join('')}</g>
|
|
159
|
+
<g class="pweb-lines">${linkParts.map(link => link.line).join('')}</g>
|
|
160
|
+
<g class="pweb-labels" aria-hidden="true">${linkParts.map(link => link.label).join('')}</g>
|
|
161
|
+
${peopleSvg.join('')}
|
|
162
|
+
</svg><details class="pweb-list"><summary>${listSummary}</summary>${listHtml}</details>`;
|
|
163
|
+
}
|
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Responsive viewport framing for mobile and tablet worlds: landscape rotation fallback when a
|
|
3
|
+
* mobile browser cannot lock orientation, safe-area inset deduplication, visual-viewport virtual
|
|
4
|
+
* keyboard adjustment, pinch/double-tap zoom suppression, scroll preservation across turns, and
|
|
5
|
+
* fullscreen toggling. Worker-safe: all browser objects enter via parameters.
|
|
6
|
+
* @module
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
const TURN_SETTLE = [0, 150, 500];
|
|
10
|
+
const INSET_SLACK = 8;
|
|
11
|
+
const SIDE_CHECK_MS = 1000;
|
|
12
|
+
const LAYOUT_SLACK = 1;
|
|
13
|
+
const TYPING_ROOM = 240;
|
|
14
|
+
const TURN_HOLD_MS = 900;
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Creates a stage viewport controller that keeps the game frame sized to the visible window on
|
|
18
|
+
* desktop, tablet, and phone browsers.
|
|
19
|
+
*
|
|
20
|
+
* @param {object} options
|
|
21
|
+
* @param {{ rot: boolean, width: number, height: number }} options.view Shared mutable view metrics (`rot`, `width`, `height`).
|
|
22
|
+
* @param {boolean} [options.isPhone=false]
|
|
23
|
+
* @param {boolean} [options.isTouch=false]
|
|
24
|
+
* @param {() => void} [options.onResize] Called after every layout fit (for example to resize the renderer).
|
|
25
|
+
* @param {(turned: boolean) => void} [options.onTurnChange] Called when landscape rotation state changes.
|
|
26
|
+
* @param {(full: boolean) => void} [options.onFullScreenChange] Called when fullscreen state changes.
|
|
27
|
+
* @param {(onChange: () => void) => (() => void)} [options.watchDensity] Optional pixel-density watcher (e.g. `watchPixelDensity`).
|
|
28
|
+
* @param {object} [options.host=globalThis] Host exposing `window`, `document`, `screen`, `performance`, `getComputedStyle`, `setTimeout`, `clearTimeout`, `setInterval`, `clearInterval`.
|
|
29
|
+
* @returns {{ fit: () => void, refit: () => void, fullScreenElement: () => Element | null,
|
|
30
|
+
* requestFullScreen: () => Promise<boolean>, toggleFullScreen: (onUnavailable?: () => void) => void, dispose: () => void }}
|
|
31
|
+
*/
|
|
32
|
+
export function createStageFrame({
|
|
33
|
+
view,
|
|
34
|
+
isPhone = false,
|
|
35
|
+
isTouch = false,
|
|
36
|
+
onResize = () => {},
|
|
37
|
+
onTurnChange = () => {},
|
|
38
|
+
onFullScreenChange = () => {},
|
|
39
|
+
watchDensity,
|
|
40
|
+
host = globalThis,
|
|
41
|
+
}) {
|
|
42
|
+
const win = host.window ?? host;
|
|
43
|
+
const doc = host.document;
|
|
44
|
+
const body = doc?.body;
|
|
45
|
+
const root = doc?.documentElement;
|
|
46
|
+
const perf = host.performance ?? globalThis.performance;
|
|
47
|
+
const cleanups = [];
|
|
48
|
+
|
|
49
|
+
let insetProbe = null;
|
|
50
|
+
const scrolled = new Map();
|
|
51
|
+
let turnUntil = 0;
|
|
52
|
+
let editFrame = null;
|
|
53
|
+
let endEditing = 0;
|
|
54
|
+
|
|
55
|
+
if (body) body.classList.toggle('phone', isPhone);
|
|
56
|
+
|
|
57
|
+
const on = (target, type, fn, opts) => {
|
|
58
|
+
if (!target?.addEventListener) return;
|
|
59
|
+
target.addEventListener(type, fn, opts);
|
|
60
|
+
cleanups.push(() => target.removeEventListener(type, fn, opts));
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
function layoutStale() {
|
|
64
|
+
if (!root) return false;
|
|
65
|
+
return Math.abs(root.clientWidth - view.width) > LAYOUT_SLACK || Math.abs(root.clientHeight - view.height) > LAYOUT_SLACK;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function frameToWindow(editing) {
|
|
69
|
+
if (!body) return;
|
|
70
|
+
const framed = isTouch && !view.rot && (!isPhone || editing || layoutStale());
|
|
71
|
+
body.classList.toggle('framed', framed);
|
|
72
|
+
body.style.width = view.rot ? view.height + 'px' : framed ? view.width + 'px' : '';
|
|
73
|
+
body.style.height = view.rot ? view.width + 'px' : framed ? view.height + 'px' : '';
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function fitSafeArea() {
|
|
77
|
+
if (!isPhone || !doc || !body) return;
|
|
78
|
+
if (!insetProbe) {
|
|
79
|
+
insetProbe = doc.createElement('div');
|
|
80
|
+
insetProbe.style.cssText =
|
|
81
|
+
'position:fixed;visibility:hidden;pointer-events:none;padding:env(safe-area-inset-top,0px) env(safe-area-inset-right,0px) env(safe-area-inset-bottom,0px) env(safe-area-inset-left,0px)';
|
|
82
|
+
body.append(insetProbe);
|
|
83
|
+
}
|
|
84
|
+
const wide = view.width;
|
|
85
|
+
const high = view.height;
|
|
86
|
+
const reported = win.getComputedStyle ? win.getComputedStyle(insetProbe) : host.getComputedStyle(insetProbe);
|
|
87
|
+
const ends = wide > high ? [reported.paddingLeft, reported.paddingRight] : [reported.paddingTop, reported.paddingBottom];
|
|
88
|
+
const inset = Math.max(parseFloat(ends[0]) || 0, parseFloat(ends[1]) || 0);
|
|
89
|
+
const scr = win.screen ?? host.screen;
|
|
90
|
+
const short = Math.max(scr.width, scr.height) - Math.max(wide, high);
|
|
91
|
+
body.classList.toggle('side-clear', inset > 0 && short >= 2 * inset - INSET_SLACK);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const typingField = () => doc?.activeElement?.matches?.('input[type="search"], input[type="text"], textarea');
|
|
95
|
+
|
|
96
|
+
function fitKeyboard(hasEditFrame) {
|
|
97
|
+
if (!body) return;
|
|
98
|
+
const viewport = win.visualViewport;
|
|
99
|
+
const top = hasEditFrame && viewport ? Math.max(0, viewport.offsetTop) : 0;
|
|
100
|
+
const bottom = hasEditFrame && viewport ? Math.max(0, view.height - viewport.height - top) : 0;
|
|
101
|
+
body.style.setProperty('--kb-top', Math.round(top) + 'px');
|
|
102
|
+
body.style.setProperty('--kb', Math.round(bottom) + 'px');
|
|
103
|
+
body.classList.toggle('typing', top + bottom > 0 && viewport.height < TYPING_ROOM);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function noteScroll(e) {
|
|
107
|
+
if (perf.now() > turnUntil && e.target?.nodeType === 1) scrolled.set(e.target, e.target.scrollTop);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function keepScroll() {
|
|
111
|
+
turnUntil = perf.now() + TURN_HOLD_MS;
|
|
112
|
+
for (const [scroller, top] of scrolled) {
|
|
113
|
+
if (!scroller.isConnected) scrolled.delete(scroller);
|
|
114
|
+
else if (scroller.scrollTop !== top) scroller.scrollTop = top;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const fullScreenElement = () => doc?.fullscreenElement || doc?.webkitFullscreenElement || null;
|
|
119
|
+
|
|
120
|
+
function requestFullScreen() {
|
|
121
|
+
if (!doc || !root) return Promise.resolve(false);
|
|
122
|
+
const request = root.requestFullscreen || root.webkitRequestFullscreen;
|
|
123
|
+
if (!request || !(doc.fullscreenEnabled || doc.webkitFullscreenEnabled)) return Promise.resolve(false);
|
|
124
|
+
try {
|
|
125
|
+
return Promise.resolve(request.call(root)).then(
|
|
126
|
+
() => {
|
|
127
|
+
if (isPhone) (win.screen ?? host.screen)?.orientation?.lock?.('landscape')?.catch?.(() => {});
|
|
128
|
+
return true;
|
|
129
|
+
},
|
|
130
|
+
() => false,
|
|
131
|
+
);
|
|
132
|
+
} catch {
|
|
133
|
+
return Promise.resolve(false);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function toggleFullScreen(onUnavailable) {
|
|
138
|
+
if (fullScreenElement()) (doc.exitFullscreen || doc.webkitExitFullscreen).call(doc);
|
|
139
|
+
else {
|
|
140
|
+
requestFullScreen().then(given => {
|
|
141
|
+
if (!given) onUnavailable?.();
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
if (isTouch && doc) {
|
|
147
|
+
const prevent = e => e.preventDefault();
|
|
148
|
+
for (const type of ['gesturestart', 'gesturechange', 'gestureend']) on(doc, type, prevent, { passive: false });
|
|
149
|
+
on(
|
|
150
|
+
doc,
|
|
151
|
+
'touchmove',
|
|
152
|
+
e => {
|
|
153
|
+
if (e.touches.length > 1) e.preventDefault();
|
|
154
|
+
},
|
|
155
|
+
{ passive: false },
|
|
156
|
+
);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
const visual = win.visualViewport;
|
|
160
|
+
const tabletViewport = isTouch && !isPhone ? visual : null;
|
|
161
|
+
const frameWidth = () => Math.round(tabletViewport?.width || win.innerWidth);
|
|
162
|
+
const frameHeight = () => Math.round(tabletViewport?.height || win.innerHeight);
|
|
163
|
+
|
|
164
|
+
function fit() {
|
|
165
|
+
const wide = editFrame?.wide ?? frameWidth();
|
|
166
|
+
const high = editFrame?.high ?? frameHeight();
|
|
167
|
+
const turn = isPhone && (editFrame?.turn ?? high > wide);
|
|
168
|
+
const turned = turn !== view.rot;
|
|
169
|
+
if (!editFrame) win.scrollTo?.(0, 0);
|
|
170
|
+
view.width = wide;
|
|
171
|
+
view.height = high;
|
|
172
|
+
if (turned) {
|
|
173
|
+
view.rot = turn;
|
|
174
|
+
body?.classList.toggle('turned', turn);
|
|
175
|
+
onTurnChange(turn);
|
|
176
|
+
}
|
|
177
|
+
frameToWindow(!!editFrame);
|
|
178
|
+
fitSafeArea();
|
|
179
|
+
if (isPhone) fitKeyboard(!!editFrame);
|
|
180
|
+
onResize();
|
|
181
|
+
if (turned) {
|
|
182
|
+
keepScroll();
|
|
183
|
+
for (const wait of TURN_SETTLE) host.setTimeout(keepScroll, wait);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function refit() {
|
|
188
|
+
if (editFrame) {
|
|
189
|
+
fitKeyboard(true);
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
if (
|
|
193
|
+
frameWidth() !== view.width ||
|
|
194
|
+
frameHeight() !== view.height ||
|
|
195
|
+
(isPhone && !view.rot && layoutStale() !== !!body?.classList.contains('framed'))
|
|
196
|
+
) {
|
|
197
|
+
fit();
|
|
198
|
+
} else {
|
|
199
|
+
fitSafeArea();
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
fit();
|
|
204
|
+
if (isTouch) {
|
|
205
|
+
const interval = host.setInterval(refit, SIDE_CHECK_MS);
|
|
206
|
+
cleanups.push(() => host.clearInterval(interval));
|
|
207
|
+
}
|
|
208
|
+
if (isPhone) {
|
|
209
|
+
on(visual, 'scroll', refit);
|
|
210
|
+
on(doc, 'focusin', () => {
|
|
211
|
+
if (!typingField()) return;
|
|
212
|
+
host.clearTimeout(endEditing);
|
|
213
|
+
editFrame ??= { wide: view.width, high: view.height, turn: view.rot };
|
|
214
|
+
frameToWindow(true);
|
|
215
|
+
fitKeyboard(true);
|
|
216
|
+
});
|
|
217
|
+
on(doc, 'focusout', () => {
|
|
218
|
+
if (!editFrame) return;
|
|
219
|
+
endEditing = host.setTimeout(() => {
|
|
220
|
+
if (typingField()) return;
|
|
221
|
+
editFrame = null;
|
|
222
|
+
fit();
|
|
223
|
+
}, 350);
|
|
224
|
+
});
|
|
225
|
+
on(doc, 'scroll', noteScroll, true);
|
|
226
|
+
}
|
|
227
|
+
on(visual, 'resize', refit);
|
|
228
|
+
on(win, 'resize', refit);
|
|
229
|
+
if (watchDensity) {
|
|
230
|
+
const stop = watchDensity(onResize);
|
|
231
|
+
if (typeof stop === 'function') cleanups.push(stop);
|
|
232
|
+
}
|
|
233
|
+
on(win, 'orientationchange', () => {
|
|
234
|
+
turnUntil = perf.now() + TURN_HOLD_MS;
|
|
235
|
+
if (editFrame) {
|
|
236
|
+
host.clearTimeout(endEditing);
|
|
237
|
+
editFrame = null;
|
|
238
|
+
if (typingField()) doc.activeElement.blur();
|
|
239
|
+
}
|
|
240
|
+
for (const wait of TURN_SETTLE) host.setTimeout(fit, wait);
|
|
241
|
+
});
|
|
242
|
+
for (const ev of ['fullscreenchange', 'webkitfullscreenchange']) {
|
|
243
|
+
on(doc, ev, () => {
|
|
244
|
+
onFullScreenChange(!!fullScreenElement());
|
|
245
|
+
refit();
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
return {
|
|
250
|
+
fit,
|
|
251
|
+
refit,
|
|
252
|
+
fullScreenElement,
|
|
253
|
+
requestFullScreen,
|
|
254
|
+
toggleFullScreen,
|
|
255
|
+
dispose() {
|
|
256
|
+
host.clearTimeout(endEditing);
|
|
257
|
+
for (const off of cleanups) off();
|
|
258
|
+
cleanups.length = 0;
|
|
259
|
+
insetProbe?.remove?.();
|
|
260
|
+
insetProbe = null;
|
|
261
|
+
},
|
|
262
|
+
};
|
|
263
|
+
}
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Browser URL address bar and history router for explorable worlds: normalises paths under a site
|
|
3
|
+
* base folder, consumes `?r=<path>` fallback redirects, parses slugged route segments, defers deep
|
|
4
|
+
* link arrival behind a settle window, keeps `history` and `document.title` synchronized with the
|
|
5
|
+
* active view, and handles browser Back/Forward navigation. Worker-safe: host objects enter via parameters.
|
|
6
|
+
* @module
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Collapses consecutive slashes so a typed path beginning with `//` is never read as a host.
|
|
11
|
+
*
|
|
12
|
+
* @param {string} path
|
|
13
|
+
* @returns {string}
|
|
14
|
+
*/
|
|
15
|
+
export function normalizeSlash(path) {
|
|
16
|
+
return path.replace(/\/{2,}/g, '/');
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Default URL slugifier: lowercases ASCII text and replaces non-alphanumeric runs with hyphens.
|
|
21
|
+
*
|
|
22
|
+
* @param {string} text
|
|
23
|
+
* @returns {string}
|
|
24
|
+
*/
|
|
25
|
+
export function defaultSlug(text) {
|
|
26
|
+
return String(text)
|
|
27
|
+
.toLowerCase()
|
|
28
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
29
|
+
.replace(/^-|-$/g, '');
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Splits a route path such as `'location/harbour-gate'` or `'wiki/places/watchtower'` into its
|
|
34
|
+
* `kind`, decoded slugged `id`, optional `term`, raw segment, and a matcher `is(id, ...names)`
|
|
35
|
+
* that tolerates an omitted leading `'the-'`.
|
|
36
|
+
*
|
|
37
|
+
* @param {string} path
|
|
38
|
+
* @param {(text: string) => string} [slugFn=defaultSlug]
|
|
39
|
+
* @returns {{ kind: string | undefined, raw: string, id: string, term: string | undefined,
|
|
40
|
+
* is: (candidateId: string, ...names: Array<string | undefined>) => boolean }}
|
|
41
|
+
*/
|
|
42
|
+
export function parseRoutePath(path, slugFn = defaultSlug) {
|
|
43
|
+
const [kind, raw = '', term] = path.split('/').filter(Boolean);
|
|
44
|
+
const id = slugFn(decodeURIComponent(raw));
|
|
45
|
+
return {
|
|
46
|
+
kind,
|
|
47
|
+
raw,
|
|
48
|
+
id,
|
|
49
|
+
term,
|
|
50
|
+
is: (candidateId, ...names) => names.some(n => n && [id, 'the-' + id].includes(slugFn(n))) || candidateId === raw,
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Creates a URL address-bar and browser-history synchroniser for a single-page world.
|
|
56
|
+
*
|
|
57
|
+
* @param {object} options
|
|
58
|
+
* @param {string} options.basePath Site base pathname (for example `'/'` or `'/world/'`).
|
|
59
|
+
* @param {() => boolean} options.isActive Returns true when the world is running (e.g. play or scene mode).
|
|
60
|
+
* @param {() => boolean} [options.isTransitioning] Returns true while a fade/cut is active so the address bar waits.
|
|
61
|
+
* @param {() => string} options.getCurrentPath Computes the canonical relative path for what is currently on screen.
|
|
62
|
+
* @param {(path: string) => void} options.onNavigate Navigates the world to a relative path.
|
|
63
|
+
* @param {(path: string) => string} options.getTitle Formats `document.title` for a relative path.
|
|
64
|
+
* @param {(path: string) => void} [options.onPopState] Handles browser Back/Forward navigation.
|
|
65
|
+
* @param {(path: string) => boolean} [options.shouldCutToBlack] Return true for deep-link paths that should hide the opening view before arrival.
|
|
66
|
+
* @param {() => void} [options.onCutToBlack] Called before navigating to a path where `shouldCutToBlack` is true.
|
|
67
|
+
* @param {() => { push: boolean, state: any }} [options.consumeHistoryMode] Returns whether the next update should `pushState` instead of `replaceState`, and the state object to record.
|
|
68
|
+
* @param {number} [options.arrivalMs=400] Delay in milliseconds after world entry before following a deep link.
|
|
69
|
+
* @param {number} [options.settleMs=2600] Milliseconds after deep-link dispatch during which the address bar is held steady.
|
|
70
|
+
* @param {number} [options.pollMs=250] Milliseconds between address-bar sync polls.
|
|
71
|
+
* @param {object} [options.host=globalThis] Host exposing `location`, `history`, `document`, `window`, `performance`, `setInterval`, `clearInterval`, `setTimeout`.
|
|
72
|
+
* @returns {{ startPath: string | null, forgetAddress: () => void, shownPath: () => string,
|
|
73
|
+
* start: (crossing?: boolean) => () => void }}
|
|
74
|
+
*/
|
|
75
|
+
export function createUrlRouter({
|
|
76
|
+
basePath,
|
|
77
|
+
isActive,
|
|
78
|
+
isTransitioning = () => false,
|
|
79
|
+
getCurrentPath,
|
|
80
|
+
onNavigate,
|
|
81
|
+
getTitle,
|
|
82
|
+
onPopState,
|
|
83
|
+
shouldCutToBlack = () => false,
|
|
84
|
+
onCutToBlack = () => {},
|
|
85
|
+
consumeHistoryMode = () => ({ push: false, state: null }),
|
|
86
|
+
arrivalMs = 400,
|
|
87
|
+
settleMs = 2600,
|
|
88
|
+
pollMs = 250,
|
|
89
|
+
host = globalThis,
|
|
90
|
+
}) {
|
|
91
|
+
const loc = host.location;
|
|
92
|
+
const hist = host.history;
|
|
93
|
+
const doc = host.document;
|
|
94
|
+
const win = host.window ?? host;
|
|
95
|
+
const perf = host.performance ?? globalThis.performance;
|
|
96
|
+
|
|
97
|
+
const base = normalizeSlash(basePath);
|
|
98
|
+
const opened = normalizeSlash(loc?.pathname ?? '/');
|
|
99
|
+
const here = opened.startsWith(base) ? opened.slice(base.length).replace(/\/+$/, '') : '';
|
|
100
|
+
const queryPath = loc ? new URLSearchParams(loc.search).get('r') : null;
|
|
101
|
+
const state = {
|
|
102
|
+
base,
|
|
103
|
+
shown: null,
|
|
104
|
+
heldUntil: 0,
|
|
105
|
+
pending: queryPath ?? (here || null),
|
|
106
|
+
};
|
|
107
|
+
if (state.pending && hist?.replaceState) {
|
|
108
|
+
hist.replaceState(null, '', state.base + state.pending.replace(/^\/+/, ''));
|
|
109
|
+
}
|
|
110
|
+
const startPath = state.pending;
|
|
111
|
+
|
|
112
|
+
function forgetAddress() {
|
|
113
|
+
state.pending = null;
|
|
114
|
+
hist?.replaceState?.(null, '', state.base);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function shownPath() {
|
|
118
|
+
const pathname = loc?.pathname ?? '';
|
|
119
|
+
return pathname.startsWith(state.base) ? pathname.slice(state.base.length).replace(/\/+$/, '') : '';
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function start(crossing = false) {
|
|
123
|
+
if (crossing) state.pending = null;
|
|
124
|
+
const interval = host.setInterval(() => {
|
|
125
|
+
if (!isActive()) return;
|
|
126
|
+
if (state.pending !== null) {
|
|
127
|
+
const p = state.pending;
|
|
128
|
+
state.pending = null;
|
|
129
|
+
if (p) {
|
|
130
|
+
if (shouldCutToBlack(p)) onCutToBlack();
|
|
131
|
+
state.heldUntil = perf.now() + arrivalMs + settleMs;
|
|
132
|
+
host.setTimeout(() => onNavigate(p), arrivalMs);
|
|
133
|
+
}
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
if (perf.now() < state.heldUntil || isTransitioning()) return;
|
|
137
|
+
const p = getCurrentPath();
|
|
138
|
+
const mode = consumeHistoryMode();
|
|
139
|
+
if (p !== state.shown) {
|
|
140
|
+
state.shown = p;
|
|
141
|
+
if (mode.push) hist?.pushState?.(mode.state, '', state.base + p);
|
|
142
|
+
else hist?.replaceState?.(mode.state, '', state.base + p);
|
|
143
|
+
if (doc) doc.title = getTitle(p);
|
|
144
|
+
}
|
|
145
|
+
}, pollMs);
|
|
146
|
+
|
|
147
|
+
const handlePop = () => {
|
|
148
|
+
const p = shownPath();
|
|
149
|
+
state.shown = p;
|
|
150
|
+
if (doc) doc.title = getTitle(p);
|
|
151
|
+
onPopState?.(p);
|
|
152
|
+
};
|
|
153
|
+
win?.addEventListener?.('popstate', handlePop);
|
|
154
|
+
|
|
155
|
+
return () => {
|
|
156
|
+
host.clearInterval(interval);
|
|
157
|
+
win?.removeEventListener?.('popstate', handlePop);
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
return { startPath, forgetAddress, shownPath, start };
|
|
162
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Timed "way back" return offer after fast travel: remembers the visitor's prior spot, shows a
|
|
3
|
+
* temporary button when the journey moved farther than `nearDistance`, and invokes `onReturn(spot)`
|
|
4
|
+
* when clicked. Worker-safe: DOM button and timers enter via parameters.
|
|
5
|
+
* @module
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Creates a timed way-back offer controller.
|
|
10
|
+
*
|
|
11
|
+
* @param {object} options
|
|
12
|
+
* @param {() => HTMLElement | null} options.getButton Returns the way-back button element.
|
|
13
|
+
* @param {() => boolean} [options.canReturn] Returns true when returning is currently permitted (e.g. play mode).
|
|
14
|
+
* @param {(spot: object) => void} options.onReturn Executes the return journey to `spot`.
|
|
15
|
+
* @param {number} [options.nearDistance=60] Metres within which a journey on the same land offers no way back.
|
|
16
|
+
* @param {number} [options.offerSeconds=5] Seconds the offer button remains shown.
|
|
17
|
+
* @param {number} [options.fadeMs=600] Fade-out transition time in milliseconds before hiding the button.
|
|
18
|
+
* @param {object} [options.host=globalThis] Host exposing `setTimeout`, `clearTimeout`, `requestAnimationFrame`.
|
|
19
|
+
* @returns {{ offer: (from: { land: string, x: number, z: number } | null, land: string, x: number, z: number) => void,
|
|
20
|
+
* hide: () => void, trigger: () => void, bind: () => () => void }}
|
|
21
|
+
*/
|
|
22
|
+
export function createWayBack({
|
|
23
|
+
getButton,
|
|
24
|
+
canReturn = () => true,
|
|
25
|
+
onReturn,
|
|
26
|
+
nearDistance = 60,
|
|
27
|
+
offerSeconds = 5,
|
|
28
|
+
fadeMs = 600,
|
|
29
|
+
host = globalThis,
|
|
30
|
+
}) {
|
|
31
|
+
let offered = null;
|
|
32
|
+
let timer = 0;
|
|
33
|
+
|
|
34
|
+
function hide() {
|
|
35
|
+
host.clearTimeout(timer);
|
|
36
|
+
const button = getButton();
|
|
37
|
+
if (!button) return;
|
|
38
|
+
button.classList.remove('show');
|
|
39
|
+
timer = host.setTimeout(() => {
|
|
40
|
+
button.hidden = true;
|
|
41
|
+
}, fadeMs);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function offer(from, land, x, z) {
|
|
45
|
+
if (!from || (from.land === land && Math.hypot(from.x - x, from.z - z) < nearDistance)) return;
|
|
46
|
+
offered = from;
|
|
47
|
+
host.clearTimeout(timer);
|
|
48
|
+
const button = getButton();
|
|
49
|
+
if (!button) return;
|
|
50
|
+
button.hidden = false;
|
|
51
|
+
host.requestAnimationFrame(() => button.classList.add('show'));
|
|
52
|
+
timer = host.setTimeout(hide, offerSeconds * 1000);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function trigger() {
|
|
56
|
+
const at = offered;
|
|
57
|
+
offered = null;
|
|
58
|
+
hide();
|
|
59
|
+
if (!at || !canReturn()) return;
|
|
60
|
+
onReturn(at);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function bind() {
|
|
64
|
+
const button = getButton();
|
|
65
|
+
if (!button?.addEventListener) return () => {};
|
|
66
|
+
button.addEventListener('click', trigger);
|
|
67
|
+
return () => button.removeEventListener('click', trigger);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
return { offer, hide, trigger, bind };
|
|
71
|
+
}
|