roamwright 0.61.24 → 0.61.26

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,177 @@
1
+ /**
2
+ * Plain-text encyclopedia article parser, link extractor, plain-text formatter, and lazy-loaded
3
+ * article catalog for people and glossary terms. Worker-safe: world data and `[[link]]` resolvers
4
+ * enter via parameters.
5
+ * @module
6
+ */
7
+
8
+ import { defaultSlug } from './url-router.js';
9
+
10
+ /** Matches inline wiki links written as `[[Target]]` or `[[Target|Shown words]]`. */
11
+ export const ARTICLE_LINK = /\[\[([^\]|]+)(?:\|([^\]]+))?\]\]/g;
12
+
13
+ /**
14
+ * Splits plain-text article markup into sections of paragraphs.
15
+ *
16
+ * Lines starting with `## ` begin titled sections; paragraphs are separated by blank lines and
17
+ * internal whitespace is collapsed to single spaces. Any text preceding the first heading is
18
+ * returned as a section with `title: null`.
19
+ *
20
+ * @param {string} text Raw article markup.
21
+ * @returns {Array<{ title: string | null, paras: string[] }>}
22
+ */
23
+ export function parseArticle(text) {
24
+ const sections = [];
25
+ for (const chunk of text.trim().split(/^## /m)) {
26
+ if (!chunk.trim()) continue;
27
+ const titled = sections.length || text.trimStart().startsWith('## ');
28
+ const [first, ...rest] = chunk.split('\n');
29
+ const body = titled ? rest.join('\n') : chunk;
30
+ sections.push({
31
+ title: titled ? first.trim() : null,
32
+ paras: body
33
+ .split(/\n\s*\n/)
34
+ .map(p => p.replace(/\s+/g, ' ').trim())
35
+ .filter(Boolean),
36
+ });
37
+ }
38
+ return sections;
39
+ }
40
+
41
+ /**
42
+ * Strips `[[Target]]` / `[[Target|Shown]]` link syntax from a paragraph, keeping the displayed words.
43
+ *
44
+ * @param {string} para Paragraph text possibly containing wiki links.
45
+ * @returns {string}
46
+ */
47
+ export function plainArticleParagraph(para) {
48
+ return para.replace(ARTICLE_LINK, (_m, name, shown) => shown ?? name);
49
+ }
50
+
51
+ /**
52
+ * Flattens a parsed article entry (lede, section headings, and paragraphs) into plain text suitable
53
+ * for static-site indexing or search snippets.
54
+ *
55
+ * @param {{ lede?: string, sections: Array<{ title: string | null, paras: string[] }> }} entry
56
+ * @returns {string}
57
+ */
58
+ export function formatArticleText(entry) {
59
+ return [entry.lede, ...entry.sections.flatMap(s => [s.title ? s.title + '.' : '', ...s.paras.map(plainArticleParagraph)])]
60
+ .filter(Boolean)
61
+ .join(' ');
62
+ }
63
+
64
+ /**
65
+ * Collects every resolved target linked from an entry's article sections, deduplicated by `path`
66
+ * in order of first mention (excluding self-links back to `entry.path`).
67
+ *
68
+ * @param {{ path: string, sections: Array<{ title: string | null, paras: string[] }> }} entry
69
+ * @param {(name: string) => ({ path: string } | null | undefined)} resolveLink
70
+ * @returns {Array<{ path: string }>}
71
+ */
72
+ export function collectArticleLinks(entry, resolveLink) {
73
+ const seen = new Set([entry.path]);
74
+ const out = [];
75
+ for (const section of entry.sections) {
76
+ for (const para of section.paras) {
77
+ for (const [, name] of para.matchAll(ARTICLE_LINK)) {
78
+ const target = resolveLink(name);
79
+ if (target && !seen.has(target.path)) {
80
+ seen.add(target.path);
81
+ out.push(target);
82
+ }
83
+ }
84
+ }
85
+ }
86
+ return out;
87
+ }
88
+
89
+ /**
90
+ * Creates a lazy-loaded catalog of person and glossary-term articles backed by a caller-supplied
91
+ * link resolver and world data accessors.
92
+ *
93
+ * @param {object} options
94
+ * @param {() => Promise<{ personArticles: Record<string, string>, termArticles: Record<string, Record<string, string>> }>} options.load
95
+ * Async loader returning `{ personArticles, termArticles }`. Invoked at most once.
96
+ * @param {(name: string) => ({ kind: string, path: string, name: string, id?: string } | null | undefined)} options.resolveLink
97
+ * Resolves a link name or slug into a target descriptor.
98
+ * @param {() => Record<string, { name?: string, desc?: string }>} options.getCharacters
99
+ * Returns the world's character table keyed by character id.
100
+ * @param {() => Array<{ id: string, title: string, intro?: string, terms: Array<[string, string, object?]> }>} options.getSections
101
+ * Returns the glossary sections and their term tuples `[name, lede, meta]`.
102
+ * @param {(text: string) => string} [options.slug=defaultSlug] Slugifier matching route paths.
103
+ * @returns {{ load: () => Promise<void>, hasLoaded: () => boolean,
104
+ * findEntry: (path: string) => object | null,
105
+ * entryText: (entry: object) => string,
106
+ * entryLinks: (entry: object) => Array<{ path: string }> }}
107
+ */
108
+ export function createArticleCatalog({ load, resolveLink, getCharacters, getSections, slug = defaultSlug }) {
109
+ let texts = null;
110
+ let fetching = null;
111
+
112
+ function loadArticles() {
113
+ fetching ??= Promise.resolve()
114
+ .then(load)
115
+ .then(module => {
116
+ texts = module;
117
+ });
118
+ return fetching;
119
+ }
120
+
121
+ function hasLoaded() {
122
+ return !!texts;
123
+ }
124
+
125
+ function personArticle(name) {
126
+ for (const [id, character] of Object.entries(getCharacters())) {
127
+ if (character.name === name && texts.personArticles[id]) return { id, text: texts.personArticles[id] };
128
+ }
129
+ return null;
130
+ }
131
+
132
+ function findEntry(path) {
133
+ if (!texts) throw new Error('findEntry: the articles are not loaded (loadArticles)');
134
+ const [kind, a, b] = path.split('/');
135
+ if (kind === 'person') {
136
+ const target = resolveLink(a ?? '');
137
+ if (target?.kind !== 'person') return null;
138
+ const character = getCharacters()[target.id];
139
+ const art = personArticle(character.name);
140
+ return {
141
+ kind,
142
+ path: target.path,
143
+ name: character.name,
144
+ id: art?.id ?? target.id,
145
+ lede: character.desc,
146
+ sections: art ? parseArticle(art.text) : [],
147
+ };
148
+ }
149
+ if (kind !== 'wiki' || !b) return null;
150
+ const section = getSections().find(s => s.id === a);
151
+ const term = section?.terms.find(t => slug(t[0]) === b);
152
+ if (!term) return null;
153
+ const [name, lede, meta = {}] = term;
154
+ const own = texts.termArticles[section.id]?.[b];
155
+ const shared = own ? null : personArticle(name);
156
+ return {
157
+ kind: 'term',
158
+ path,
159
+ name,
160
+ section,
161
+ lede,
162
+ also: meta.also,
163
+ book: meta.book,
164
+ who: meta.who ?? [],
165
+ id: shared?.id,
166
+ sections: parseArticle(own ?? shared?.text ?? ''),
167
+ };
168
+ }
169
+
170
+ return {
171
+ load: loadArticles,
172
+ hasLoaded,
173
+ findEntry,
174
+ entryText: formatArticleText,
175
+ entryLinks: entry => collectArticleLinks(entry, resolveLink),
176
+ };
177
+ }
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Periodic HUD bounding-box tracker so world-space labels, nameplates, and waypoints avoid
3
+ * overlapping interface chrome without forcing browser layout every frame.
4
+ * Worker-safe: DOM lookups and rectangle readers enter via parameters.
5
+ * @module
6
+ */
7
+
8
+ /**
9
+ * Creates a throttled HUD exclusion-box tracker.
10
+ *
11
+ * Elements are read in three ordered groups:
12
+ * 1. `rightColumn` — boxes forming the right-hand HUD column; their union is tracked on `room.right`
13
+ * (`{ left, bottom }`) and counted in `room.shared`.
14
+ * 2. `conditional` — overlay boxes included only when they hold non-empty `textContent` (such as
15
+ * captions or scene buttons), also counted in `room.shared`.
16
+ * 3. `extra` — remaining HUD controls checked only by `overlapsAll` (or when passing `room.count`).
17
+ *
18
+ * @param {object} [options]
19
+ * @param {(id: string) => { textContent?: string | null, getBoundingClientRect?: () => { left: number, top: number, width: number, height: number } } | null} [options.getElement]
20
+ * Looks up an element by id (defaults to `document.getElementById` when available).
21
+ * @param {(el: any) => { left: number, top: number, width: number, height: number }} [options.getRect]
22
+ * Measures an element's box in stage/page pixels (defaults to `el.getBoundingClientRect()`).
23
+ * @param {string[]} [options.rightColumn=[]] Element ids stacked along the right edge.
24
+ * @param {string[]} [options.conditional=[]] Element ids kept only while `el.textContent` is non-empty.
25
+ * @param {string[]} [options.extra=[]] Additional HUD element ids checked by `overlapsAll`.
26
+ * @param {number} [options.readEvery=0.5] Minimum interval in seconds between layout reads.
27
+ * @returns {{ room: { right: { left: number, bottom: number }, boxes: Float32Array, count: number, shared: number, wait: number },
28
+ * read: () => void, update: (dt: number) => void,
29
+ * overlaps: (x0: number, y0: number, x1: number, y1: number, count?: number) => boolean,
30
+ * overlapsAll: (x0: number, y0: number, x1: number, y1: number) => boolean }}
31
+ */
32
+ export function createHudRoom({
33
+ getElement = id => (typeof document !== 'undefined' ? document.getElementById(id) : null),
34
+ getRect = el => el.getBoundingClientRect(),
35
+ rightColumn = [],
36
+ conditional = [],
37
+ extra = [],
38
+ readEvery = 0.5,
39
+ } = {}) {
40
+ const maxBoxes = rightColumn.length + conditional.length + extra.length;
41
+ const room = {
42
+ right: { left: 1e9, bottom: 0 },
43
+ boxes: new Float32Array(maxBoxes * 4),
44
+ count: 0,
45
+ shared: 0,
46
+ wait: 0,
47
+ };
48
+
49
+ function keep(rect) {
50
+ if (!rect || !rect.width || room.count >= maxBoxes) return;
51
+ const offset = room.count++ * 4;
52
+ room.boxes[offset] = rect.left;
53
+ room.boxes[offset + 1] = rect.top;
54
+ room.boxes[offset + 2] = rect.left + rect.width;
55
+ room.boxes[offset + 3] = rect.top + rect.height;
56
+ }
57
+
58
+ function read() {
59
+ const right = room.right;
60
+ right.left = 1e9;
61
+ right.bottom = 0;
62
+ room.count = 0;
63
+ for (let i = 0; i < rightColumn.length; i++) {
64
+ const el = getElement(rightColumn[i]);
65
+ if (!el) continue;
66
+ const rect = getRect(el);
67
+ if (!rect || !rect.width) continue;
68
+ right.left = Math.min(right.left, rect.left);
69
+ right.bottom = Math.max(right.bottom, rect.top + rect.height);
70
+ keep(rect);
71
+ }
72
+ for (let i = 0; i < conditional.length; i++) {
73
+ const el = getElement(conditional[i]);
74
+ if (el && el.textContent) keep(getRect(el));
75
+ }
76
+ room.shared = room.count;
77
+ for (let i = 0; i < extra.length; i++) {
78
+ const el = getElement(extra[i]);
79
+ if (el) keep(getRect(el));
80
+ }
81
+ }
82
+
83
+ function update(dt) {
84
+ if ((room.wait -= dt) > 0) return;
85
+ room.wait = readEvery;
86
+ read();
87
+ }
88
+
89
+ function overlaps(x0, y0, x1, y1, count = room.shared) {
90
+ const boxes = room.boxes;
91
+ for (let i = 0; i < count; i++) {
92
+ const offset = i * 4;
93
+ if (x1 > boxes[offset] && x0 < boxes[offset + 2] && y1 > boxes[offset + 1] && y0 < boxes[offset + 3]) return true;
94
+ }
95
+ return false;
96
+ }
97
+
98
+ function overlapsAll(x0, y0, x1, y1) {
99
+ return overlaps(x0, y0, x1, y1, room.count);
100
+ }
101
+
102
+ return { room, read, update, overlaps, overlapsAll };
103
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Cross-land journey persistence and arrival-handler registry.
3
+ *
4
+ * When travelling between separately loaded lands causes a fresh page load, the journey's
5
+ * destination, travel mode (flying, altitude), return point, and arrival aim (`{ kind, id }`)
6
+ * are recorded in session storage and consumed on the far side once the matching landing spot loads.
7
+ * Worker-safe: storage access enters via an optional getter.
8
+ * @module
9
+ */
10
+
11
+ /**
12
+ * Creates a journey store backed by session storage (or an injected Storage-compatible object).
13
+ *
14
+ * @param {object} [options]
15
+ * @param {string} [options.storageKey='roamwright:journey'] Session-storage key for the pending journey record.
16
+ * @param {() => ({ getItem: (k: string) => string | null, setItem: (k: string, v: string) => void, removeItem: (k: string) => void } | null | undefined)} [options.getStorage]
17
+ * Returns the storage backend (defaults to `globalThis.sessionStorage`).
18
+ * @returns {{ onArrival: (kind: string, act: (id: any) => void) => void,
19
+ * arrive: (aim: { kind: string, id?: any }) => void,
20
+ * note: (journey: { land: string, x: number, z: number, up?: number, fly?: boolean, aim?: { kind: string, id?: any } | null, from?: any }) => void,
21
+ * take: (land: string, x: number, z: number) => object | null }}
22
+ */
23
+ export function createJourneyStore({
24
+ storageKey = 'roamwright:journey',
25
+ getStorage = () => (typeof sessionStorage !== 'undefined' ? sessionStorage : null),
26
+ } = {}) {
27
+ const arrivals = {};
28
+
29
+ function onArrival(kind, act) {
30
+ arrivals[kind] = act;
31
+ }
32
+
33
+ function arrive(aim) {
34
+ arrivals[aim.kind]?.(aim.id);
35
+ }
36
+
37
+ function note(journey) {
38
+ try {
39
+ const storage = getStorage();
40
+ if (storage) storage.setItem(storageKey, JSON.stringify(journey));
41
+ } catch {
42
+ // Storage unavailable (for example a restricted private window): travel proceeds without the arrival note.
43
+ }
44
+ }
45
+
46
+ function take(land, x, z) {
47
+ let journey = null;
48
+ try {
49
+ const storage = getStorage();
50
+ if (!storage) return null;
51
+ journey = JSON.parse(storage.getItem(storageKey));
52
+ storage.removeItem(storageKey);
53
+ } catch {
54
+ return null;
55
+ }
56
+ return journey && journey.land === land && journey.x === x && journey.z === z ? journey : null;
57
+ }
58
+
59
+ return { onArrival, arrive, note, take };
60
+ }
@@ -1,3 +1,4 @@
1
+ import { mulberry32 } from '../math/random.js';
1
2
  import { nextFrame } from './frame-yield.js';
2
3
 
3
4
  /**
@@ -103,3 +104,71 @@ export function createLazySets({ build, unfetched: tellUnfetched = () => {} }) {
103
104
 
104
105
  return { declare, fetch, raise, raiseWithin, raiseNearest, stands, declared };
105
106
  }
107
+
108
+ /**
109
+ * Creates a local-frame set builder helper anchored at `origin` in `space`: binds a seeded PRNG,
110
+ * kit and optional rock geometry builders, a local ground sampler `Y(x, z)`, collider recording via
111
+ * `block`, kit placement via `build`, and a `finish(group, enter)` finaliser that meshes static
112
+ * geometry and registers colliders. Worker-safe.
113
+ *
114
+ * @param {object} options
115
+ * @param {{ ground: (x: number, z: number) => number, group?: object }} options.space - Host space providing `ground(x, z)` and default `group`.
116
+ * @param {{ x: number, z: number }} options.origin - Local frame world origin in metres.
117
+ * @param {number} [options.seed=0] - Per-set seed offset added to `baseSeed`.
118
+ * @param {number} [options.baseSeed=0] - World seed offset added before seeding `mulberry32`.
119
+ * @param {() => number} [options.random] - Optional pre-seeded PRNG (defaults to `mulberry32(baseSeed + seed)`).
120
+ * @param {() => object} [options.createKit] - Factory for the set's kit builders.
121
+ * @param {(() => { ox?: number, oz?: number, p?: ArrayLike<number> }) | null} [options.createRock=null] - Optional factory for the set's rock geometry builder; receives `ox` and `oz` origin offsets.
122
+ * @param {(kit: object, x: number, y: number, z: number, yaw: number, plain: boolean, parts: Function, rng: () => number) => void} [options.placeKit] - Places `parts` into `kit` at `(x, y, z)`.
123
+ * @param {(kit: object, group: object) => void} [options.meshKit] - Meshes `kit` into `group` on `finish`.
124
+ * @param {(rock: object, group: object) => void} [options.meshRock] - Meshes `rock` into `group` on `finish` when `rock.p.length > 0`.
125
+ * @param {(space: object, solids: object[]) => void} [options.addSolids] - Registers collected colliders on `finish` when `enter` is true.
126
+ * @returns {{
127
+ * O: { x: number, z: number },
128
+ * B: object,
129
+ * rock: object | null,
130
+ * rng: () => number,
131
+ * Y: (x: number, z: number) => number,
132
+ * block: (s: object) => number,
133
+ * build: (parts: Function) => void,
134
+ * solid: object[],
135
+ * finish: (group?: object, enter?: boolean) => void,
136
+ * }}
137
+ */
138
+ export function createSetFrame({
139
+ space,
140
+ origin,
141
+ seed = 0,
142
+ baseSeed = 0,
143
+ random,
144
+ createKit = () => ({}),
145
+ createRock = null,
146
+ placeKit = (kit, _x, _y, _z, _yaw, _plain, parts, rng) => parts(kit, rng),
147
+ meshKit = () => {},
148
+ meshRock = () => {},
149
+ addSolids = () => {},
150
+ }) {
151
+ const B = createKit();
152
+ const rock = createRock ? createRock() : null;
153
+ const rng = random ?? mulberry32(baseSeed + seed);
154
+ const solid = [];
155
+ if (rock) {
156
+ rock.ox = origin.x;
157
+ rock.oz = origin.z;
158
+ }
159
+ return {
160
+ O: origin,
161
+ B,
162
+ rock,
163
+ rng,
164
+ Y: (x, z) => space.ground(origin.x + x, origin.z + z),
165
+ block: s => solid.push({ ...s, x: origin.x + s.x, z: origin.z + s.z }),
166
+ build: parts => placeKit(B, origin.x, 0, origin.z, 0, false, parts, rng),
167
+ solid,
168
+ finish(group = space.group, enter = true) {
169
+ meshKit(B, group);
170
+ if (rock?.p?.length) meshRock(rock, group);
171
+ if (enter) addSolids(space, solid);
172
+ },
173
+ };
174
+ }