foldkit-site 0.0.0-stage → 0.2.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.
package/dist/index.mjs ADDED
@@ -0,0 +1,664 @@
1
+ import { Effect, Option, Predicate, Schema } from "effect";
2
+ import "foldkit-bundle";
3
+ import * as Command from "foldkit/command";
4
+ import * as Navigation from "foldkit/navigation";
5
+ import { UrlRequest } from "foldkit/navigation";
6
+ import { oneOf, parseUrlWithFallback } from "foldkit/route";
7
+ import * as Update from "foldkit/update";
8
+ import * as Url$1 from "foldkit/url";
9
+ import { Surface } from "foldkit-surface";
10
+ //#region src/index.ts
11
+ /**
12
+ * `foldkit-site` — the deployed route topology of a Foldkit application.
13
+ *
14
+ * A Site says where the application is: stable route nodes in a hierarchy,
15
+ * each with its Foldkit Router, its metadata, and the Surfaces it activates.
16
+ * Everything else — fetching, caching, rendering, navigation effects — stays
17
+ * where it already is: the node compiles down to the primitives the runtime
18
+ * already runs (`Route` biparsers, `Surface.when`, Bundle placements), so the
19
+ * Site never becomes a second router, loader, or store.
20
+ *
21
+ * The rule, from the design:
22
+ *
23
+ * > Router says where the application is. Surface says what that state makes
24
+ * > observable and capable. Remote says what server facts those observations
25
+ * > require.
26
+ *
27
+ * Nothing here runs: nodes, mounts, trees, and targets are data. A `SiteTree`
28
+ * is frozen at `Site.make`. `Site.routing` is the one runtime piece: the
29
+ * link-click and URL-change lifecycle as a wiring, so applications stop
30
+ * hand-writing those two update branches.
31
+ */
32
+ /**
33
+ * The tag a tagged constructor names, read the way `Surface.when` reads it
34
+ * off a route case. Anything else is a definition-time error, not a silent
35
+ * mismatch.
36
+ */
37
+ const tagOfConstructor = (constructor, what) => {
38
+ const literal = constructor.fields?._tag?.ast?.literal;
39
+ if (typeof literal !== "string") throw new Error(`${what} must be a tagged constructor`);
40
+ return literal;
41
+ };
42
+ const indexes = /* @__PURE__ */ new WeakMap();
43
+ /** The parent and tag maps and the parser of a tree, computed once per tree value. */
44
+ const indexOf = (site) => {
45
+ const known = indexes.get(site);
46
+ if (known !== void 0) return known;
47
+ const parent = /* @__PURE__ */ new Map();
48
+ const byTag = /* @__PURE__ */ new Map();
49
+ const visit = (mount, above) => {
50
+ if (parent.has(mount.node)) throw new Error(`Site.make: "${mount.node.tag}" is mounted twice; a node has one place in a tree`);
51
+ const knownTag = byTag.get(mount.node.tag);
52
+ if (knownTag !== void 0 && knownTag !== mount.node) throw new Error(`Site.make: two nodes share the tag "${mount.node.tag}"; one route case is one node`);
53
+ parent.set(mount.node, above);
54
+ byTag.set(mount.node.tag, mount.node);
55
+ for (const child of mount.children) visit(child, mount.node);
56
+ };
57
+ for (const root of site.roots) visit(root, void 0);
58
+ const parser = parseUrlWithFallback(oneOf(...[...parent.keys()].map((node) => node.router)), { make: () => Option.none() });
59
+ const read = (url) => {
60
+ const parsed = parser(url);
61
+ return Option.isOption(parsed) ? parsed : Option.some(parsed);
62
+ };
63
+ const index = {
64
+ parent,
65
+ byTag,
66
+ read
67
+ };
68
+ indexes.set(site, index);
69
+ return index;
70
+ };
71
+ /** Whether a node's route has params beyond its tag, so its addresses must be listed. */
72
+ const takesParams = (node) => Object.keys(node.case.fields ?? {}).some((field) => field !== "_tag");
73
+ const asMount = (node) => "children" in node ? node : {
74
+ node,
75
+ children: []
76
+ };
77
+ /** One surfaced node's `Surface.when` over the route place, or nothing surfaceless. */
78
+ const sourceOf = (node, owner, place) => {
79
+ const bound = node.bound;
80
+ if (bound === void 0) return void 0;
81
+ if (bound.surface.owner !== owner) throw new Error(`Site: "${bound.surface.name}" belongs to another application than the site`);
82
+ return [node.tag, Surface.when(bound.surface, place, node.case, bound.params)];
83
+ };
84
+ /** The fields a `Meta` gives, so one left `undefined` does not erase an ancestor's. */
85
+ const saidOf = (meta) => Object.fromEntries(Object.entries(meta).filter(([, value]) => value !== void 0));
86
+ const freezeMount = (mount) => Object.freeze({
87
+ node: mount.node,
88
+ children: Object.freeze(mount.children.map(freezeMount))
89
+ });
90
+ /** A bare node: its tag from its route case, nothing annotated. */
91
+ const baseNode = (router, routeCase) => Object.freeze({
92
+ tag: tagOfConstructor(routeCase, "Site.route: expected a route case from defineRouteUnion"),
93
+ router,
94
+ case: routeCase
95
+ });
96
+ const Site = {
97
+ /**
98
+ * One deployed location from its Foldkit Router and its route case:
99
+ *
100
+ * ```ts
101
+ * const Person = Site.route(personRouter, AppRoute.Person, {
102
+ * title: ({ personId }) => `Person ${personId} | Routing`,
103
+ * section: 'People',
104
+ * })
105
+ * ```
106
+ *
107
+ * The router stays the whole URL story (parse and build); the case names
108
+ * the tag and builds route values. Metadata is annotated once here, and
109
+ * navigation, titles, and history derive from it. To share annotations
110
+ * across nodes, or to build incrementally, use the `Site.node` builder
111
+ * instead — these options are sugar over it.
112
+ */
113
+ route: (router, routeCase, options) => {
114
+ let built = Site.node(router, routeCase);
115
+ if (options?.title !== void 0) built = built.title(options.title);
116
+ if (options?.section !== void 0) built = built.section(options.section);
117
+ if (options?.landing !== void 0) built = built.landing(options.landing);
118
+ if (options?.shortcut !== void 0) built = built.shortcut(options.shortcut);
119
+ if (options?.history !== void 0) built = built.history(options.history);
120
+ if (options?.layout !== void 0) built = built.layout(options.layout);
121
+ if (options?.view !== void 0) built = built.view(options.view);
122
+ if (options?.meta !== void 0) built = built.meta(options.meta);
123
+ if (options?.indexed !== void 0) built = built.indexed(options.indexed);
124
+ if (options?.surface !== void 0) built = built.surface(options.surface);
125
+ return built.node;
126
+ },
127
+ /**
128
+ * One deployed location as an incremental builder, for nodes annotated in
129
+ * steps or annotations shared across nodes:
130
+ *
131
+ * ```ts
132
+ * const Person = Site.node(personRouter, AppRoute.Person)
133
+ * .title(({ personId }) => `Person ${personId} | Routing`)
134
+ * .section('People')
135
+ * .node
136
+ * ```
137
+ *
138
+ * Methods — not pipeable fragments — because a pipeable fragment cannot
139
+ * infer the route: each stage is a separate generic call, so its type
140
+ * parameter falls back to the constraint and a typed callback no longer
141
+ * matches. A method already knows its node's route, so inline lambdas
142
+ * infer with no annotation. Read `.node` at any stage: every step freezes,
143
+ * so intermediates are usable nodes too (targets, hrefs), never drafts.
144
+ * `Site.route`'s options are sugar over this builder — one implementation.
145
+ */
146
+ node: (router, routeCase) => {
147
+ const at = (built) => ({
148
+ node: built,
149
+ pipe: (fn) => fn(at(built)),
150
+ title: (title) => at(Object.freeze({
151
+ ...built,
152
+ title
153
+ })),
154
+ section: (section) => at(Object.freeze({
155
+ ...built,
156
+ section
157
+ })),
158
+ landing: (landing) => at(Object.freeze({
159
+ ...built,
160
+ landing
161
+ })),
162
+ shortcut: (shortcut) => at(Object.freeze({
163
+ ...built,
164
+ shortcut
165
+ })),
166
+ history: (history) => at(Object.freeze({
167
+ ...built,
168
+ history
169
+ })),
170
+ layout: (layout) => at(Object.freeze({
171
+ ...built,
172
+ layout
173
+ })),
174
+ view: (view) => at(Object.freeze({
175
+ ...built,
176
+ view
177
+ })),
178
+ meta: (meta) => at(Object.freeze({
179
+ ...built,
180
+ meta
181
+ })),
182
+ indexed: (indexed) => at(Object.freeze({
183
+ ...built,
184
+ indexed
185
+ })),
186
+ surface: (config) => at(Object.freeze({
187
+ ...built,
188
+ bound: config
189
+ }))
190
+ });
191
+ return at(baseNode(router, routeCase));
192
+ },
193
+ /**
194
+ * A node with its children. Returns a mount; the node itself is untouched,
195
+ * so it stays usable bare for targets and hrefs. Children may be bare
196
+ * nodes (childless) or mounts.
197
+ */
198
+ mount: (node, children) => Object.freeze({
199
+ node,
200
+ children: Object.freeze((children ?? []).map(asMount))
201
+ }),
202
+ /**
203
+ * The deployed topology from its roots: bare nodes or mounts, frozen.
204
+ * Refuses two nodes sharing a tag and one node mounted twice, since both
205
+ * would make chain inspection ambiguous.
206
+ */
207
+ make: (...roots) => {
208
+ const tree = Object.freeze({ roots: Object.freeze(roots.map(asMount).map(freezeMount)) });
209
+ indexOf(tree);
210
+ return tree;
211
+ },
212
+ /**
213
+ * One typed destination: the route value and the URL from the node's own
214
+ * declaration, so a link can never point where the parser would not go.
215
+ */
216
+ target: (node, params) => ({
217
+ node,
218
+ route: node.case(params),
219
+ url: node.router.build(params)
220
+ }),
221
+ /** The URL of a target, or of a node with params directly. */
222
+ href: ((targetOrNode, params) => {
223
+ if ("url" in targetOrNode) return targetOrNode.url;
224
+ if (params === void 0) throw new Error(`Site.href: "${targetOrNode.tag}" needs params to build its URL`);
225
+ return Site.target(targetOrNode, params).url;
226
+ }),
227
+ /**
228
+ * The tree's parser: an address to the route of the first node, in tree
229
+ * order (depth-first, parents first), whose router takes all of it, or the
230
+ * fallback. A router that takes any segment (`/:slug`) belongs after the
231
+ * nodes whose literal it would take too. With `Site.hrefOf`, the tree is
232
+ * the one declaration of both directions.
233
+ */
234
+ parse: (site, fallback) => {
235
+ const { read } = indexOf(site);
236
+ return (url) => Option.getOrElse(read(url), () => fallback.make({ path: url.pathname }));
237
+ },
238
+ /**
239
+ * The route the tree reads at an address, as `Site.parse` does, or nothing
240
+ * when no node takes it: an address the tree does not hold is another
241
+ * document's, which a link reaches with a full load.
242
+ */
243
+ routeAt: (site, url) => indexOf(site).read(url),
244
+ /**
245
+ * The address of a route the tree holds, built by its node's router, so it
246
+ * parses back to the same route (`Site.parse`).
247
+ */
248
+ hrefOf: (site, route) => {
249
+ const node = indexOf(site).byTag.get(route._tag);
250
+ if (node === void 0) throw new Error(`Site.hrefOf: no node holds the tag "${route._tag}"`);
251
+ const { _tag, ...params } = route;
252
+ return node.router.build(params);
253
+ },
254
+ /**
255
+ * A node's addresses, from data: every published post is one. `list` is an
256
+ * Effect the build runs, such as a Remote query read through
257
+ * `Data.satisfy`, so it lists what a visitor may see.
258
+ *
259
+ * ```ts
260
+ * const posts = Site.paths(PostNode, listPosts.pipe(
261
+ * Effect.map(rows => rows.map(row => ({ params: { slug: row.slug }, modified: row.at }))),
262
+ * ))
263
+ * ```
264
+ */
265
+ paths: (node, list) => ({
266
+ node,
267
+ list
268
+ }),
269
+ /**
270
+ * Every address of the site, in tree order: one for each node whose route
271
+ * has no params, and what `paths` lists for each node whose route has
272
+ * them. What a build renders, a sitemap lists (with `Site.indexedOf`), and
273
+ * a prefetch warms. A node with params and no `paths` is refused, as are
274
+ * `paths` for a node the tree does not hold or twice for one node, so no
275
+ * page is left out unsaid; `Site.paths(node, Effect.succeed([]))` lists none.
276
+ */
277
+ targets: (site, paths) => {
278
+ const nodes = Site.nodesOf(site);
279
+ const listed = /* @__PURE__ */ new Map();
280
+ for (const each of paths) {
281
+ if (!nodes.includes(each.node)) throw new Error(`Site.targets: "${each.node.tag}" has paths but is not in the tree`);
282
+ if (listed.has(each.node)) throw new Error(`Site.targets: "${each.node.tag}" has paths twice`);
283
+ listed.set(each.node, each);
284
+ }
285
+ const unlisted = nodes.filter((node) => takesParams(node) && !listed.has(node));
286
+ if (unlisted.length > 0) throw new Error(`Site.targets: ${unlisted.map((node) => `"${node.tag}"`).join(", ")} take params and have no paths`);
287
+ return Effect.map(Effect.forEach(nodes, (node) => {
288
+ const source = listed.get(node);
289
+ if (source === void 0) return Effect.succeed([Site.target(node, {})]);
290
+ return Effect.map(source.list, (found) => found.map(({ params, modified }) => ({
291
+ ...Site.target(node, params),
292
+ ...modified === void 0 ? {} : { modified }
293
+ })));
294
+ }, { concurrency: "unbounded" }), (perNode) => perNode.flat());
295
+ },
296
+ /** Every node in the tree, depth-first, parents before children. */
297
+ nodesOf: (site) => {
298
+ const out = [];
299
+ const visit = (mount) => {
300
+ out.push(mount.node);
301
+ for (const child of mount.children) visit(child);
302
+ };
303
+ for (const root of site.roots) visit(root);
304
+ return out;
305
+ },
306
+ /** The node a route value is on, or nothing for a tag the tree does not hold. */
307
+ nodeOf: (site, route) => indexOf(site).byTag.get(route._tag),
308
+ /** The chain a route value is on, root first; none for an unknown tag. */
309
+ chainOf: (site, route) => {
310
+ const { parent, byTag } = indexOf(site);
311
+ const node = byTag.get(route._tag);
312
+ if (node === void 0) return [];
313
+ const chain = [node];
314
+ let above = parent.get(node);
315
+ while (above !== void 0) {
316
+ chain.unshift(above);
317
+ above = parent.get(above);
318
+ }
319
+ return chain;
320
+ },
321
+ /** The node above this one in the tree, or nothing at a root. */
322
+ parentOf: (site, node) => indexOf(site).parent.get(node),
323
+ /** Every node above this one, root first. */
324
+ ancestorsOf: (site, node) => {
325
+ const { parent } = indexOf(site);
326
+ const out = [];
327
+ let above = parent.get(node);
328
+ while (above !== void 0) {
329
+ out.unshift(above);
330
+ above = parent.get(above);
331
+ }
332
+ return out;
333
+ },
334
+ /** How deep the node sits: a root is 0, its children 1. */
335
+ depthOf: (site, node) => Site.ancestorsOf(site, node).length,
336
+ /** The title the tree annotates for a route value, or nothing. */
337
+ titleOf: (site, route) => {
338
+ return indexOf(site).byTag.get(route._tag)?.title?.(route);
339
+ },
340
+ /**
341
+ * Whether search engines index a route: the nearest declaration up its
342
+ * chain, so a `noindex` studio covers every node below it. A route the tree
343
+ * does not hold is indexed, as a page with no declaration is.
344
+ */
345
+ indexedOf: (site, route) => {
346
+ const chain = Site.chainOf(site, route);
347
+ for (let at = chain.length - 1; at >= 0; at--) {
348
+ const indexed = chain[at].indexed;
349
+ if (indexed !== void 0) return indexed;
350
+ }
351
+ return true;
352
+ },
353
+ /**
354
+ * What a route says of itself in the head, for an SSR plan's `meta`:
355
+ *
356
+ * ```ts
357
+ * SSR.plan(App, { id: 'site', state, meta: model => Site.metaOf(AppSite, model.route, model) })
358
+ * ```
359
+ *
360
+ * Each node of the chain's `meta`, root first, with a deeper node's field
361
+ * replacing its ancestor's and a field it leaves out keeping the ancestor's.
362
+ * The preview title falls back to the route's `title`. An unindexed route
363
+ * (`Site.indexedOf`) is `noindex` whatever its `meta` says.
364
+ */
365
+ metaOf: (site, route, model) => {
366
+ let meta = {};
367
+ for (const node of Site.chainOf(site, route)) if (node.meta !== void 0) meta = {
368
+ ...meta,
369
+ ...saidOf(node.meta({
370
+ route,
371
+ model
372
+ }))
373
+ };
374
+ const title = meta.title ?? Site.titleOf(site, route);
375
+ return {
376
+ ...meta,
377
+ ...title === void 0 ? {} : { title },
378
+ ...Site.indexedOf(site, route) ? {} : { robots: "noindex" }
379
+ };
380
+ },
381
+ /** The navigation section the tree annotates for a route value, or nothing. */
382
+ sectionOf: (site, route) => indexOf(site).byTag.get(route._tag)?.section,
383
+ /**
384
+ * Where a section's nav item points: the first node of the section with a
385
+ * landing, as a target. Nothing when no node of the section declares one —
386
+ * every section shown needs a landing, so navigation asserts it.
387
+ */
388
+ landing: (site, section) => {
389
+ for (const candidate of Site.nodesOf(site)) {
390
+ if (candidate.section !== section) continue;
391
+ const landing = candidate.landing;
392
+ if (landing === void 0) continue;
393
+ return Site.target(candidate, landing);
394
+ }
395
+ },
396
+ /**
397
+ * The tree's shortcuts as key bindings, each sending the Message
398
+ * `toMessage` makes of its node's landing:
399
+ *
400
+ * ```ts
401
+ * Subscription.keyBindings({
402
+ * bindings: Site.shortcuts(AppSite, target => Message.PressedShortcut({ url: target.url })),
403
+ * })
404
+ * ```
405
+ *
406
+ * A shortcut on a node with no `landing` goes nowhere, and one used twice
407
+ * goes to two places; both are refused.
408
+ */
409
+ shortcuts: (site, toMessage) => {
410
+ const taken = /* @__PURE__ */ new Map();
411
+ return Site.nodesOf(site).flatMap((node) => {
412
+ const keys = node.shortcut;
413
+ if (keys === void 0) return [];
414
+ if (node.landing === void 0) throw new Error(`Site.shortcuts: "${node.tag}" has a shortcut and no landing to go to`);
415
+ const named = typeof keys === "string" ? keys : keys.join(" ");
416
+ const other = taken.get(named);
417
+ if (other !== void 0) throw new Error(`Site.shortcuts: "${named}" goes to both "${other}" and "${node.tag}"`);
418
+ taken.set(named, node.tag);
419
+ const message = toMessage(Site.target(node, node.landing));
420
+ const mapEvent = () => message;
421
+ return [typeof keys === "string" ? {
422
+ keys,
423
+ mapEvent
424
+ } : {
425
+ keys,
426
+ mapEvent
427
+ }];
428
+ });
429
+ },
430
+ /**
431
+ * Which history step a move is: to another node, a step; within a node, its
432
+ * declaration (a string, or a function for nodes where some param changes
433
+ * are entries of their own); with no previous target — the current location
434
+ * is unknown to the site — a step too, so Back can still return to it.
435
+ */
436
+ historyOf: (prev, next) => {
437
+ if (prev === void 0 || prev.node !== next.node) return "push";
438
+ const rule = next.node.history ?? "replace";
439
+ return typeof rule === "function" ? rule(prev.route, next.route) : rule;
440
+ },
441
+ /**
442
+ * What the route draws: the deepest node's view, wrapped by every
443
+ * ancestor's layout root-first. Ancestors contribute layouts only — never
444
+ * their views. Pure function composition over ordinary Foldkit rendering;
445
+ * unknown tags and viewless leaves fail loudly, since rendering one would
446
+ * guess.
447
+ */
448
+ view: (site, route, model, h) => {
449
+ const chain = Site.chainOf(site, route);
450
+ if (chain.length === 0) throw new Error(`Site.view: no node holds the tag "${route._tag}"`);
451
+ const leaf = chain[chain.length - 1];
452
+ if (leaf.view === void 0) throw new Error(`Site.view: "${leaf.tag}" draws nothing; give the leaf a view`);
453
+ let child = leaf.view.render(model, h);
454
+ for (let at = chain.length - 2; at >= 0; at--) {
455
+ const layout = chain[at].layout;
456
+ if (layout !== void 0) child = layout.render(child, model, h);
457
+ }
458
+ return child;
459
+ },
460
+ /**
461
+ * What the tree's surfaced nodes activate, keyed by tag, for `Data.wiring`,
462
+ * `Data.subscriptions`, `Data.satisfy`, or an SSR plan's `surfaces`: each
463
+ * node's `Surface.when` over the application's route place. A surface from
464
+ * another application is refused here, not at its reads.
465
+ */
466
+ sources: (site, owner, place) => {
467
+ const out = {};
468
+ for (const node of Site.nodesOf(site)) {
469
+ const entry = sourceOf(node, owner, place);
470
+ if (entry !== void 0) out[entry[0]] = entry[1];
471
+ }
472
+ return out;
473
+ },
474
+ /**
475
+ * The route-level Sources for one destination: the same entries as
476
+ * `Site.sources`, but only the target's chain. Prefetch, SSR, and DevTools
477
+ * read what a route will activate without building its Model first; the
478
+ * preparation itself stays caller-composed (`Data.satisfy` over these, with
479
+ * the route set to the target's). A tag the tree does not hold resolves to
480
+ * no Sources, the way an inactive Surface resolves to nothing.
481
+ *
482
+ * ```ts
483
+ * const active = Site.sourcesFor(AppSite, App.owner, App.model.route, target.route)
484
+ * const prepared = yield* Data.satisfy({ ...model, route: target.route }, active)
485
+ * ```
486
+ *
487
+ * There is deliberately no `SitePlan` object: the chain is already
488
+ * `Site.chainOf`, and the head is `Site.metaOf`.
489
+ */
490
+ sourcesFor: (site, owner, place, route) => {
491
+ const out = {};
492
+ for (const node of Site.chainOf(site, route)) {
493
+ const entry = sourceOf(node, owner, place);
494
+ if (entry !== void 0) out[entry[0]] = entry[1];
495
+ }
496
+ return out;
497
+ },
498
+ /**
499
+ * The application's link-click and URL-change lifecycle as one wiring, so
500
+ * `update` stops hand-writing those two branches. A click on a link the
501
+ * tree holds navigates (pushing or replacing per `Site.historyOf`); on any
502
+ * other, on this origin or not, it loads, since another document serves
503
+ * it (`Site.routeAt`); a URL change sets the route field — or touches
504
+ * nothing when the address parses to the route already shown, so an echo
505
+ * of our own write never re-renders or clears pending state. The
506
+ * application's own update answers nothing for either message; `reduces`
507
+ * names them for its guard, the way `Remote.reduces` does.
508
+ *
509
+ * ```ts
510
+ * const Routing = Site.routing<Model, Message, AppRoute>({
511
+ * site: AppSite,
512
+ * owner: App.owner,
513
+ * route: {
514
+ * dependency: App.model.route.dependency,
515
+ * get: (model) => model.route,
516
+ * set: (model, route) => modifyFields(model, { route: () => route }),
517
+ * },
518
+ * parse: urlToAppRoute,
519
+ * tags: { clicked: 'ClickedLink', changed: 'ChangedUrl' },
520
+ * completed: Message.CompletedNavigation,
521
+ * })
522
+ * const assembly = Bundle.assemble([Routing, ...pages])
523
+ * const update = assembly.update((model, message) =>
524
+ * Routing.reduces(message) ? { model } : updateOwn(model, message),
525
+ * )
526
+ * ```
527
+ *
528
+ * One routing per application: it claims the click tag and shares the
529
+ * change tag with URL mirrors, which read their slices first. With `pages`,
530
+ * a route change sets the field and then informs each page whose route
531
+ * arrived, through the page's own `changed` Message.
532
+ */
533
+ routing: (config) => {
534
+ const completedTag = tagOfConstructor(config.completed, "Site.routing: completed must be a message constructor");
535
+ const Navigate = Command.define("Site.Navigate", {
536
+ args: {
537
+ url: Schema.String,
538
+ history: Schema.Literals(["push", "replace"])
539
+ },
540
+ messages: [config.completed],
541
+ execute: ({ url, history }) => (history === "push" ? Navigation.pushUrl(url) : Navigation.replaceUrl(url)).pipe(Effect.as(config.completed()))
542
+ });
543
+ const { arrived } = config;
544
+ const Load = Command.define("Site.Load", {
545
+ args: { href: Schema.String },
546
+ messages: [config.completed],
547
+ execute: ({ href }) => Navigation.load(href).pipe(Effect.as(config.completed()))
548
+ });
549
+ const sameRoute = (a, b) => JSON.stringify(a) === JSON.stringify(b);
550
+ const setRoute = (model, next) => {
551
+ const current = config.route.get(model);
552
+ return sameRoute(current, next) ? model : config.route.set(model, next);
553
+ };
554
+ const currentTarget = (model) => {
555
+ const current = config.route.get(model);
556
+ const node = Site.nodeOf(config.site, current);
557
+ if (node === void 0) return void 0;
558
+ const { _tag, ...params } = current;
559
+ return Site.target(node, params);
560
+ };
561
+ const reduces = (message) => message._tag === config.tags.clicked || message._tag === config.tags.changed;
562
+ return {
563
+ key: "site",
564
+ handles: [config.tags.clicked, config.tags.changed],
565
+ shared: [config.tags.changed],
566
+ route: (model, message) => {
567
+ if (message._tag === config.tags.clicked) {
568
+ const request = message.request;
569
+ return Option.some(UrlRequest.match(request, {
570
+ Internal: ({ url }) => Option.match(Site.routeAt(config.site, url), {
571
+ onNone: () => ({
572
+ model,
573
+ commands: [Load({ href: Url$1.toString(url) })]
574
+ }),
575
+ onSome: (next) => {
576
+ const node = Site.nodeOf(config.site, next);
577
+ const history = Site.historyOf(currentTarget(model), {
578
+ node,
579
+ route: next,
580
+ url: Url$1.toString(url)
581
+ });
582
+ return {
583
+ model,
584
+ commands: [Navigate({
585
+ url: Url$1.toString(url),
586
+ history
587
+ })]
588
+ };
589
+ }
590
+ }),
591
+ External: ({ href }) => ({
592
+ model,
593
+ commands: [Load({ href })]
594
+ })
595
+ }));
596
+ }
597
+ if (message._tag === config.tags.changed) {
598
+ const url = message.url;
599
+ const next = config.parse(url);
600
+ if (sameRoute(config.route.get(model), next)) return Option.some({ model });
601
+ const steps = [
602
+ (model) => ({ model: setRoute(model, next) }),
603
+ ...(config.pages ?? []).map((page) => (model) => Option.getOrElse(page.inform(model, next), () => ({ model }))),
604
+ ...arrived === void 0 ? [] : [(model) => arrived(model, next)]
605
+ ];
606
+ return Option.some(Update.combine(model, steps));
607
+ }
608
+ return Option.none();
609
+ },
610
+ onUrl: (model, url) => setRoute(model, config.parse(url)),
611
+ contract: {
612
+ kind: "site",
613
+ name: "site",
614
+ owner: config.owner,
615
+ owns: [],
616
+ observes: [config.route.dependency],
617
+ messages: [completedTag],
618
+ metadata: []
619
+ },
620
+ reduces
621
+ };
622
+ },
623
+ /**
624
+ * One routed page stated once: its link (where its Model lives and how its
625
+ * Messages wrap), what starts it, and what its route arrival tells it. The
626
+ * link carries the field and the wrapper together; `placed.update` folds
627
+ * the child's Messages and `placed.view` draws it, and `Site.routing`
628
+ * informs it through `changed` when its route arrives.
629
+ *
630
+ * ```ts
631
+ * const PeoplePage = Site.placement(People, PeopleBundle, {
632
+ * link: Link.field<Model>()('peoplePage', Link.wrapper(Message.GotPeopleMessage)),
633
+ * args: parent => ({
634
+ * searchText: parent.route._tag === 'People' ? parent.route.searchText : Option.none(),
635
+ * }),
636
+ * changed: route => People.Message.ChangedRoute({ route }),
637
+ * })
638
+ * const assembly = Bundle.assemble([PeoplePage.placed, Routing])
639
+ * ```
640
+ *
641
+ * `changed` receives the node's own case value and returns the child's
642
+ * Message, or nothing when the arrival needs no answer. Without it the
643
+ * page is never informed. Bundles with OutMessages, and children that are
644
+ * not Bundles, stay on `Bundle.at` and `Link.child` directly.
645
+ */
646
+ placement: (node, bundle, config) => {
647
+ const { link, changed } = config;
648
+ const placed = bundle.at(link, config);
649
+ return {
650
+ node,
651
+ placed,
652
+ inform: (model, route) => {
653
+ if (!Predicate.isTagged(route, node.tag) || changed === void 0) return Option.none();
654
+ const child = changed(route);
655
+ if (child === void 0) return Option.none();
656
+ return placed.update(model, link.toParentMessage(child));
657
+ }
658
+ };
659
+ }
660
+ };
661
+ //#endregion
662
+ export { Site };
663
+
664
+ //# sourceMappingURL=index.mjs.map