@supa-media/tex-contract 0.0.0-stage → 0.3.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 (227) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +33 -2
  3. package/package.json +16 -4
  4. package/texContract/aboutLines.cjs +117 -0
  5. package/texContract/aboutLines.d.cts +14 -0
  6. package/texContract/aboutNoteLimits.cjs +41 -0
  7. package/texContract/aboutNoteLimits.d.cts +5 -0
  8. package/texContract/actionManual.cjs +104 -0
  9. package/texContract/activityHint.cjs +40 -0
  10. package/texContract/activityHint.d.cts +4 -0
  11. package/texContract/asks.cjs +16 -0
  12. package/texContract/asks.d.cts +6 -0
  13. package/texContract/asksToFile.cjs +20 -0
  14. package/texContract/asksToFile.d.cts +2 -0
  15. package/texContract/attention.cjs +138 -0
  16. package/texContract/attention.d.cts +20 -0
  17. package/texContract/browserHandback.cjs +13 -0
  18. package/texContract/browserHandback.d.cts +3 -0
  19. package/texContract/browserOwner.cjs +31 -0
  20. package/texContract/browserOwner.d.cts +2 -0
  21. package/texContract/bytes.cjs +12 -0
  22. package/texContract/capabilities.cjs +47 -0
  23. package/texContract/capabilities.d.cts +27 -0
  24. package/texContract/capabilities.generated.json +77 -0
  25. package/texContract/chatHistoryPath.cjs +38 -0
  26. package/texContract/chatHistoryPath.d.cts +5 -0
  27. package/texContract/chatLedger.cjs +91 -0
  28. package/texContract/chatLedger.d.cts +21 -0
  29. package/texContract/computerTool.cjs +102 -0
  30. package/texContract/computerTool.d.cts +16 -0
  31. package/texContract/consentYes.cjs +22 -0
  32. package/texContract/consentYes.d.cts +5 -0
  33. package/texContract/contextGateway.cjs +52 -0
  34. package/texContract/contextGateway.d.cts +19 -0
  35. package/texContract/deskEligible.cjs +20 -0
  36. package/texContract/deskEligible.d.cts +3 -0
  37. package/texContract/downloads.cjs +129 -0
  38. package/texContract/downloads.d.cts +15 -0
  39. package/texContract/egressLedger.cjs +114 -0
  40. package/texContract/egressLedger.d.cts +14 -0
  41. package/texContract/emailRead.cjs +38 -0
  42. package/texContract/emailRead.d.cts +5 -0
  43. package/texContract/eventWords.cjs +35 -0
  44. package/texContract/eventWords.d.cts +4 -0
  45. package/texContract/fileParts.cjs +43 -0
  46. package/texContract/fileParts.d.cts +6 -0
  47. package/texContract/fileTables.cjs +243 -0
  48. package/texContract/fileWords.cjs +169 -0
  49. package/texContract/folded.cjs +16 -0
  50. package/texContract/folded.d.cts +3 -0
  51. package/texContract/googleAiAccess.cjs +12 -0
  52. package/texContract/googleAiAccess.d.cts +2 -0
  53. package/texContract/graphWires.cjs +18 -0
  54. package/texContract/graphWires.d.cts +5 -0
  55. package/texContract/groupSession.cjs +28 -0
  56. package/texContract/groupSession.d.cts +7 -0
  57. package/texContract/guestNames.cjs +136 -0
  58. package/texContract/guestNames.d.cts +35 -0
  59. package/texContract/heard.cjs +19 -0
  60. package/texContract/heard.d.cts +4 -0
  61. package/texContract/heldOffer.cjs +57 -0
  62. package/texContract/heldOffer.d.cts +8 -0
  63. package/texContract/helperCallers.cjs +29 -0
  64. package/texContract/helperCallers.d.cts +4 -0
  65. package/texContract/identity.cjs +179 -0
  66. package/texContract/identity.d.cts +8 -0
  67. package/texContract/jobLogEntries.cjs +93 -0
  68. package/texContract/jobLogEntries.d.cts +12 -0
  69. package/texContract/judgedActions.cjs +20 -0
  70. package/texContract/judgedActions.d.cts +4 -0
  71. package/texContract/labSandboxGate.cjs +63 -0
  72. package/texContract/labSandboxGate.d.cts +9 -0
  73. package/texContract/ledgerReadChars.cjs +4 -0
  74. package/texContract/ledgerReadChars.d.cts +3 -0
  75. package/texContract/mailCheck.cjs +90 -0
  76. package/texContract/mailCheck.d.cts +12 -0
  77. package/texContract/mailEntries.cjs +64 -0
  78. package/texContract/mailEntries.d.cts +13 -0
  79. package/texContract/mailHealth.cjs +60 -0
  80. package/texContract/mailHealth.d.cts +10 -0
  81. package/texContract/notePath.cjs +99 -0
  82. package/texContract/notePath.d.cts +4 -0
  83. package/texContract/noteRunFacts.cjs +136 -0
  84. package/texContract/noteRunFacts.d.cts +32 -0
  85. package/texContract/objectEtag.cjs +84 -0
  86. package/texContract/objectEtag.d.cts +4 -0
  87. package/texContract/objectPlace.cjs +32 -0
  88. package/texContract/objectPlace.d.cts +5 -0
  89. package/texContract/pageJobs.cjs +226 -0
  90. package/texContract/pageJobs.d.cts +13 -0
  91. package/texContract/pdfLinks.cjs +135 -0
  92. package/texContract/pdfLinks.d.cts +4 -0
  93. package/texContract/personHub.cjs +38 -0
  94. package/texContract/personHub.d.cts +5 -0
  95. package/texContract/personNameText.cjs +18 -0
  96. package/texContract/personNameText.d.cts +3 -0
  97. package/texContract/pinnedContext.cjs +12 -0
  98. package/texContract/pinnedContext.d.cts +3 -0
  99. package/texContract/quietHoursWindow.cjs +36 -0
  100. package/texContract/quietHoursWindow.d.cts +3 -0
  101. package/texContract/reactEmoji.cjs +79 -0
  102. package/texContract/reactEmoji.d.cts +2 -0
  103. package/texContract/scopeClamp.cjs +117 -0
  104. package/texContract/scopeClamp.d.cts +5 -0
  105. package/texContract/scopes.cjs +29 -0
  106. package/texContract/scopes.d.cts +7 -0
  107. package/texContract/searchSettings.cjs +54 -0
  108. package/texContract/searchSettings.d.cts +6 -0
  109. package/texContract/settingHabits.cjs +87 -0
  110. package/texContract/settingHabits.d.cts +20 -0
  111. package/texContract/settingsNotes.cjs +217 -0
  112. package/texContract/settingsNotes.d.cts +26 -0
  113. package/texContract/shownEmail.cjs +181 -0
  114. package/texContract/texClients.cjs +53 -0
  115. package/texContract/texClients.d.cts +12 -0
  116. package/texContract/texGraph.cjs +593 -0
  117. package/texContract/texGraph.d.cts +55 -0
  118. package/texContract/texKeys.cjs +100 -0
  119. package/texContract/texKeys.d.cts +13 -0
  120. package/texContract/texNumber.cjs +20 -0
  121. package/texContract/texNumber.d.cts +3 -0
  122. package/texContract/texOwnSources.cjs +9 -0
  123. package/texContract/texOwnSources.d.cts +3 -0
  124. package/texContract/texSettings.cjs +22 -0
  125. package/texContract/texSettings.d.cts +20 -0
  126. package/texContract/texSettings.generated.json +25 -0
  127. package/texContract/texStateFiles.cjs +22 -0
  128. package/texContract/texStateFiles.d.cts +9 -0
  129. package/texContract/texSteps.cjs +27 -0
  130. package/texContract/texSteps.d.cts +14 -0
  131. package/texContract/texSteps.generated.json +41 -0
  132. package/texContract/texStoreNames.cjs +26 -0
  133. package/texContract/texStoreNames.d.cts +12 -0
  134. package/texContract/texStoreWire.cjs +306 -0
  135. package/texContract/texStoreWire.d.cts +32 -0
  136. package/texContract/threadsFold.cjs +75 -0
  137. package/texContract/threadsFold.d.cts +22 -0
  138. package/texContract/toolActions.cjs +253 -0
  139. package/texContract/toolCatalog.cjs +49 -0
  140. package/texContract/toolCatalog.generated.json +90 -0
  141. package/texContract/toolContract.cjs +52 -0
  142. package/texContract/toolContract.d.cts +12 -0
  143. package/texContract/toolShapes.cjs +14 -0
  144. package/texContract/transcription.cjs +101 -0
  145. package/texContract/transcription.d.cts +3 -0
  146. package/texContract/treeJobs.cjs +31 -0
  147. package/texContract/treeJobs.d.cts +3 -0
  148. package/texContract/turnSession.cjs +90 -0
  149. package/texContract/turnSession.d.cts +19 -0
  150. package/texContract/turnWords.cjs +90 -0
  151. package/texContract/turnWords.d.cts +9 -0
  152. package/texContract/uploadImages.cjs +131 -0
  153. package/texContract/uploadImages.d.cts +13 -0
  154. package/texContract/v2Names.cjs +41 -0
  155. package/texContract/v2SearchFetch.cjs +316 -0
  156. package/texContract/v2Translate.cjs +123 -0
  157. package/texContract/vaultTools.cjs +112 -0
  158. package/texContract/vaultTools.d.cts +15 -0
  159. package/texContract/yesWords.cjs +91 -0
  160. package/texShared/argumentCoercion.cjs +93 -0
  161. package/texShared/cellComments.cjs +122 -0
  162. package/texShared/cellComments.d.cts +21 -0
  163. package/texShared/comments.cjs +586 -0
  164. package/texShared/comments.d.cts +115 -0
  165. package/texShared/contentTypes.cjs +85 -0
  166. package/texShared/fileKinds.cjs +123 -0
  167. package/texShared/flags.cjs +159 -0
  168. package/texShared/flags.d.cts +23 -0
  169. package/texShared/folderJobInfo.cjs +301 -0
  170. package/texShared/folderJobInfo.d.cts +40 -0
  171. package/texShared/folderRoles.cjs +512 -0
  172. package/texShared/folderRoles.d.cts +73 -0
  173. package/texShared/githubOidc.ts +98 -0
  174. package/texShared/groupRunQuestions.cjs +98 -0
  175. package/texShared/groupRunQuestions.d.cts +4 -0
  176. package/texShared/inboxFolders.cjs +49 -0
  177. package/texShared/inboxFolders.d.cts +5 -0
  178. package/texShared/ink/drawing.cjs +474 -0
  179. package/texShared/ink/texFigure.cjs +252 -0
  180. package/texShared/ink/texFigure.d.cts +36 -0
  181. package/texShared/ink/texPoses.cjs +180 -0
  182. package/texShared/ink/texPoses.d.cts +20 -0
  183. package/texShared/jobPartEnd.cjs +133 -0
  184. package/texShared/jobPartEnd.d.cts +13 -0
  185. package/texShared/jobResume.cjs +31 -0
  186. package/texShared/jobResume.d.cts +5 -0
  187. package/texShared/jobSplit.cjs +90 -0
  188. package/texShared/jobSplit.d.cts +6 -0
  189. package/texShared/jobStart.cjs +56 -0
  190. package/texShared/jobStart.d.cts +9 -0
  191. package/texShared/mail.cjs +400 -0
  192. package/texShared/mail.d.cts +56 -0
  193. package/texShared/messageAnchors.cjs +38 -0
  194. package/texShared/models/aiKeys.cjs +137 -0
  195. package/texShared/models/aiKeys.d.cts +42 -0
  196. package/texShared/models/aiKeys.json +56 -0
  197. package/texShared/models/creditRest.cjs +269 -0
  198. package/texShared/models/promptBudget.cjs +295 -0
  199. package/texShared/models/promptSections.cjs +29 -0
  200. package/texShared/noteAppLink.cjs +23 -0
  201. package/texShared/notePreview.cjs +219 -0
  202. package/texShared/notePreview.d.cts +21 -0
  203. package/texShared/pages/blocks.cjs +215 -0
  204. package/texShared/pages/cover.cjs +164 -0
  205. package/texShared/pages/css.cjs +181 -0
  206. package/texShared/pages/cssBlocks.cjs +264 -0
  207. package/texShared/pages/draw.cjs +212 -0
  208. package/texShared/pages/drawRich.cjs +232 -0
  209. package/texShared/pages/html.cjs +168 -0
  210. package/texShared/pages/inline.cjs +251 -0
  211. package/texShared/pages/layout.cjs +76 -0
  212. package/texShared/pages/parse.cjs +418 -0
  213. package/texShared/pages/render.cjs +200 -0
  214. package/texShared/pages/skill.cjs +147 -0
  215. package/texShared/pages/skill.d.cts +5 -0
  216. package/texShared/pages/templates.cjs +336 -0
  217. package/texShared/r2Store.cjs +163 -0
  218. package/texShared/remoteImage.cjs +177 -0
  219. package/texShared/routines.cjs +656 -0
  220. package/texShared/routines.d.cts +86 -0
  221. package/texShared/servedListing.cjs +250 -0
  222. package/texShared/servedListing.d.cts +17 -0
  223. package/texShared/sheetCsv.cjs +566 -0
  224. package/texShared/sheetCsv.d.cts +91 -0
  225. package/texShared/storageLayout.cjs +88 -0
  226. package/texShared/storeKeys.cjs +144 -0
  227. package/texShared/toolArguments.cjs +323 -0
@@ -0,0 +1,232 @@
1
+ /**
2
+ * The block kinds that make a page more than a list (owner, 2026-10-27:
3
+ * "more pictures, clever ways to display information"; drawn and reviewed in
4
+ * the round 2 artboard): the pick with the vote inside it, places as photo
5
+ * spreads with a fit bar and a fact strip, prices on one shared axis, an
6
+ * itinerary of photo stops and walks, budget tiers, and contacts with buttons.
7
+ *
8
+ * The model writes words and rows (`blocks.cjs` says how); the layout is
9
+ * chosen here from the shape of the data: a place with no photo gets its
10
+ * initial, an unknown price a hollow dot and an Ask, seven places or more a
11
+ * shortlist instead of spreads.
12
+ */
13
+
14
+ const { numberIn, fieldOf, seatsIn, UNKNOWN } = require("./blocks.cjs");
15
+ const { esc, SAFE_HREF, runsHtml, part, fieldHtml, plain, setting, itemName, sources, photo, faces, voters, sourceLink, gallery } = require("./html.cjs");
16
+
17
+ /** Fields a block draws in a place of its own; any other field on a place is a fact. */
18
+ const KNOWN = new Set(["photo", "photos", "price", "seats", "votes", "address", "why", "map", "phone", "email", "text", "site", "walk", "state", "status", "source", "sources", "link", "url"]);
19
+
20
+ const photosOf = (item) => [...sources(fieldOf(item, "photos")), ...sources(fieldOf(item, "photo"))];
21
+
22
+ /** The pick in a vote or tiers block: who decided, else the most votes, else the writer's own (the first, or `pick:`). */
23
+ function pickOf(block) {
24
+ const names = block.items.map(itemName);
25
+ const chosen = setting(block, "chosen");
26
+ if (chosen && names.some((name) => name.toLowerCase() === chosen.toLowerCase())) return { name: names.find((name) => name.toLowerCase() === chosen.toLowerCase()), decided: true };
27
+ const counts = block.items.map((item) => voters(fieldOf(item, "votes")).length);
28
+ const most = Math.max(...counts);
29
+ if (most > 0) return { name: names[counts.indexOf(most)], decided: false };
30
+ const pick = setting(block, "pick");
31
+ return { name: names.find((name) => name.toLowerCase() === pick.toLowerCase()) ?? names[0], decided: false };
32
+ }
33
+
34
+ const ICONS = {
35
+ phone: '<path d="M5 4h4l2 5-2.5 1.5a11 11 0 0 0 5 5L15 13l5 2v4a2 2 0 0 1-2 2A16 16 0 0 1 3 6a2 2 0 0 1 2-2"/>',
36
+ email: '<rect x="3" y="5" width="18" height="14" rx="2"/><path d="m3 7 9 6 9-6"/>',
37
+ text: '<path d="M4 5h16v11H9l-5 4z"/>',
38
+ site: '<circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3c3 3.5 3 14.5 0 18M12 3c-3 3.5-3 14.5 0 18"/>',
39
+ };
40
+ const icon = (name) => `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${ICONS[name]}</svg>`;
41
+
42
+ /** A button that opens a phone, mail, text or web address; nothing else is drawn as one. */
43
+ function contactButton(kind, value, name) {
44
+ const raw = value.trim();
45
+ const digits = raw.replace(/[^\d+]/g, "");
46
+ const href =
47
+ kind === "phone" ? `tel:${digits}` : kind === "text" ? `sms:${digits}` : kind === "email" ? `mailto:${raw}` : /^https?:\/\//i.test(raw) ? raw : `https://${raw}`;
48
+ if (!SAFE_HREF.test(href) || ((kind === "phone" || kind === "text") && digits.replace(/\D/g, "").length < 3)) return "";
49
+ const verb = { phone: "Call", email: "Email", text: "Text", site: "Open the site of" }[kind];
50
+ return `<a class="pg-ibtn" href="${esc(href)}" data-href="${esc(href)}" aria-label="${esc(`${verb} ${name}`)}" title="${esc(raw)}">${icon(kind)}</a>`;
51
+ }
52
+
53
+ /** A round step for an axis that ends near `max`: 1, 2 or 5 times a power of ten. */
54
+ function niceStep(max) {
55
+ const raw = max / 3 || 1;
56
+ const power = 10 ** Math.floor(Math.log10(raw));
57
+ return [1, 2, 5, 10].map((m) => m * power).find((step) => step >= raw) ?? raw;
58
+ }
59
+
60
+ /** "$" in "$14.50", "€" in "€9": the sign a total is written with. */
61
+ const currency = (text) => (/[$€£¥₦]/.exec(text) ?? [""])[0];
62
+ const money = (sign, n) => `${sign}${n >= 100 ? Math.round(n).toLocaleString("en-US") : n.toFixed(n % 1 ? 2 : 0)}`;
63
+
64
+ const RICH = {
65
+ vote: (block, ctx) => {
66
+ const { open, me } = ctx;
67
+ const pick = pickOf(block);
68
+ const counted = new Set(block.items.flatMap((item) => voters(fieldOf(item, "votes"))));
69
+ const expected = numberIn(setting(block, "voters"));
70
+ const action = (setting(block, "action") || "Go with {pick}").replace(/\{pick\}/gi, pick.name);
71
+ const mine = (item) => Boolean(me) && voters(fieldOf(item, "votes")).some((name) => name.toLowerCase() === String(me).toLowerCase());
72
+ const options = block.items
73
+ .map((item) => {
74
+ const name = itemName(item);
75
+ const on = block.items.some(mine) ? mine(item) : name === pick.name;
76
+ return (
77
+ `<div class="pg-vopt" role="radio" aria-checked="${on}" tabindex="0" data-vote="${esc(name)}">` +
78
+ photo(photosOf(item)[0], ctx, { name }) +
79
+ `<div>${item.label ? part(item, -1, open, "b") : part(item, 0, open, "b")}${part(item, item.label ? 0 : 1, open, "small")}${sourceLink(item)}</div>` +
80
+ faces(voters(fieldOf(item, "votes"))) +
81
+ `</div>`
82
+ );
83
+ })
84
+ .join("");
85
+ const tally = counted.size > 0 || expected !== null ? `<small>${counted.size}${expected !== null ? ` of ${expected}` : ""} voted</small>` : "";
86
+ return (
87
+ `<div class="pg-verdict"><div class="pg-verdict-say"><div class="pg-k">${pick.decided ? "Decided" : "The pick"}</div>` +
88
+ `<blockquote><span class="pg-verdict-pick">${esc(block.title)}${block.words.length && !/[.!?:]$/.test(block.title) ? "." : ""}</span>${block.words.length ? ` <span data-edit>${runsHtml(block.words, open)}</span>` : ""}</blockquote></div>` +
89
+ `<div class="pg-vote" role="radiogroup" aria-label="${esc(block.title)}" data-block="${block.from}">${options}` +
90
+ `<div class="pg-act"><button type="button" class="pg-btn" data-choose="${esc(pick.name)}" aria-pressed="${pick.decided}">${pick.decided ? "✓ " : ""}${esc(action)}</button>${tally}</div></div></div>`
91
+ );
92
+ },
93
+
94
+ places: (block, ctx) => {
95
+ const { open } = ctx;
96
+ const near = setting(block, "near");
97
+ const need = seatsIn(setting(block, "need"));
98
+ const map = sources(setting(block, "map") ? { value: { text: setting(block, "map") } } : null)[0];
99
+ const mapHtml = map ? `<figure class="pg-map">${photo(map, ctx, { name: block.title || "Map", cls: "pg-map-img" })}</figure>` : "";
100
+ const mapLink = (item) => {
101
+ const query = [itemName(item), plain(item.parts[0].runs), near].filter(Boolean).join(", ");
102
+ const href = `https://maps.apple.com/?q=${encodeURIComponent(query)}`;
103
+ return `<a class="pg-maplink" href="${esc(href)}" data-href="${esc(href)}">Map</a>`;
104
+ };
105
+ const priceHtml = (item, cls = "pg-vprice") => {
106
+ const price = fieldOf(item, "price");
107
+ if (!price) return "";
108
+ return UNKNOWN.test(price.value.text) ? `<span class="${cls} ask">Ask for price</span>` : fieldHtml(price, open, "span", cls);
109
+ };
110
+ if (block.items.length > 6) {
111
+ return (
112
+ mapHtml +
113
+ `<ol class="pg-short">${block.items
114
+ .map(
115
+ (item, i) =>
116
+ `<li><span class="pg-no">${i + 1}</span>${photo(photosOf(item)[0], ctx, { name: itemName(item) })}<div>${part(item, -1, open, "b")}${part(item, 0, open, "small")}</div>${priceHtml(item, "pg-short-price") || mapLink(item)}</li>`,
117
+ )
118
+ .join("")}</ol>`
119
+ );
120
+ }
121
+ const spreads = block.items
122
+ .map((item, i) => {
123
+ const name = itemName(item);
124
+ const bento = gallery(photosOf(item), ctx, { name, no: String(i + 1) });
125
+ const seatsField = fieldOf(item, "seats");
126
+ const seats = seatsIn(seatsField?.value.text);
127
+ let fit = "";
128
+ if (seats !== null && need !== null) {
129
+ const top = Math.max(seats, need) * 1.1;
130
+ fit =
131
+ `<div class="pg-fit${seats < need ? " short" : ""}"><div class="pg-fit-lbl"><span>Seats ${fieldHtml(seatsField, open)}</span><span>you need ${esc(setting(block, "need"))}</span></div>` +
132
+ `<div class="pg-fit-bar"><i style="width:${((seats / top) * 100).toFixed(1)}%"></i><u style="left:${((need / top) * 100).toFixed(1)}%"></u></div></div>`;
133
+ } else if (seatsField) fit = `<div class="pg-fit-lbl"><span>Seats ${fieldHtml(seatsField, open)}</span></div>`;
134
+ const facts = (item.fields ?? []).filter((field) => !KNOWN.has(field.key)).slice(0, 6);
135
+ const factsHtml = facts.length
136
+ ? `<div class="pg-facts">${facts
137
+ .map((field) => {
138
+ const v = field.value.text.trim().toLowerCase();
139
+ const cls = /^(yes|y|✓|true|own|included)$/.test(v) ? "y" : /^(no|n|✕|false|none)$/.test(v) ? "n" : /^(\?|ask|unknown)$/.test(v) ? "q" : "";
140
+ return `<div>${esc(field.name)}${fieldHtml(field, open, "b", cls)}</div>`;
141
+ })
142
+ .join("")}</div>`
143
+ : "";
144
+ return (
145
+ `<article class="pg-venue">${bento}<div class="pg-venue-h"><div>${part(item, -1, open, "h4")}${part(item, 0, open, "span", "pg-where")}${sourceLink(item)}</div>${mapLink(item)}</div>` +
146
+ `${priceHtml(item)}${fit}${factsHtml}${part(item, 1, open, "p", "pg-why")}</article>`
147
+ );
148
+ })
149
+ .join("");
150
+ return `${mapHtml}<div class="pg-venues${block.items.length === 2 ? " two" : ""}">${spreads}</div>`;
151
+ },
152
+
153
+ prices: (block, ctx) => {
154
+ const { open } = ctx;
155
+ const values = block.items.map((item) => (UNKNOWN.test(item.parts[0].text) ? null : numberIn(item.parts[0].text)));
156
+ const known = values.filter((v) => v !== null);
157
+ const step = niceStep(Math.max(...known, 1) * 1.1);
158
+ const top = step * Math.ceil((Math.max(...known, 1) * 1.1) / step);
159
+ const group = numberIn(setting(block, "for"));
160
+ const per = setting(block, "per");
161
+ const pickName = setting(block, "pick").toLowerCase();
162
+ const cheapest = Math.min(...known);
163
+ const sign = currency(block.items.map((item) => item.parts[0].text).join(" "));
164
+ const ticks = [];
165
+ for (let t = step; t <= top + 1e-9; t += step) ticks.push(t);
166
+ const head =
167
+ `<div class="pg-ticks"><span></span><div>${ticks.map((t, i) => `<span>${esc(money(sign, t))}${i === ticks.length - 1 && per ? ` a ${esc(per)}` : ""}</span>`).join("")}</div>` +
168
+ `<span>${group !== null ? `for ${esc(setting(block, "for"))}` : ""}</span></div>`;
169
+ const rows = block.items
170
+ .map((item, i) => {
171
+ const value = values[i];
172
+ const name = itemName(item);
173
+ const pick = pickName ? name.toLowerCase() === pickName : value !== null && value === cheapest;
174
+ const left = value === null ? 100 : Math.min(100, (value / top) * 100);
175
+ const dot = `<span class="pg-dot${value === null ? " hollow" : ""}" style="left:${left.toFixed(1)}%">${part(item, 0, open, "em")}</span>`;
176
+ const total = value === null ? `<span class="pg-tot ask">Ask</span>` : group !== null ? `<span class="pg-tot">${esc(money(sign, value * group))}</span>` : "<span></span>";
177
+ return `<div class="pg-prow${pick ? " pick" : ""}">${photo(photosOf(item)[0], ctx, { name })}<div>${part(item, -1, open, "b")}${part(item, 1, open, "span", "pg-what")}${sourceLink(item)}<div class="pg-scale">${dot}</div></div>${total}</div>`;
178
+ })
179
+ .join("");
180
+ return `<div class="pg-plot">${head}${rows}</div>`;
181
+ },
182
+
183
+ itinerary: (block, ctx) => {
184
+ const { open } = ctx;
185
+ return `<div class="pg-stops">${block.items
186
+ .map((item, i) => {
187
+ const walk = fieldOf(item, "walk");
188
+ const leg = walk && i < block.items.length - 1 ? `<div class="pg-leg"><span>Walk</span>${fieldHtml(walk, open)}</div>` : "";
189
+ return `<div class="pg-stop">${part(item, -1, open, "time", "pg-tm")}${photo(photosOf(item)[0], ctx, { name: plain(item.parts[0].runs) })}<div>${part(item, 0, open, "b")}${part(item, 1, open, "span")}${sourceLink(item)}</div></div>${leg}`;
190
+ })
191
+ .join("")}</div>`;
192
+ },
193
+
194
+ tiers: (block, ctx) => {
195
+ const { open } = ctx;
196
+ const pick = pickOf(block);
197
+ const writer = (setting(block, "pick") || itemName(block.items[0])).toLowerCase();
198
+ return `<div class="pg-tiers" data-block="${block.from}">${block.items
199
+ .map((item) => {
200
+ const name = itemName(item);
201
+ const on = name === pick.name;
202
+ const names = voters(fieldOf(item, "votes"));
203
+ const lines = (item.fields ?? []).filter((field) => !KNOWN.has(field.key));
204
+ const pics = photosOf(item).slice(0, 3);
205
+ return (
206
+ `<div class="pg-tier${on ? " pick" : ""}"><div class="pg-tier-top">${part(item, -1, open, "span", "pg-k")}${name.toLowerCase() === writer ? `<span class="pg-badge">The pick</span>` : ""}</div>` +
207
+ `<div class="pg-pp">${part(item, 0, open, "span")}${part(item, 1, open, "small")}</div>` +
208
+ (pics.length ? `<div class="pg-strip">${pics.map((src) => photo(src, ctx, { name })).join("")}</div>` : "") +
209
+ (lines.length ? `<ul>${lines.map((field) => `<li><span>${esc(field.name)}</span>${fieldHtml(field, open)}</li>`).join("")}</ul>` : "") +
210
+ (names.length ? `<div class="pg-who">${faces(names)}${names.length} picked this</div>` : "") +
211
+ `<button type="button" class="pg-btn${on ? "" : " quiet"}" data-choose="${esc(name)}" aria-pressed="${pick.decided && on}">${pick.decided && on ? "✓ Chosen" : "Go with this one"}</button></div>`
212
+ );
213
+ })
214
+ .join("")}</div>`;
215
+ },
216
+
217
+ contacts: (block, { open }) =>
218
+ `<div class="pg-contacts">${block.items
219
+ .map((item) => {
220
+ const name = itemName(item);
221
+ const buttons = ["phone", "text", "email", "site"]
222
+ .map((kind) => {
223
+ const field = fieldOf(item, kind);
224
+ return field ? contactButton(kind, field.value.text, name) : "";
225
+ })
226
+ .join("");
227
+ return `<div class="pg-contact"><div>${part(item, -1, open, "b")}${part(item, 0, open, "small")}${part(item, 1, open, "small")}</div><div class="pg-ib">${buttons}</div></div>`;
228
+ })
229
+ .join("")}</div>`,
230
+ };
231
+
232
+ module.exports = { RICH, pickOf, photosOf };
@@ -0,0 +1,168 @@
1
+ /**
2
+ * The small pieces every page drawing is made of: escaping, a run of words
3
+ * with its source map, a block item's part, a photo slot, a row of faces.
4
+ *
5
+ * Shared by `render.cjs` (the page and its nodes), `draw.cjs` and
6
+ * `drawRich.cjs` (the blocks) and `cover.cjs` (the first screen), so the one
7
+ * rule holds in all of them: nothing from the note reaches the markup except
8
+ * as escaped text, a number computed here, or a class name chosen here.
9
+ */
10
+
11
+ const { runsText } = require("./inline.cjs");
12
+
13
+ const ENTITIES = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" };
14
+ const esc = (value) => String(value ?? "").replace(/[&<>"']/g, (c) => ENTITIES[c]);
15
+
16
+ /** Only these link targets are drawn as links; the runtime asks the app before opening any. */
17
+ const SAFE_HREF = /^(https?:\/\/|mailto:|tel:|sms:)[^\s"'<>]*$/i;
18
+
19
+ /**
20
+ * A picture the page names (`photo: stand.jpg`): a workspace file the app
21
+ * loads for the frame, or one a cover was handed as bytes. Never a script, a
22
+ * style or anything with a scheme other than the web's.
23
+ */
24
+ const SAFE_SRC = /^(?!\s)(?!(?:javascript|data|vbscript|file):)[^"'<>\s][^"'<>]{0,299}$/i;
25
+
26
+ /** A written-out address as a reader wants to see it: the site and the start of its path, "redeemerbk.com/who-we-are". */
27
+ function shortAddress(href) {
28
+ const bare = String(href).replace(/^https?:\/\/(?:www\.)?/i, "").replace(/[?#].*$/, "").replace(/\/$/, "");
29
+ return bare.length > 42 ? `${bare.slice(0, 40)}…` : bare;
30
+ }
31
+
32
+ /** Runs as HTML. `open` is the set of comment threads still open, whose words are highlighted. */
33
+ function runsHtml(runs, open) {
34
+ let out = "";
35
+ for (const run of runs) {
36
+ if (run.image) {
37
+ out += `<img class="pg-img" data-src="${esc(run.image.src)}" alt="${esc(run.image.alt)}">`;
38
+ continue;
39
+ }
40
+ if (run.text === "") continue;
41
+ const anchors = (run.anchors ?? []).filter((id) => open.has(id));
42
+ const attrs = run.editable === false ? "" : ` data-f="${run.from}" data-t="${run.to}"`;
43
+ let html = `<span class="r${anchors.length ? " pg-c" : ""}"${attrs}${anchors.length ? ` data-a="${esc(anchors.join(" "))}"` : ""}>${esc(run.text)}</span>`;
44
+ if (run.code) html = `<code>${html}</code>`;
45
+ if (run.strike) html = `<s>${html}</s>`;
46
+ if (run.em) html = `<em>${html}</em>`;
47
+ if (run.strong) html = `<strong>${html}</strong>`;
48
+ if (run.note) html = `<a class="pg-note" href="#" data-note="${esc(run.note)}">${html}</a>`;
49
+ else if (run.bare && SAFE_HREF.test(run.href)) html = `<a class="pg-out" href="${esc(run.href)}" data-href="${esc(run.href)}" title="${esc(run.href)}">${esc(shortAddress(run.href))} ↗</a>`;
50
+ else if (run.href) html = SAFE_HREF.test(run.href) ? `<a href="${esc(run.href)}" data-href="${esc(run.href)}">${html}</a>` : html;
51
+ out += html;
52
+ }
53
+ return out;
54
+ }
55
+
56
+ const plain = (runs) => runsText(runs ?? []).trim();
57
+
58
+ /** One part of a block item (`-1` is its label): its words, editable in place. */
59
+ function part(item, index, open, tag = "span", cls = "") {
60
+ const p = index === -1 ? item.label : item.parts[index];
61
+ if (!p || p.text === "") return "";
62
+ return `<${tag} class="${cls}" data-edit>${runsHtml(p.runs, open)}</${tag}>`;
63
+ }
64
+
65
+ /** A field's words, editable in place, or "" when the item has none of those names. */
66
+ function fieldHtml(field, open, tag = "span", cls = "") {
67
+ if (!field) return "";
68
+ return `<${tag} class="${cls}" data-edit>${runsHtml(field.value.runs, open)}</${tag}>`;
69
+ }
70
+
71
+ const setting = (block, key) => (block.settings[key] ? block.settings[key].value.trim() : "");
72
+
73
+ /** The name an item is known by: its label, or its first part. */
74
+ const itemName = (item) => plain(item.label ? item.label.runs : item.parts[0].runs);
75
+
76
+ /** The pictures a field names, split at commas: `photos: a.jpg, b.jpg`. */
77
+ function sources(field) {
78
+ if (!field) return [];
79
+ return field.value.text
80
+ .split(",")
81
+ .map((name) => name.trim().replace(/^<|>$/g, ""))
82
+ .filter((name) => SAFE_SRC.test(name))
83
+ .slice(0, 9);
84
+ }
85
+
86
+ /**
87
+ * A photo slot. With a source, an `<img>` the runtime fills (`data-src`), or,
88
+ * on a cover, the bytes it was handed (`images`); without, the first letter of
89
+ * what it shows on a tint, so a place with no photo still has a face.
90
+ */
91
+ function photo(src, ctx, { name = "", cls = "", label = "" } = {}) {
92
+ const initial = esc((name.match(/[A-Za-z0-9]/) ?? [""])[0].toUpperCase());
93
+ const ready = src && ctx.images && ctx.images.get(src);
94
+ const img = !src ? "" : ready ? `<img src="${esc(ready)}" alt="${esc(name)}">` : `<img data-src="${esc(src)}" alt="${esc(name)}">`;
95
+ return `<div class="pg-ph ${cls}" data-i="${initial}">${img}${label ? `<span class="pg-ph-label">${esc(label)}</span>` : ""}</div>`;
96
+ }
97
+
98
+ /**
99
+ * Tex's drawing of a page (`cover.cjs`): the light picture, and the dark one
100
+ * when there is one, each shown on its own page by the page's tokens
101
+ * (`--pg-ink-light`, `--pg-ink-dark`, `css.cjs`), so the frame needs no
102
+ * script to switch them. Both are pictures of the note, read like a photo.
103
+ */
104
+ function drawing(light, dark, ctx, { name = "" } = {}) {
105
+ const one = (src, cls) => {
106
+ const ready = ctx.images && ctx.images.get(src);
107
+ return ready ? `<img class="${cls}" src="${esc(ready)}" alt="${esc(name)}">` : `<img class="${cls}" data-src="${esc(src)}" alt="${esc(name)}">`;
108
+ };
109
+ return `<div class="pg-ph pg-drawing">${one(light, dark ? "pg-ink-light" : "")}${dark ? one(dark, "pg-ink-dark") : ""}</div>`;
110
+ }
111
+
112
+ /**
113
+ * Where an option's facts came from: its `source:` (or `sources:`, `link:`,
114
+ * `url:`, `site:`) as a link out naming the site ("tagvenue.com ↗"), or "".
115
+ * Only a web address is ever drawn as one (owner, 2026-10-28: "there should
116
+ * be a link out to the website sources where we got the info").
117
+ */
118
+ const SOURCE_KEYS = ["source", "sources", "link", "url", "site"];
119
+ function sourceLink(item) {
120
+ const field = (item.fields ?? []).find((f) => SOURCE_KEYS.includes(f.key));
121
+ const raw = field ? field.value.text.split(/[\s,]+/).find((word) => word !== "") ?? "" : "";
122
+ const href = /^https?:\/\//i.test(raw) ? raw : /^[a-z0-9-]+(\.[a-z0-9-]+)+(\/\S*)?$/i.test(raw) ? `https://${raw}` : "";
123
+ if (!href || !SAFE_HREF.test(href)) return "";
124
+ const host = (/^https?:\/\/(?:www\.)?([^/?#:]+)/i.exec(href) ?? ["", "source"])[1].toLowerCase();
125
+ return `<a class="pg-src" href="${esc(href)}" data-href="${esc(href)}" title="${esc(href)}">${esc(host)} ↗</a>`;
126
+ }
127
+
128
+ /**
129
+ * Photos to swipe through: every one an option names, side by side, one
130
+ * slide wide with the next peeking in, a count and dots under them (the
131
+ * runtime moves the dots, `apps/mobile/page-frame/entry.js`). Owner,
132
+ * 2026-10-28: "show more images of the different options, and have a
133
+ * swipable carousel go through". `no` is the option's number, drawn over it.
134
+ */
135
+ function gallery(pics, ctx, { name = "", no = "" } = {}) {
136
+ const shown = pics.length ? pics : [null];
137
+ const badge = no ? `<span class="pg-no">${esc(no)}</span>` : "";
138
+ const dots = shown.length > 1 ? `<div class="pg-gal-dots" aria-hidden="true">${shown.map((_, k) => `<i${k === 0 ? ' class="on"' : ""}></i>`).join("")}</div>` : "";
139
+ return (
140
+ `<div class="pg-gal n${Math.min(shown.length, 2)}">${badge}<div class="pg-gal-track" role="group" aria-label="${esc(`Photos of ${name}`)}">` +
141
+ shown.map((src, k) => photo(src, ctx, { name, label: shown.length > 1 && k === 0 ? `${shown.length} photos` : "" })).join("") +
142
+ `</div>${dots}</div>`
143
+ );
144
+ }
145
+
146
+ /** People as overlapping initials, each in one of six colors picked by their name. */
147
+ function faces(names, cls = "") {
148
+ if (names.length === 0) return "";
149
+ const hue = (name) => [...name].reduce((sum, ch) => (sum * 31 + ch.charCodeAt(0)) >>> 0, 7) % 6;
150
+ const initials = (name) =>
151
+ /^[A-Za-z]{1,3}$/.test(name)
152
+ ? name.toUpperCase()
153
+ : name
154
+ .split(/\s+/)
155
+ .filter(Boolean)
156
+ .slice(0, 2)
157
+ .map((word) => word[0].toUpperCase())
158
+ .join("");
159
+ return `<span class="pg-faces ${cls}">${names
160
+ .slice(0, 6)
161
+ .map((name) => `<i class="f${hue(name)}" title="${esc(name)}">${esc(initials(name))}</i>`)
162
+ .join("")}${names.length > 6 ? `<i class="more">+${names.length - 6}</i>` : ""}</span>`;
163
+ }
164
+
165
+ /** The names in a `votes:` field. */
166
+ const voters = (field) => (field ? field.value.text.split(",").map((name) => name.trim()).filter((name) => name && !/^(none|-)$/i.test(name)).slice(0, 40) : []);
167
+
168
+ module.exports = { esc, SAFE_HREF, SAFE_SRC, runsHtml, plain, part, fieldHtml, setting, itemName, sources, photo, faces, voters, sourceLink, gallery, drawing };
@@ -0,0 +1,251 @@
1
+ /**
2
+ * The words of a page, cut into runs that each know where they came from.
3
+ *
4
+ * A page is drawn from a Markdown note, and every word on it has to stay a
5
+ * word in that note: typing over it on the page, or commenting on it, changes
6
+ * the Markdown and nothing else (see `docs/decisions/app-and-console/pages.md`).
7
+ * So the inline parser here keeps, for every run of plain text it finds, the
8
+ * stretch of the source it was read from, `[from, to)`. An edit to a run is a
9
+ * replacement of exactly that stretch, written back escaped (`escapeText`), and
10
+ * a comment on a run is an anchor around exactly those characters.
11
+ *
12
+ * What it reads is the common, unambiguous part of Markdown that notes use:
13
+ * `**strong**`, `*em*` / `_em_`, `~~struck~~`, `` `code` ``, `[words](url)`,
14
+ * `[[a note]]`, `![alt](src)` / `![[picture.png]]`, a bare `https://` address,
15
+ * backslash escapes, and the
16
+ * comment anchors `<!--c:id-->…<!--/c:id-->`, which are zero-width here and
17
+ * mark the runs between them as commented. Any other HTML comment is hidden.
18
+ * Anything it does not read stays as the text it is, so nothing is lost.
19
+ *
20
+ * Code spans, link targets and wiki links are drawn but not editable: their
21
+ * characters are not prose, and an edit that escaped them would change what
22
+ * they point at.
23
+ */
24
+
25
+ const ESCAPABLE = "\\`*_{}[]()#+-.!|~<>";
26
+
27
+ /** Characters escaped when typed words are written back, so they stay words. */
28
+ const WRITE_ESCAPES = /[\\`*_[\]<>|~]/g;
29
+
30
+ /** A comment anchor marker; same shape as `comments.cjs`'s, matched here at a position. */
31
+ const MARKER = /^<!--(\/?)c:([A-Za-z0-9_-]{1,40})-->/;
32
+ const HTML_COMMENT = /^<!--[\s\S]*?-->/;
33
+ const CODE_SPAN = /^(`+)([\s\S]*?[^`])\1(?!`)/;
34
+ const WIKI = /^(!?)\[\[([^\]\n|]{1,300})(?:\|([^\]\n]{1,300}))?\]\]/;
35
+ /** A web address written out in the words, up to a space or a bracket. */
36
+ const BARE_URL = /^https?:\/\/[^\s<>()[\]"']{3,500}/i;
37
+
38
+ /**
39
+ * The runs of the source between `from` and `to`.
40
+ *
41
+ * Each run is `{ text, from, to, editable, strong, em, strike, code, href,
42
+ * note, anchors }`, or an image `{ image: { src, alt }, from, to }`.
43
+ * `anchors` lists the ids of the comment threads whose words include the run.
44
+ */
45
+ function inlineRuns(source, from = 0, to = source.length) {
46
+ const runs = [];
47
+ const open = new Set(); // comment ids currently open
48
+ const marks = { strong: false, em: false, strike: false };
49
+ let i = from;
50
+ let text = "";
51
+ let textFrom = from;
52
+
53
+ const flush = (end) => {
54
+ if (text !== "") {
55
+ runs.push({
56
+ text,
57
+ from: textFrom,
58
+ to: end,
59
+ editable: true,
60
+ strong: marks.strong,
61
+ em: marks.em,
62
+ strike: marks.strike,
63
+ anchors: [...open],
64
+ });
65
+ }
66
+ text = "";
67
+ textFrom = end;
68
+ };
69
+ const push = (run, end) => {
70
+ flush(i);
71
+ runs.push({ strong: marks.strong, em: marks.em, strike: marks.strike, anchors: [...open], ...run });
72
+ i = end;
73
+ textFrom = end;
74
+ };
75
+
76
+ while (i < to) {
77
+ const c = source[i];
78
+ const rest = () => source.slice(i, to);
79
+
80
+ if (c === "\\" && i + 1 < to && ESCAPABLE.includes(source[i + 1])) {
81
+ if (text === "") textFrom = i;
82
+ text += source[i + 1];
83
+ i += 2;
84
+ continue;
85
+ }
86
+ if (c === "<" && source.startsWith("<!--", i)) {
87
+ const marker = MARKER.exec(rest());
88
+ if (marker) {
89
+ flush(i);
90
+ if (marker[1] === "/") open.delete(marker[2]);
91
+ else open.add(marker[2]);
92
+ i += marker[0].length;
93
+ textFrom = i;
94
+ continue;
95
+ }
96
+ const hidden = HTML_COMMENT.exec(rest());
97
+ if (hidden) {
98
+ flush(i);
99
+ i += hidden[0].length;
100
+ textFrom = i;
101
+ continue;
102
+ }
103
+ }
104
+ if (c === "`") {
105
+ const code = CODE_SPAN.exec(rest());
106
+ if (code) {
107
+ push({ text: code[2].replace(/^ (.*) $/s, "$1"), from: i, to: i + code[0].length, editable: false, code: true }, i + code[0].length);
108
+ continue;
109
+ }
110
+ }
111
+ if (c === "[" || (c === "!" && source[i + 1] === "[")) {
112
+ const wiki = WIKI.exec(rest());
113
+ if (wiki) {
114
+ const end = i + wiki[0].length;
115
+ if (wiki[1] === "!") push({ image: { src: wiki[2].trim(), alt: (wiki[3] ?? "").trim() }, from: i, to: end }, end);
116
+ else push({ text: (wiki[3] ?? wiki[2]).trim(), from: i, to: end, editable: false, note: wiki[2].trim() }, end);
117
+ continue;
118
+ }
119
+ const link = linkAt(source, c === "!" ? i + 1 : i, to);
120
+ if (link) {
121
+ if (c === "!") {
122
+ push({ image: { src: link.href, alt: source.slice(link.textFrom, link.textTo) }, from: i, to: link.end }, link.end);
123
+ continue;
124
+ }
125
+ flush(i);
126
+ const inner = inlineRuns(source, link.textFrom, link.textTo);
127
+ for (const run of inner) {
128
+ if (run.image) runs.push(run);
129
+ else
130
+ runs.push({
131
+ ...run,
132
+ strong: run.strong || marks.strong,
133
+ em: run.em || marks.em,
134
+ strike: run.strike || marks.strike,
135
+ anchors: [...new Set([...open, ...run.anchors])],
136
+ href: link.href,
137
+ });
138
+ }
139
+ i = link.end;
140
+ textFrom = i;
141
+ continue;
142
+ }
143
+ }
144
+ if (c === "*" || c === "_" || c === "~") {
145
+ const toggled = toggleAt(source, i, to, marks);
146
+ if (toggled) {
147
+ flush(i);
148
+ marks[toggled.mark] = !marks[toggled.mark];
149
+ i += toggled.width;
150
+ textFrom = i;
151
+ continue;
152
+ }
153
+ }
154
+ // A bare web address is a link too (owner, 2026-11-10: "no ability to click on a link to learn more"), drawn by its site's name.
155
+ if ((c === "h" || c === "H") && (i === from || /[\s(]/.test(source[i - 1]))) {
156
+ const bare = BARE_URL.exec(source.slice(i, to));
157
+ if (bare) {
158
+ const url = bare[0].replace(/[.,;:!?'"]+$/, "");
159
+ push({ text: url, from: i, to: i + url.length, editable: false, href: url, bare: true }, i + url.length);
160
+ continue;
161
+ }
162
+ }
163
+ if (text === "") textFrom = i;
164
+ text += c === "\n" ? " " : c;
165
+ i += 1;
166
+ }
167
+ flush(to);
168
+ return runs;
169
+ }
170
+
171
+ /** `[words](target)` starting at `at`, or null. Targets with spaces or a title are not read. */
172
+ function linkAt(source, at, to) {
173
+ if (source[at] !== "[") return null;
174
+ let depth = 0;
175
+ let j = at;
176
+ for (; j < to; j++) {
177
+ const ch = source[j];
178
+ if (ch === "\\") {
179
+ j++;
180
+ continue;
181
+ }
182
+ if (ch === "\n" && source[j + 1] === "\n") return null;
183
+ if (ch === "[") depth++;
184
+ if (ch === "]" && --depth === 0) break;
185
+ }
186
+ if (j >= to || source[j + 1] !== "(") return null;
187
+ const close = source.indexOf(")", j + 2);
188
+ if (close === -1 || close >= to) return null;
189
+ const href = source.slice(j + 2, close).trim();
190
+ if (href === "" || /\s/.test(href)) return null;
191
+ return { textFrom: at + 1, textTo: j, href, end: close + 1 };
192
+ }
193
+
194
+ /**
195
+ * Whether the emphasis marker at `i` opens or closes a mark, and which.
196
+ *
197
+ * Opening needs a closer later in the same stretch, so a lone `*` (a price
198
+ * footnote, a multiplication) stays a character. `_` only counts at a word's
199
+ * edge, so `snake_case_names` stay whole.
200
+ */
201
+ function toggleAt(source, i, to, marks) {
202
+ const two = source.slice(i, i + 2);
203
+ let mark;
204
+ let width;
205
+ if (two === "**" || two === "__") [mark, width] = ["strong", 2];
206
+ else if (two === "~~") [mark, width] = ["strike", 2];
207
+ else if (source[i] === "*" || source[i] === "_") [mark, width] = ["em", 1];
208
+ else return null;
209
+ const token = source.slice(i, i + width);
210
+ const before = source[i - 1] ?? " ";
211
+ const after = source[i + width] ?? " ";
212
+ if (token[0] === "_" && /[A-Za-z0-9]/.test(marks[mark] ? after : before)) return null;
213
+ if (marks[mark]) return /\s/.test(before) ? null : { mark, width };
214
+ if (/\s/.test(after)) return null;
215
+ for (let k = source.indexOf(token, i + width + 1); k !== -1 && k < to; k = source.indexOf(token, k + 1)) {
216
+ if (/\s/.test(source[k - 1])) continue;
217
+ // A single `*` that is half of a `**` closes nothing.
218
+ if (width === 1 && (source[k + 1] === token || source[k - 1] === token)) continue;
219
+ return { mark, width };
220
+ }
221
+ return null;
222
+ }
223
+
224
+ /** Typed words as Markdown that reads back as exactly those words: one line, punctuation escaped. */
225
+ function escapeText(text) {
226
+ return String(text)
227
+ .replace(/[\r\n]+/g, " ")
228
+ .replace(WRITE_ESCAPES, (ch) => `\\${ch}`);
229
+ }
230
+
231
+ /**
232
+ * Where the `offset`-th character a reader sees in a run sits in the source.
233
+ * A run's words differ from its source only by backslash escapes, each one
234
+ * character drawn from two.
235
+ */
236
+ function sourceOffset(source, from, to, offset) {
237
+ let seen = 0;
238
+ let i = from;
239
+ while (i < to && seen < offset) {
240
+ i += source[i] === "\\" && i + 1 < to && ESCAPABLE.includes(source[i + 1]) ? 2 : 1;
241
+ seen++;
242
+ }
243
+ return i;
244
+ }
245
+
246
+ /** The plain words of some runs, as a reader sees them. */
247
+ function runsText(runs) {
248
+ return runs.map((run) => (run.image ? run.image.alt : run.text)).join("");
249
+ }
250
+
251
+ module.exports = { inlineRuns, escapeText, runsText, sourceOffset };