@mvarble/mesearch-workflow 0.0.0-stage → 0.1.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 (165) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +109 -2
  3. package/agents/reference/authoring.md +142 -0
  4. package/agents/reference/workflow.md +118 -0
  5. package/agents/skills/wf-abandon/SKILL.md +18 -0
  6. package/agents/skills/wf-approve/SKILL.md +24 -0
  7. package/agents/skills/wf-build/SKILL.md +45 -0
  8. package/agents/skills/wf-plan/SKILL.md +49 -0
  9. package/agents/skills/wf-publish/SKILL.md +42 -0
  10. package/agents/skills/wf-reopen/SKILL.md +22 -0
  11. package/agents/skills/wf-resume/SKILL.md +16 -0
  12. package/agents/skills/wf-start/SKILL.md +27 -0
  13. package/agents/skills/wf-status/SKILL.md +15 -0
  14. package/agents/skills/wf-writeup/SKILL.md +61 -0
  15. package/app/ambient.d.ts +71 -0
  16. package/app/lib/components/CopyCode.svelte +24 -0
  17. package/app/lib/components/DocumentMap.svelte +38 -0
  18. package/app/lib/components/DocumentPage.svelte +184 -0
  19. package/app/lib/components/Icon.svelte +35 -0
  20. package/app/lib/components/ImageFigure.svelte +213 -0
  21. package/app/lib/components/LinkList.svelte +46 -0
  22. package/app/lib/components/ModelGraph.svelte +169 -0
  23. package/app/lib/components/OpenEntry.svelte +35 -0
  24. package/app/lib/components/PageList.svelte +35 -0
  25. package/app/lib/components/PrevNext.svelte +24 -0
  26. package/app/lib/components/Proof.svelte +12 -0
  27. package/app/lib/components/Shell.svelte +55 -0
  28. package/app/lib/components/Sidebar.svelte +50 -0
  29. package/app/lib/components/StageRail.svelte +30 -0
  30. package/app/lib/components/Statement.svelte +41 -0
  31. package/app/lib/components/Tex.svelte +25 -0
  32. package/app/lib/components/ThemeToggle.svelte +17 -0
  33. package/app/lib/components/Timeline.svelte +31 -0
  34. package/app/lib/components/Toc.svelte +41 -0
  35. package/app/lib/components/TopBar.svelte +55 -0
  36. package/app/lib/components/TrackCard.svelte +19 -0
  37. package/app/lib/documents.ts +52 -0
  38. package/app/lib/graph/describe.ts +29 -0
  39. package/app/lib/graph/geometry.ts +296 -0
  40. package/app/lib/graph/spec.ts +158 -0
  41. package/app/lib/kit.ts +11 -0
  42. package/app/lib/load.ts +12 -0
  43. package/app/lib/map.ts +6 -0
  44. package/app/lib/nav.ts +59 -0
  45. package/app/lib/questions.ts +33 -0
  46. package/app/lib/server/document.ts +117 -0
  47. package/app/lib/server/map.ts +41 -0
  48. package/app/lib/server/markdown.ts +134 -0
  49. package/app/lib/server/open.ts +35 -0
  50. package/app/lib/server/repo.ts +6 -0
  51. package/app/lib/server/specs.ts +26 -0
  52. package/app/lib/server/title.ts +9 -0
  53. package/app/lib/state/persisted.svelte.ts +40 -0
  54. package/app/lib/state/theme.svelte.ts +24 -0
  55. package/app/lib/tex.ts +99 -0
  56. package/app/params/slug.ts +5 -0
  57. package/app/params/track.ts +5 -0
  58. package/app/routes/+layout.ts +2 -0
  59. package/app/routes/[...key].md/+server.ts +19 -0
  60. package/app/routes/[track=track]/+page.server.ts +14 -0
  61. package/app/routes/[track=track]/+page.svelte +24 -0
  62. package/app/routes/[track=track]/[slug=slug]/+page.server.ts +9 -0
  63. package/app/routes/[track=track]/[slug=slug]/+page.svelte +7 -0
  64. package/app/routes/[track=track]/[slug=slug]/+page.ts +4 -0
  65. package/app/routes/archive/+page.server.ts +18 -0
  66. package/app/routes/archive/+page.svelte +44 -0
  67. package/app/routes/archive/[entry=slug]/+page.server.ts +9 -0
  68. package/app/routes/archive/[entry=slug]/+page.svelte +7 -0
  69. package/app/routes/archive/[entry=slug]/+page.ts +4 -0
  70. package/app/routes/archive/[entry=slug]/[name=slug]/+page.server.ts +14 -0
  71. package/app/routes/archive/[entry=slug]/[name=slug]/+page.svelte +7 -0
  72. package/app/routes/archive/[entry=slug]/[name=slug]/+page.ts +4 -0
  73. package/app/routes/llms-full.txt/+server.ts +17 -0
  74. package/app/routes/llms.txt/+server.ts +50 -0
  75. package/app/routes/math/+page.server.ts +21 -0
  76. package/app/routes/math/+page.svelte +56 -0
  77. package/app/routes/math/[slug=slug]/+page.server.ts +8 -0
  78. package/app/routes/math/[slug=slug]/+page.svelte +7 -0
  79. package/app/routes/math/[slug=slug]/+page.ts +4 -0
  80. package/app/styles/base.css +98 -0
  81. package/app/styles/code.css +83 -0
  82. package/app/styles/index.css +17 -0
  83. package/app/styles/katex.css +14 -0
  84. package/app/styles/layout.css +526 -0
  85. package/app/styles/text.css +96 -0
  86. package/app/styles/tokens/dimensions.css +31 -0
  87. package/app/styles/tokens/typography.css +33 -0
  88. package/app/styles/tokens.css +2 -0
  89. package/app/styles/utils/archive.css +339 -0
  90. package/app/styles/utils/buttons.css +28 -0
  91. package/app/styles/utils/callouts.css +41 -0
  92. package/app/styles/utils/cards.css +95 -0
  93. package/app/styles/utils/graph.css +186 -0
  94. package/app/styles/utils/map.css +45 -0
  95. package/app/styles/utils/tables.css +25 -0
  96. package/dist/cli.d.ts +2 -0
  97. package/dist/cli.js +88 -0
  98. package/dist/cli.js.map +1 -0
  99. package/dist/engine/cli.d.ts +12 -0
  100. package/dist/engine/cli.js +744 -0
  101. package/dist/engine/cli.js.map +1 -0
  102. package/dist/engine/config.d.ts +40 -0
  103. package/dist/engine/config.js +16 -0
  104. package/dist/engine/config.js.map +1 -0
  105. package/dist/engine/lib.d.ts +108 -0
  106. package/dist/engine/lib.js +375 -0
  107. package/dist/engine/lib.js.map +1 -0
  108. package/dist/engine/main.d.ts +1 -0
  109. package/dist/engine/main.js +45 -0
  110. package/dist/engine/main.js.map +1 -0
  111. package/dist/index.d.ts +4 -0
  112. package/dist/index.js +3 -0
  113. package/dist/index.js.map +1 -0
  114. package/dist/site/hooks.d.ts +27 -0
  115. package/dist/site/hooks.js +2 -0
  116. package/dist/site/hooks.js.map +1 -0
  117. package/dist/site/index.d.ts +1 -0
  118. package/dist/site/index.js +2 -0
  119. package/dist/site/index.js.map +1 -0
  120. package/dist/site/preset/index.d.ts +15 -0
  121. package/dist/site/preset/index.js +556 -0
  122. package/dist/site/preset/index.js.map +1 -0
  123. package/dist/site/preset/runtime.d.ts +42 -0
  124. package/dist/site/preset/runtime.js +99 -0
  125. package/dist/site/preset/runtime.js.map +1 -0
  126. package/dist/site/preset/types.d.ts +87 -0
  127. package/dist/site/preset/types.js +2 -0
  128. package/dist/site/preset/types.js.map +1 -0
  129. package/dist/site/vite.d.ts +14 -0
  130. package/dist/site/vite.js +202 -0
  131. package/dist/site/vite.js.map +1 -0
  132. package/dist/sync/index.d.ts +17 -0
  133. package/dist/sync/index.js +175 -0
  134. package/dist/sync/index.js.map +1 -0
  135. package/dist/sync/init.d.ts +7 -0
  136. package/dist/sync/init.js +62 -0
  137. package/dist/sync/init.js.map +1 -0
  138. package/dist/sync/render.d.ts +3 -0
  139. package/dist/sync/render.js +115 -0
  140. package/dist/sync/render.js.map +1 -0
  141. package/dist/sync/site.d.ts +3 -0
  142. package/dist/sync/site.js +58 -0
  143. package/dist/sync/site.js.map +1 -0
  144. package/package.json +78 -3
  145. package/templates/.agents/reference/authoring.md +12 -0
  146. package/templates/.agents/reference/stages/README.md +5 -0
  147. package/templates/AGENTS.md +42 -0
  148. package/templates/site/content/landing.md +5 -0
  149. package/templates/site/katex.config.ts +5 -0
  150. package/templates/site/package.json +22 -0
  151. package/templates/site/src/app.d.ts +8 -0
  152. package/templates/site/src/app.html +23 -0
  153. package/templates/site/src/lib/components/Logo.svelte +12 -0
  154. package/templates/site/src/lib/site.ts +39 -0
  155. package/templates/site/src/routes/+layout.server.ts +3 -0
  156. package/templates/site/src/routes/+layout.svelte +11 -0
  157. package/templates/site/src/routes/+page.server.ts +3 -0
  158. package/templates/site/src/routes/+page.svelte +34 -0
  159. package/templates/site/src/routes/+page.ts +7 -0
  160. package/templates/site/src/styles/index.css +4 -0
  161. package/templates/site/src/styles/tokens/colors.css +107 -0
  162. package/templates/site/static/favicon.svg +1 -0
  163. package/templates/site/tsconfig.json +20 -0
  164. package/templates/site/vite.config.ts +4 -0
  165. package/templates/workflow.config.ts +40 -0
@@ -0,0 +1,55 @@
1
+ <script lang="ts">
2
+ import { resolve } from '$app/paths';
3
+ import { page } from '$app/state';
4
+ import { Logo, SITE } from '$site';
5
+ import type { NavSection } from '../nav';
6
+ import Icon from './Icon.svelte';
7
+ import ThemeToggle from './ThemeToggle.svelte';
8
+
9
+ let {
10
+ menuOpen = $bindable(false),
11
+ showMenu = true,
12
+ }: { menuOpen?: boolean; showMenu?: boolean } = $props();
13
+
14
+ // Every section but "Start here", which the home page leads to.
15
+ const sections = $derived((page.data.nav as NavSection[]).filter((s) => s.id != 'start'));
16
+ const current = $derived(page.url.pathname);
17
+ </script>
18
+
19
+ <header class="topbar">
20
+ {#if showMenu}
21
+ <button
22
+ class="icon-button menu-button"
23
+ type="button"
24
+ aria-label={menuOpen ? 'Close navigation' : 'Open navigation'}
25
+ aria-expanded={menuOpen}
26
+ aria-controls="sidebar"
27
+ onclick={() => (menuOpen = !menuOpen)}
28
+ >
29
+ <Icon name={menuOpen ? 'close' : 'menu'} />
30
+ </button>
31
+ {/if}
32
+
33
+ <a class="wordmark" href={resolve('/')}>
34
+ <Logo variant="icon" />
35
+ <span>{SITE.name}</span>
36
+ <span class="version">v{SITE.version}</span>
37
+ </a>
38
+
39
+ <nav class="track-nav" aria-label="Sections">
40
+ {#each sections as section (section.id)}
41
+ <a
42
+ href={section.href}
43
+ aria-current={current.startsWith(section.href) ? 'page' : undefined}
44
+ >{section.short}</a
45
+ >
46
+ {/each}
47
+ </nav>
48
+
49
+ <div class="topbar-actions">
50
+ <a class="icon-button" href={SITE.repo} rel="external" aria-label="Source on GitHub">
51
+ <Icon name="github" />
52
+ </a>
53
+ <ThemeToggle />
54
+ </div>
55
+ </header>
@@ -0,0 +1,19 @@
1
+ <script lang="ts">
2
+ import { page } from '$app/state';
3
+ import type { NavSection } from '../nav';
4
+
5
+ let { id, eyebrow, blurb }: { id: string; eyebrow?: string; blurb: string } = $props();
6
+ const section = $derived((page.data.nav as NavSection[]).find((s) => s.id == id)!);
7
+ const first = $derived(section.items[0]);
8
+ </script>
9
+
10
+ <a class="card track-card" href={first && id != 'archive' ? first.href : section.href}>
11
+ {#if eyebrow}<span class="eyebrow">{eyebrow}</span>{/if}
12
+ <span class="card-title">{section.title}</span>
13
+ <span class="card-body">{blurb}</span>
14
+ {#if first && id != 'archive'}
15
+ <span class="card-cta">Begin with “{first.title}” →</span>
16
+ {:else if !first}
17
+ <span class="card-cta muted">Nothing here yet.</span>
18
+ {/if}
19
+ </a>
@@ -0,0 +1,52 @@
1
+ import { resolve } from '$app/paths';
2
+ import type { SiteDocument } from '@mvarble/mesearch-workflow/preset';
3
+
4
+ export type {
5
+ Heading,
6
+ SiteDocument,
7
+ SiteEntry,
8
+ SiteEntryDocument,
9
+ SiteMath,
10
+ SitePage,
11
+ WorkflowEvent,
12
+ } from '@mvarble/mesearch-workflow/preset';
13
+
14
+ // What the navigation and the lists of documents need of one, small enough to send with every
15
+ // page.
16
+ export interface DocumentLink {
17
+ key: string;
18
+ kind: SiteDocument['kind'];
19
+ title: string;
20
+ href: string;
21
+ summary: string;
22
+ status?: string;
23
+ }
24
+
25
+ // A document's URL, from its key: `<track>/<slug>`, `math/<slug>`, `archive/<slug>` or
26
+ // `archive/<slug>/<name>`.
27
+ export function hrefOf(key: string): string {
28
+ const [first, second, third] = key.split('/') as [string, string, string?];
29
+ if (first == 'math') return resolve('/math/[slug=slug]', { slug: second });
30
+ if (first == 'archive') {
31
+ return third
32
+ ? resolve('/archive/[entry=slug]/[name=slug]', { entry: second, name: third })
33
+ : resolve('/archive/[entry=slug]', { entry: second });
34
+ }
35
+ return resolve('/[track=track]/[slug=slug]', { track: first, slug: second });
36
+ }
37
+
38
+ // The Markdown version of a document.
39
+ export function markdownHrefOf(key: string): string {
40
+ return resolve('/[...key].md', { key });
41
+ }
42
+
43
+ export function linkOf(record: SiteDocument): DocumentLink {
44
+ return {
45
+ key: record.key,
46
+ kind: record.kind,
47
+ title: record.title,
48
+ href: hrefOf(record.key),
49
+ summary: record.summary,
50
+ ...(record.kind == 'entry' ? { status: record.status } : {}),
51
+ };
52
+ }
@@ -0,0 +1,29 @@
1
+ import { hasTex } from '../tex';
2
+ import type { GraphSpec } from './spec';
3
+
4
+ // A graph figure as Markdown text, for the `.md` exports: a reader without the SVG still gets every
5
+ // node and edge, and the figure's name for the kind of each.
6
+ export function describeGraph(spec: GraphSpec): string {
7
+ // A label with math is left as `$…$`, which Markdown readers treat as math; anything else is
8
+ // set as code.
9
+ const quote = (text: string) => (hasTex(text) ? text : `\`${text}\``);
10
+ const name = new Map(spec.nodes.map((n) => [n.id, quote(n.label ?? n.id)]));
11
+ const lines = [`**Figure: ${spec.title}.**${spec.caption ? ` ${spec.caption}` : ''}`, ''];
12
+
13
+ lines.push('Nodes:', '');
14
+ for (const node of spec.nodes) {
15
+ const extra = node.annotation ? `, ${node.annotation}` : '';
16
+ lines.push(
17
+ `- ${name.get(node.id)}: ${spec.nodeKinds[node.kind]?.name ?? node.kind}${extra}`,
18
+ );
19
+ }
20
+
21
+ lines.push('', 'Edges:', '');
22
+ for (const edge of spec.edges) {
23
+ const kind = edge.kind === undefined ? undefined : spec.edgeKinds?.[edge.kind];
24
+ const what = kind ? `: ${kind.name}` : '';
25
+ const label = edge.label ? ` (“${edge.label}”)` : '';
26
+ lines.push(`- ${name.get(edge.from)} → ${name.get(edge.to)}${what}${label}`);
27
+ }
28
+ return lines.join('\n');
29
+ }
@@ -0,0 +1,296 @@
1
+ import type { EdgeSpec, GraphSpec, NodeSpec, Point } from './spec';
2
+
3
+ // Turns a `GraphSpec` into SVG-ready geometry. Everything here is computed in the spec's
4
+ // mathematical coordinates (+Y up); `flip` converts to SVG coordinates (+Y down) only when a
5
+ // coordinate is written out.
6
+
7
+ export interface NodeLayout {
8
+ spec: NodeSpec;
9
+ shape: 'circle' | 'square';
10
+ r: number;
11
+ /** Center, in SVG coordinates. */
12
+ cx: number;
13
+ cy: number;
14
+ annotation?: TextLayout;
15
+ }
16
+
17
+ /**
18
+ * Where a piece of text goes, in SVG coordinates. `anchor` says which part of the text's box sits
19
+ * on (x, y) horizontally, and `baseline` vertically: `auto` puts the box above the point, `hanging`
20
+ * below it.
21
+ */
22
+ export interface TextLayout {
23
+ x: number;
24
+ y: number;
25
+ anchor: 'start' | 'middle' | 'end';
26
+ baseline: 'auto' | 'middle' | 'hanging';
27
+ }
28
+
29
+ export interface EdgeLayout {
30
+ spec: EdgeSpec;
31
+ /** The SVG path data of the edge's line, stopping short of any arrowhead. */
32
+ d: string;
33
+ /** The SVG `points` of each arrowhead polygon. */
34
+ arrows: string[];
35
+ label?: { x: number; y: number };
36
+ }
37
+
38
+ export interface GraphLayout {
39
+ width: number;
40
+ height: number;
41
+ fontSize: number;
42
+ nodes: NodeLayout[];
43
+ edges: EdgeLayout[];
44
+ }
45
+
46
+ type Vec = Point;
47
+
48
+ const add = (a: Vec, b: Vec): Vec => [a[0] + b[0], a[1] + b[1]];
49
+ const sub = (a: Vec, b: Vec): Vec => [a[0] - b[0], a[1] - b[1]];
50
+ const scale = (a: Vec, k: number): Vec => [a[0] * k, a[1] * k];
51
+ const norm = (a: Vec) => Math.hypot(a[0], a[1]);
52
+ const unit = (a: Vec): Vec => {
53
+ const n = norm(a);
54
+ return n > 1e-9 ? scale(a, 1 / n) : [1, 0];
55
+ };
56
+ const radians = (degrees: number) => (degrees * Math.PI) / 180;
57
+ const direction = (degrees: number): Vec => [
58
+ Math.cos(radians(degrees)),
59
+ Math.sin(radians(degrees)),
60
+ ];
61
+ const angleTo = (from: Vec, to: Vec) =>
62
+ (Math.atan2(to[1] - from[1], to[0] - from[0]) * 180) / Math.PI;
63
+
64
+ /** The point where the ray from a node's center at `angle` leaves its boundary. */
65
+ export function boundaryPoint(
66
+ node: { x: number; y: number; r: number; shape: 'circle' | 'square' },
67
+ angle: number,
68
+ ): Vec {
69
+ const [c, s] = direction(angle);
70
+ const reach = node.shape == 'square' ? node.r / Math.max(Math.abs(c), Math.abs(s)) : node.r;
71
+ return [node.x + reach * c, node.y + reach * s];
72
+ }
73
+
74
+ interface Resolved {
75
+ x: number;
76
+ y: number;
77
+ r: number;
78
+ shape: 'circle' | 'square';
79
+ }
80
+
81
+ export function layoutGraph(spec: GraphSpec): GraphLayout {
82
+ const fontSize = spec.fontSize ?? 15;
83
+ const arrowSize = spec.arrowSize ?? 10;
84
+ const flip = ([x, y]: Vec): Vec => [x, spec.height - y];
85
+
86
+ const resolved = new Map<string, Resolved>();
87
+ const nodes: NodeLayout[] = spec.nodes.map((node) => {
88
+ if (resolved.has(node.id))
89
+ throw new Error(`Graph "${spec.title}": duplicate node "${node.id}".`);
90
+ const kind = spec.nodeKinds[node.kind];
91
+ if (!kind) {
92
+ throw new Error(
93
+ `Graph "${spec.title}": node "${node.id}" is of kind "${node.kind}", which ` +
94
+ `\`nodeKinds\` does not define.`,
95
+ );
96
+ }
97
+ const r = node.r ?? spec.nodeRadius ?? 22;
98
+ const shape = node.shape ?? kind.shape ?? 'circle';
99
+ const geometry = { x: node.x, y: node.y, r, shape };
100
+ resolved.set(node.id, geometry);
101
+ const [cx, cy] = flip([node.x, node.y]);
102
+ return {
103
+ spec: node,
104
+ shape,
105
+ r,
106
+ cx,
107
+ cy,
108
+ annotation: node.annotation
109
+ ? annotationAt(geometry, node.annotationAngle ?? -90, fontSize, flip)
110
+ : undefined,
111
+ };
112
+ });
113
+
114
+ const find = (id: string, edge: EdgeSpec) => {
115
+ const node = resolved.get(id);
116
+ if (!node) {
117
+ throw new Error(
118
+ `Graph "${spec.title}": edge ${edge.from} → ${edge.to} names no node "${id}".`,
119
+ );
120
+ }
121
+ return node;
122
+ };
123
+
124
+ const edges = spec.edges.map((edge): EdgeLayout => {
125
+ if (edge.kind !== undefined && !spec.edgeKinds?.[edge.kind]) {
126
+ throw new Error(
127
+ `Graph "${spec.title}": edge ${edge.from} → ${edge.to} is of kind ` +
128
+ `"${edge.kind}", which \`edgeKinds\` does not define.`,
129
+ );
130
+ }
131
+ return layoutEdge(edge, find(edge.from, edge), find(edge.to, edge), arrowSize, flip);
132
+ });
133
+
134
+ return { width: spec.width, height: spec.height, fontSize, nodes, edges };
135
+ }
136
+
137
+ function annotationAt(
138
+ node: Resolved,
139
+ angle: number,
140
+ fontSize: number,
141
+ flip: (p: Vec) => Vec,
142
+ ): TextLayout {
143
+ const [c, s] = direction(angle);
144
+ const [x, y] = flip(add(boundaryPoint(node, angle), scale([c, s], fontSize * 0.45)));
145
+ return {
146
+ x,
147
+ y,
148
+ anchor: c > 0.3 ? 'start' : c < -0.3 ? 'end' : 'middle',
149
+ // Above the node the text sits on its baseline; below, it hangs from its top.
150
+ baseline: s > 0.3 ? 'auto' : s < -0.3 ? 'hanging' : 'middle',
151
+ };
152
+ }
153
+
154
+ /** A cubic Bézier segment, as its four control points. */
155
+ type Cubic = [Vec, Vec, Vec, Vec];
156
+
157
+ function layoutEdge(
158
+ edge: EdgeSpec,
159
+ from: Resolved,
160
+ to: Resolved,
161
+ arrowSize: number,
162
+ flip: (p: Vec) => Vec,
163
+ ): EdgeLayout {
164
+ const via = edge.via ?? [];
165
+ const bend = via.length ? 0 : (edge.bend ?? 0);
166
+ const curve = edge.curve ?? (bend ? 'bezier' : 'straight');
167
+ const arrow = edge.arrow ?? 'end';
168
+
169
+ const fromCenter: Vec = [from.x, from.y];
170
+ const toCenter: Vec = [to.x, to.y];
171
+ const fromAngle = edge.fromAngle ?? angleTo(fromCenter, via[0] ?? toCenter) + bend;
172
+ const toAngle = edge.toAngle ?? angleTo(toCenter, via.at(-1) ?? fromCenter) - bend;
173
+ const points: Vec[] = [boundaryPoint(from, fromAngle), ...via, boundaryPoint(to, toAngle)];
174
+
175
+ // The path as either line segments or cubic segments. An arrowhead's tip sits on the node's
176
+ // boundary, so the line is shortened by the arrowhead's length at that end.
177
+ const arrows: Vec[][] = [];
178
+ let d: string;
179
+ let samples: Vec[];
180
+
181
+ if (curve == 'straight') {
182
+ if (arrow == 'end' || arrow == 'both') {
183
+ const last = points.length - 1;
184
+ const dir = unit(sub(points[last], points[last - 1]));
185
+ arrows.push(arrowhead(points[last], dir, arrowSize));
186
+ points[last] = sub(points[last], scale(dir, arrowSize));
187
+ }
188
+ if (arrow == 'start' || arrow == 'both') {
189
+ const dir = unit(sub(points[0], points[1]));
190
+ arrows.push(arrowhead(points[0], dir, arrowSize));
191
+ points[0] = sub(points[0], scale(dir, arrowSize));
192
+ }
193
+ d = points.map((p, i) => `${i ? 'L' : 'M'} ${fmt(flip(p))}`).join(' ');
194
+ samples = points;
195
+ } else {
196
+ const cubics = smoothThrough(points, direction(fromAngle), direction(toAngle));
197
+ if (arrow == 'end' || arrow == 'both') {
198
+ const last = cubics[cubics.length - 1];
199
+ const dir = travelInto(last[3], [last[2], last[1], last[0]], direction(toAngle));
200
+ arrows.push(arrowhead(last[3], dir, arrowSize));
201
+ last[3] = sub(last[3], scale(dir, arrowSize));
202
+ last[2] = sub(last[2], scale(dir, arrowSize));
203
+ }
204
+ if (arrow == 'start' || arrow == 'both') {
205
+ const first = cubics[0];
206
+ const dir = travelInto(first[0], [first[1], first[2], first[3]], direction(fromAngle));
207
+ arrows.push(arrowhead(first[0], dir, arrowSize));
208
+ first[0] = sub(first[0], scale(dir, arrowSize));
209
+ first[1] = sub(first[1], scale(dir, arrowSize));
210
+ }
211
+ d =
212
+ `M ${fmt(flip(cubics[0][0]))} ` +
213
+ cubics
214
+ .map(([, c1, c2, p]) => `C ${fmt(flip(c1))} ${fmt(flip(c2))} ${fmt(flip(p))}`)
215
+ .join(' ');
216
+ samples = cubics.flatMap((c, i) => sampleCubic(c, 24).slice(i ? 1 : 0));
217
+ }
218
+
219
+ return {
220
+ spec: edge,
221
+ d,
222
+ arrows: arrows.map((polygon) => polygon.map((p) => fmt(flip(p))).join(' ')),
223
+ label: edge.label ? toXY(flip(alongPolyline(samples, edge.labelAt ?? 0.5))) : undefined,
224
+ };
225
+ }
226
+
227
+ /**
228
+ * A smooth curve through `points` (a Catmull–Rom spline, as cubic segments) that leaves the first
229
+ * point along `startNormal` and arrives at the last point against `endNormal`, both of which point
230
+ * out of their nodes.
231
+ */
232
+ export function smoothThrough(points: Vec[], startNormal: Vec, endNormal: Vec): Cubic[] {
233
+ const n = points.length - 1;
234
+ // Endpoint tangents are 1.2 chord lengths, so that a two-point curve has its control points
235
+ // 0.4 of the way along, much as TikZ's default looseness does.
236
+ const tangents = points.map((p, i): Vec => {
237
+ if (i == 0) return scale(startNormal, 1.2 * norm(sub(points[1], p)));
238
+ if (i == n) return scale(endNormal, -1.2 * norm(sub(p, points[n - 1])));
239
+ return scale(sub(points[i + 1], points[i - 1]), 0.5);
240
+ });
241
+ return points
242
+ .slice(0, n)
243
+ .map((p, i) => [
244
+ p,
245
+ add(p, scale(tangents[i], 1 / 3)),
246
+ sub(points[i + 1], scale(tangents[i + 1], 1 / 3)),
247
+ points[i + 1],
248
+ ]);
249
+ }
250
+
251
+ /**
252
+ * The direction in which a curve arrives at its endpoint `tip`, from the nearest of `candidates`
253
+ * (the control points, nearest first) that differs from it: a control point can coincide with its
254
+ * endpoint. If they all do, the curve arrives against the node's outward `normal`.
255
+ */
256
+ function travelInto(tip: Vec, candidates: Vec[], normal: Vec): Vec {
257
+ for (const p of candidates) {
258
+ if (norm(sub(tip, p)) > 1e-6) return unit(sub(tip, p));
259
+ }
260
+ return scale(normal, -1);
261
+ }
262
+
263
+ function arrowhead(tip: Vec, dir: Vec, size: number): Vec[] {
264
+ const base = sub(tip, scale(dir, size));
265
+ const across = scale([-dir[1], dir[0]], size * 0.45);
266
+ return [tip, add(base, across), sub(base, across)];
267
+ }
268
+
269
+ function sampleCubic([p0, p1, p2, p3]: Cubic, count: number): Vec[] {
270
+ return Array.from({ length: count + 1 }, (_, i) => {
271
+ const t = i / count;
272
+ const u = 1 - t;
273
+ return add(
274
+ add(scale(p0, u * u * u), scale(p1, 3 * u * u * t)),
275
+ add(scale(p2, 3 * u * t * t), scale(p3, t * t * t)),
276
+ );
277
+ });
278
+ }
279
+
280
+ /** The point a `fraction` of the way along a polyline, by length. */
281
+ export function alongPolyline(points: Vec[], fraction: number): Vec {
282
+ const lengths = points.slice(1).map((p, i) => norm(sub(p, points[i])));
283
+ let remaining = Math.min(Math.max(fraction, 0), 1) * lengths.reduce((a, b) => a + b, 0);
284
+ for (let i = 0; i < lengths.length; i++) {
285
+ if (remaining <= lengths[i] || i == lengths.length - 1) {
286
+ const t = lengths[i] ? Math.min(remaining / lengths[i], 1) : 0;
287
+ return add(points[i], scale(sub(points[i + 1], points[i]), t));
288
+ }
289
+ remaining -= lengths[i];
290
+ }
291
+ return points[0];
292
+ }
293
+
294
+ const round = (v: number) => Math.round(v * 100) / 100;
295
+ const fmt = ([x, y]: Vec) => `${round(x)},${round(y)}`;
296
+ const toXY = ([x, y]: Vec) => ({ x: round(x), y: round(y) });
@@ -0,0 +1,158 @@
1
+ // The input to `<ModelGraph>`: a hand-placed figure of a graph.
2
+ //
3
+ // A figure names its own kinds of node and edge. The component knows nothing of what a node
4
+ // means: each figure says what its kinds are called (in the legend and in the Markdown export) and
5
+ // how each is drawn, from a fixed palette of hues, shapes and line styles.
6
+ //
7
+ // Every piece of text (kind names, node labels, annotations, edge labels, the caption) may contain
8
+ // inline KaTeX between dollar signs, e.g. String.raw`$\log p(x \mid \mu)$`. `\$` is a literal
9
+ // dollar sign.
10
+ //
11
+ // Coordinates are mathematical, not SVG: the origin is the bottom-left corner of the viewport, +X
12
+ // points right and +Y points **up**. Angles are in degrees, counter-clockwise from +X, so 90° is
13
+ // straight up. Lengths are in viewport units; the figure scales to fit its column.
14
+
15
+ /** The palette. Each hue is a token `--graph-<hue>` in `tokens/colors.css`, tuned for both themes. */
16
+ export const HUES = [
17
+ 'gray',
18
+ 'blue',
19
+ 'orange',
20
+ 'green',
21
+ 'purple',
22
+ 'teal',
23
+ 'red',
24
+ 'sky',
25
+ 'amber',
26
+ 'olive',
27
+ 'magenta',
28
+ ] as const;
29
+ export type Hue = (typeof HUES)[number];
30
+
31
+ /** A kind of node: what the figure calls it, and how it is drawn. */
32
+ export interface NodeKindSpec {
33
+ /** Its name in the legend and the Markdown export, e.g. `Quantity`. */
34
+ name: string;
35
+ hue: Hue;
36
+ /** Defaults to `circle`. */
37
+ shape?: 'circle' | 'square';
38
+ /** `shaded` fills the node strongly, the convention for an observed quantity. Defaults to `light`. */
39
+ fill?: 'light' | 'shaded';
40
+ /** Defaults to `solid`. */
41
+ outline?: 'solid' | 'dashed';
42
+ }
43
+
44
+ /** A kind of edge: what the figure calls it, and how it is drawn. */
45
+ export interface EdgeKindSpec {
46
+ /** Its name in the legend and the Markdown export, e.g. `input of`. */
47
+ name: string;
48
+ /** Defaults to the neutral edge colour. */
49
+ hue?: Hue;
50
+ /** Defaults to `solid`. */
51
+ line?: 'solid' | 'dotted' | 'dashed';
52
+ }
53
+
54
+ export type Point = [x: number, y: number];
55
+
56
+ export interface NodeSpec {
57
+ id: string;
58
+ /** The center, in mathematical coordinates. */
59
+ x: number;
60
+ y: number;
61
+ /** A key of the figure's `nodeKinds`. */
62
+ kind: string;
63
+ /** Radius, or half the side of a square. Defaults to the figure's `nodeRadius`. */
64
+ r?: number;
65
+ /** Overrides the kind's shape. */
66
+ shape?: 'circle' | 'square';
67
+ /** Text drawn inside the node: plain (`x₁`) or TeX (`$x_1$`). */
68
+ label?: string;
69
+ /** Text drawn just outside the node, e.g. a quantity type or an operation. */
70
+ annotation?: string;
71
+ /** Where the annotation sits, as an angle on the node. Defaults to -90 (below). */
72
+ annotationAngle?: number;
73
+ /** A hover tooltip. */
74
+ title?: string;
75
+ /** Draw faintly, to focus attention elsewhere. */
76
+ muted?: boolean;
77
+ class?: string;
78
+ style?: string;
79
+ }
80
+
81
+ export interface EdgeSpec {
82
+ from: string;
83
+ to: string;
84
+ /**
85
+ * A key of the figure's `edgeKinds`. Without one, the edge is a plain solid line in the
86
+ * neutral colour, and the legend does not list it.
87
+ */
88
+ kind?: string;
89
+ /**
90
+ * Where the edge leaves `from` / meets `to`, as an angle on that node. Defaults to the direction
91
+ * of the edge's next point (the other node's center, or the nearest `via` point).
92
+ */
93
+ fromAngle?: number;
94
+ toAngle?: number;
95
+ /** Intermediate points the edge passes through. */
96
+ via?: Point[];
97
+ /**
98
+ * `straight` joins the points with line segments. `bezier` draws a smooth curve through them
99
+ * that leaves and meets each node along its normal. Defaults to `bezier` when `bend` is set.
100
+ */
101
+ curve?: 'straight' | 'bezier';
102
+ /**
103
+ * Rotate both default endpoint angles by this many degrees, as TikZ's `bend left` does:
104
+ * positive bows the edge to the left of its direction of travel. Ignored when `via` is set.
105
+ */
106
+ bend?: number;
107
+ /** Defaults to `end`. */
108
+ arrow?: 'end' | 'start' | 'both' | 'none';
109
+ label?: string;
110
+ /** How far along the edge the label sits, from 0 to 1. Defaults to 0.5. */
111
+ labelAt?: number;
112
+ muted?: boolean;
113
+ class?: string;
114
+ style?: string;
115
+ }
116
+
117
+ export interface GraphSpec {
118
+ /** The viewport. */
119
+ width: number;
120
+ height: number;
121
+ /** The figure's accessible name, also shown as the start of its caption. */
122
+ title: string;
123
+ /** A sentence or two explaining the figure. Kept in the Markdown export. */
124
+ caption?: string;
125
+ /** The figure's kinds of node, by key. The legend lists them in this order. */
126
+ nodeKinds: Record<string, NodeKindSpec>;
127
+ /** The figure's kinds of edge, by key. The legend lists them in this order. */
128
+ edgeKinds?: Record<string, EdgeKindSpec>;
129
+ nodes: NodeSpec[];
130
+ edges: EdgeSpec[];
131
+ /** Default node radius. Defaults to 22. */
132
+ nodeRadius?: number;
133
+ /** Text size, in viewport units. Defaults to 15. */
134
+ fontSize?: number;
135
+ /** Arrowhead length, in viewport units. Defaults to 10. */
136
+ arrowSize?: number;
137
+ /** KaTeX macros for this figure, over the site-wide ones in `katex.config.ts`. */
138
+ katexMacros?: Record<string, string>;
139
+ /** Show a legend of the node and edge kinds used. Defaults to true. */
140
+ legend?: boolean;
141
+ }
142
+
143
+ /** An identity function that type-checks a spec where it is written. */
144
+ export const defineGraph = (spec: GraphSpec): GraphSpec => spec;
145
+
146
+ /** The CSS classes that draw a node of `kind`. */
147
+ export const nodeKindClasses = (kind: NodeKindSpec) =>
148
+ [
149
+ `hue-${kind.hue}`,
150
+ kind.fill == 'shaded' && 'fill-shaded',
151
+ kind.outline == 'dashed' && 'outline-dashed',
152
+ ]
153
+ .filter(Boolean)
154
+ .join(' ');
155
+
156
+ /** The CSS classes that draw an edge of `kind`, or a plain edge when there is none. */
157
+ export const edgeKindClasses = (kind: EdgeKindSpec | undefined) =>
158
+ [kind?.hue && `hue-${kind.hue}`, `line-${kind?.line ?? 'solid'}`].filter(Boolean).join(' ');
package/app/lib/kit.ts ADDED
@@ -0,0 +1,11 @@
1
+ // The types SvelteKit generates as `./$types` for a route in a project, which a route shipped in
2
+ // this package has none of: the same shapes, with parameters left as strings.
3
+ import type { Load, RequestHandler as KitRequestHandler, ServerLoad } from '@sveltejs/kit';
4
+
5
+ type Params = Record<string, string>;
6
+
7
+ export type EntryGenerator = () => Params[] | Promise<Params[]>;
8
+ export type PageServerLoad = ServerLoad<Params>;
9
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
10
+ export type PageLoad = Load<Params, any>;
11
+ export type RequestHandler = KitRequestHandler<Params>;
@@ -0,0 +1,12 @@
1
+ import loaders from '$cms/loaders';
2
+ import type { Component } from 'svelte';
3
+
4
+ // A document's body is a compiled component, which cannot travel as data from the server: each
5
+ // document route's `+page.ts` attaches it here, by the filename the server load sent.
6
+ export async function withComponent<T extends { doc: { filename: string } }>(
7
+ data: T,
8
+ ): Promise<T & { component: Component }> {
9
+ const load = loaders[data.doc.filename];
10
+ if (!load) throw new Error(`No component for ${data.doc.filename}.`);
11
+ return { ...data, component: (await load()).default };
12
+ }
package/app/lib/map.ts ADDED
@@ -0,0 +1,6 @@
1
+ import type { GraphTuning } from '@mvarble/mesearch-ui';
2
+
3
+ // How the document map is laid out: stronger repulsion and longer links than mesearch's defaults,
4
+ // so that labels as long as skoro's keep their distance. The build lays the map out with it, and
5
+ // the component re-runs the same simulation with it when a node is dragged.
6
+ export const MAP_TUNING: GraphTuning = { charge: -5000, linkDistance: 200, gravity: 0.008 };