@bigmistqke/workpad 0.0.0-stage → 0.18.1

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 (277) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +781 -2
  3. package/bin/workpad.ts +1526 -0
  4. package/dist/_virtual/_@oxc-project_runtime@0.156.0/helpers/esm/taggedTemplateLiteral.js +5 -0
  5. package/dist/bin/workpad.js +1202 -0
  6. package/dist/client/runtime.js +1194 -0
  7. package/dist/define.js +27 -0
  8. package/dist/plugins/alert/README.md +18 -0
  9. package/dist/plugins/alert/index.js +40 -0
  10. package/dist/plugins/alert/public/style.css +40 -0
  11. package/dist/plugins/ansi/README.md +36 -0
  12. package/dist/plugins/ansi/index.js +63 -0
  13. package/dist/plugins/ansi/public/style.css +28 -0
  14. package/dist/plugins/badge/README.md +32 -0
  15. package/dist/plugins/badge/index.js +28 -0
  16. package/dist/plugins/badge/public/style.css +30 -0
  17. package/dist/plugins/chat/README.md +81 -0
  18. package/dist/plugins/chat/index.js +96 -0
  19. package/dist/plugins/chat/public/client.js +3 -0
  20. package/dist/plugins/chat/public/style.css +143 -0
  21. package/dist/plugins/claude/README.md +116 -0
  22. package/dist/plugins/claude/channel.js +130 -0
  23. package/dist/plugins/claude/doctor.js +316 -0
  24. package/dist/plugins/claude/index.js +199 -0
  25. package/dist/plugins/claude/session.js +68 -0
  26. package/dist/plugins/code/README.md +54 -0
  27. package/dist/plugins/code/diff.js +75 -0
  28. package/dist/plugins/code/index.js +105 -0
  29. package/dist/plugins/code/public/client.js +1 -0
  30. package/dist/plugins/code/public/style.css +99 -0
  31. package/dist/plugins/comments/README.md +30 -0
  32. package/dist/plugins/comments/index.js +39 -0
  33. package/dist/plugins/comments/public/client.js +24 -0
  34. package/dist/plugins/comments/public/style.css +224 -0
  35. package/dist/plugins/details/README.md +24 -0
  36. package/dist/plugins/details/index.js +28 -0
  37. package/dist/plugins/details/public/style.css +7 -0
  38. package/dist/plugins/draft/README.md +14 -0
  39. package/dist/plugins/draft/index.js +27 -0
  40. package/dist/plugins/draft/public/style.css +21 -0
  41. package/dist/plugins/forge/README.md +22 -0
  42. package/dist/plugins/forge/index.js +83 -0
  43. package/dist/plugins/form/README.md +126 -0
  44. package/dist/plugins/form/index.js +179 -0
  45. package/dist/plugins/form/public/style.css +172 -0
  46. package/dist/plugins/grid/README.md +45 -0
  47. package/dist/plugins/grid/index.js +35 -0
  48. package/dist/plugins/grid/public/style.css +98 -0
  49. package/dist/plugins/iframe/README.md +18 -0
  50. package/dist/plugins/iframe/index.js +49 -0
  51. package/dist/plugins/iframe/public/style.css +28 -0
  52. package/dist/plugins/index.js +44 -0
  53. package/dist/plugins/lightbox/README.md +24 -0
  54. package/dist/plugins/lightbox/index.js +20 -0
  55. package/dist/plugins/lightbox/public/client.js +4 -0
  56. package/dist/plugins/lightbox/public/style.css +66 -0
  57. package/dist/plugins/mermaid/README.md +21 -0
  58. package/dist/plugins/mermaid/index.js +42 -0
  59. package/dist/plugins/mermaid/public/style.css +21 -0
  60. package/dist/plugins/opencode/README.md +48 -0
  61. package/dist/plugins/opencode/channel.js +92 -0
  62. package/dist/plugins/opencode/index.js +64 -0
  63. package/dist/plugins/opencode/shim.js +150 -0
  64. package/dist/plugins/quiet/README.md +26 -0
  65. package/dist/plugins/quiet/index.js +23 -0
  66. package/dist/plugins/tabs/README.md +44 -0
  67. package/dist/plugins/tabs/index.js +75 -0
  68. package/dist/plugins/tabs/public/client.js +1 -0
  69. package/dist/plugins/tabs/public/style.css +98 -0
  70. package/dist/plugins/terminal/README.md +63 -0
  71. package/dist/plugins/terminal/host.js +338 -0
  72. package/dist/plugins/terminal/index.js +170 -0
  73. package/dist/plugins/terminal/modes.js +32 -0
  74. package/dist/plugins/terminal/public/client.js +41 -0
  75. package/dist/plugins/terminal/public/style.css +511 -0
  76. package/dist/plugins/terminal/server.js +256 -0
  77. package/dist/plugins/terminal/sizes.js +58 -0
  78. package/dist/plugins/timeline/README.md +48 -0
  79. package/dist/plugins/timeline/index.js +83 -0
  80. package/dist/plugins/timeline/public/style.css +138 -0
  81. package/dist/plugins/toc/README.md +40 -0
  82. package/dist/plugins/toc/index.js +29 -0
  83. package/dist/plugins/toc/public/client.js +1 -0
  84. package/dist/plugins/toc/public/style.css +117 -0
  85. package/dist/plugins/window/README.md +51 -0
  86. package/dist/plugins/window/index.js +91 -0
  87. package/dist/solid/index.js +41 -0
  88. package/dist/src/agents.js +81 -0
  89. package/dist/src/anchors.js +52 -0
  90. package/dist/src/api.js +282 -0
  91. package/dist/src/archive.js +49 -0
  92. package/dist/src/auth.js +67 -0
  93. package/dist/src/build.js +159 -0
  94. package/dist/src/client/page/base.css +1762 -0
  95. package/dist/src/client/page/main.js +2121 -0
  96. package/dist/src/config.js +76 -0
  97. package/dist/src/document.js +93 -0
  98. package/dist/src/entries.js +264 -0
  99. package/dist/src/events.js +322 -0
  100. package/dist/src/files.js +47 -0
  101. package/dist/src/formstate.js +65 -0
  102. package/dist/src/help.js +213 -0
  103. package/dist/src/html.js +34 -0
  104. package/dist/src/hub.js +348 -0
  105. package/dist/src/icons.js +6 -0
  106. package/dist/src/listen.js +132 -0
  107. package/dist/src/listeners.js +64 -0
  108. package/dist/src/load.js +81 -0
  109. package/dist/src/loader.js +179 -0
  110. package/dist/src/migrate.js +314 -0
  111. package/dist/src/package.js +52 -0
  112. package/dist/src/pages/blocks.js +67 -0
  113. package/dist/src/pages/board.js +59 -0
  114. package/dist/src/pages/index.js +27 -0
  115. package/dist/src/pages/markdown.js +863 -0
  116. package/dist/src/pages/render.js +761 -0
  117. package/dist/src/pages/window.js +29 -0
  118. package/dist/src/plugins.js +283 -0
  119. package/dist/src/public.js +24 -0
  120. package/dist/src/rename.js +130 -0
  121. package/dist/src/running.js +146 -0
  122. package/dist/src/serve.js +188 -0
  123. package/dist/src/server.js +1105 -0
  124. package/dist/src/site.js +179 -0
  125. package/dist/src/state.js +155 -0
  126. package/dist/src/status.js +323 -0
  127. package/dist/src/thread.js +68 -0
  128. package/dist/src/watchdog.js +38 -0
  129. package/dist/src/ws.js +128 -0
  130. package/package.json +154 -4
  131. package/plugins/README.md +304 -0
  132. package/plugins/alert/README.md +18 -0
  133. package/plugins/alert/index.ts +50 -0
  134. package/plugins/alert/public/style.css +40 -0
  135. package/plugins/ansi/README.md +36 -0
  136. package/plugins/ansi/index.ts +95 -0
  137. package/plugins/ansi/public/style.css +28 -0
  138. package/plugins/badge/README.md +32 -0
  139. package/plugins/badge/index.ts +36 -0
  140. package/plugins/badge/public/style.css +30 -0
  141. package/plugins/chat/README.md +81 -0
  142. package/plugins/chat/autosize.ts +139 -0
  143. package/plugins/chat/client.tsx +187 -0
  144. package/plugins/chat/index.ts +146 -0
  145. package/plugins/chat/public/style.css +143 -0
  146. package/plugins/claude/README.md +116 -0
  147. package/plugins/claude/channel.ts +136 -0
  148. package/plugins/claude/doctor.ts +274 -0
  149. package/plugins/claude/index.ts +248 -0
  150. package/plugins/claude/session.ts +70 -0
  151. package/plugins/code/README.md +54 -0
  152. package/plugins/code/client.ts +73 -0
  153. package/plugins/code/diff.ts +96 -0
  154. package/plugins/code/index.ts +136 -0
  155. package/plugins/code/public/style.css +99 -0
  156. package/plugins/comments/README.md +30 -0
  157. package/plugins/comments/client.ts +723 -0
  158. package/plugins/comments/index.ts +48 -0
  159. package/plugins/comments/public/style.css +224 -0
  160. package/plugins/details/README.md +24 -0
  161. package/plugins/details/index.ts +30 -0
  162. package/plugins/details/public/style.css +7 -0
  163. package/plugins/draft/README.md +14 -0
  164. package/plugins/draft/index.ts +23 -0
  165. package/plugins/draft/public/style.css +21 -0
  166. package/plugins/forge/README.md +22 -0
  167. package/plugins/forge/index.ts +84 -0
  168. package/plugins/form/README.md +126 -0
  169. package/plugins/form/index.ts +199 -0
  170. package/plugins/form/public/style.css +172 -0
  171. package/plugins/grid/README.md +45 -0
  172. package/plugins/grid/index.ts +41 -0
  173. package/plugins/grid/public/style.css +98 -0
  174. package/plugins/iframe/README.md +18 -0
  175. package/plugins/iframe/index.ts +53 -0
  176. package/plugins/iframe/public/style.css +28 -0
  177. package/plugins/index.ts +49 -0
  178. package/plugins/lightbox/README.md +24 -0
  179. package/plugins/lightbox/client.ts +109 -0
  180. package/plugins/lightbox/index.ts +25 -0
  181. package/plugins/lightbox/public/style.css +66 -0
  182. package/plugins/mermaid/README.md +21 -0
  183. package/plugins/mermaid/index.ts +46 -0
  184. package/plugins/mermaid/public/style.css +21 -0
  185. package/plugins/opencode/README.md +48 -0
  186. package/plugins/opencode/channel.ts +112 -0
  187. package/plugins/opencode/index.ts +91 -0
  188. package/plugins/opencode/shim.ts +166 -0
  189. package/plugins/quiet/README.md +26 -0
  190. package/plugins/quiet/index.ts +28 -0
  191. package/plugins/tabs/README.md +44 -0
  192. package/plugins/tabs/client.ts +96 -0
  193. package/plugins/tabs/index.ts +103 -0
  194. package/plugins/tabs/public/style.css +98 -0
  195. package/plugins/terminal/README.md +63 -0
  196. package/plugins/terminal/client.ts +391 -0
  197. package/plugins/terminal/host.ts +434 -0
  198. package/plugins/terminal/index.ts +199 -0
  199. package/plugins/terminal/modes.ts +30 -0
  200. package/plugins/terminal/public/style.css +225 -0
  201. package/plugins/terminal/server.ts +266 -0
  202. package/plugins/terminal/sizes.ts +72 -0
  203. package/plugins/timeline/README.md +48 -0
  204. package/plugins/timeline/index.ts +82 -0
  205. package/plugins/timeline/public/style.css +138 -0
  206. package/plugins/toc/README.md +40 -0
  207. package/plugins/toc/client.ts +236 -0
  208. package/plugins/toc/index.ts +55 -0
  209. package/plugins/toc/public/style.css +117 -0
  210. package/plugins/window/README.md +51 -0
  211. package/plugins/window/index.ts +92 -0
  212. package/skills/workpad/SKILL.md +592 -0
  213. package/solid/index.tsx +80 -0
  214. package/src/agents.ts +134 -0
  215. package/src/anchors.ts +85 -0
  216. package/src/api.ts +444 -0
  217. package/src/archive.ts +75 -0
  218. package/src/auth.ts +99 -0
  219. package/src/build.ts +213 -0
  220. package/src/client/base.ts +19 -0
  221. package/src/client/forms.ts +420 -0
  222. package/src/client/markdown.ts +147 -0
  223. package/src/client/page/base.css +1762 -0
  224. package/src/client/page/board.ts +166 -0
  225. package/src/client/page/elsewhere.ts +153 -0
  226. package/src/client/page/fresh.ts +343 -0
  227. package/src/client/page/heading-link.ts +32 -0
  228. package/src/client/page/live.ts +134 -0
  229. package/src/client/page/main.ts +398 -0
  230. package/src/client/page/orphans.ts +64 -0
  231. package/src/client/page/place.ts +260 -0
  232. package/src/client/page/sort.ts +49 -0
  233. package/src/client/page/sticky.ts +58 -0
  234. package/src/client/page/theme.ts +36 -0
  235. package/src/client/page/view.ts +9 -0
  236. package/src/client/page/waiting.ts +278 -0
  237. package/src/client/page/window.ts +40 -0
  238. package/src/client/reactive.ts +19 -0
  239. package/src/client/read.ts +111 -0
  240. package/src/client/runtime.ts +499 -0
  241. package/src/client/scroll.ts +90 -0
  242. package/src/client/toast.ts +99 -0
  243. package/src/config.ts +111 -0
  244. package/src/define.ts +997 -0
  245. package/src/document.ts +191 -0
  246. package/src/entries.ts +352 -0
  247. package/src/events.ts +463 -0
  248. package/src/files.ts +74 -0
  249. package/src/formstate.ts +72 -0
  250. package/src/help.ts +240 -0
  251. package/src/html.ts +44 -0
  252. package/src/hub.ts +435 -0
  253. package/src/icons.ts +18 -0
  254. package/src/listen.ts +171 -0
  255. package/src/listeners.ts +89 -0
  256. package/src/load.ts +113 -0
  257. package/src/loader.ts +227 -0
  258. package/src/migrate.ts +352 -0
  259. package/src/package.ts +62 -0
  260. package/src/pages/blocks.ts +106 -0
  261. package/src/pages/board.ts +89 -0
  262. package/src/pages/index.ts +79 -0
  263. package/src/pages/markdown.ts +976 -0
  264. package/src/pages/render.ts +845 -0
  265. package/src/pages/window.ts +69 -0
  266. package/src/plugins.ts +319 -0
  267. package/src/public.ts +39 -0
  268. package/src/rename.ts +147 -0
  269. package/src/running.ts +171 -0
  270. package/src/serve.ts +221 -0
  271. package/src/server.ts +1385 -0
  272. package/src/site.ts +170 -0
  273. package/src/state.ts +327 -0
  274. package/src/status.ts +466 -0
  275. package/src/thread.ts +98 -0
  276. package/src/watchdog.ts +53 -0
  277. package/src/ws.ts +155 -0
@@ -0,0 +1,2121 @@
1
+ // node_modules/morphdom/dist/morphdom-esm.js
2
+ var DOCUMENT_FRAGMENT_NODE = 11;
3
+ function morphAttrs(fromNode, toNode) {
4
+ var toNodeAttrs = toNode.attributes;
5
+ var attr;
6
+ var attrName;
7
+ var attrNamespaceURI;
8
+ var attrValue;
9
+ var fromValue;
10
+ if (toNode.nodeType === DOCUMENT_FRAGMENT_NODE || fromNode.nodeType === DOCUMENT_FRAGMENT_NODE) return;
11
+ for (var i = toNodeAttrs.length - 1; i >= 0; i--) {
12
+ attr = toNodeAttrs[i];
13
+ attrName = attr.name;
14
+ attrNamespaceURI = attr.namespaceURI;
15
+ attrValue = attr.value;
16
+ if (attrNamespaceURI) {
17
+ attrName = attr.localName || attrName;
18
+ fromValue = fromNode.getAttributeNS(attrNamespaceURI, attrName);
19
+ if (fromValue !== attrValue) {
20
+ if (attr.prefix === "xmlns") attrName = attr.name;
21
+ fromNode.setAttributeNS(attrNamespaceURI, attrName, attrValue);
22
+ }
23
+ } else {
24
+ fromValue = fromNode.getAttribute(attrName);
25
+ if (fromValue !== attrValue) fromNode.setAttribute(attrName, attrValue);
26
+ }
27
+ }
28
+ var fromNodeAttrs = fromNode.attributes;
29
+ for (var d = fromNodeAttrs.length - 1; d >= 0; d--) {
30
+ attr = fromNodeAttrs[d];
31
+ attrName = attr.name;
32
+ attrNamespaceURI = attr.namespaceURI;
33
+ if (attrNamespaceURI) {
34
+ attrName = attr.localName || attrName;
35
+ if (!toNode.hasAttributeNS(attrNamespaceURI, attrName)) fromNode.removeAttributeNS(attrNamespaceURI, attrName);
36
+ } else if (!toNode.hasAttribute(attrName)) fromNode.removeAttribute(attrName);
37
+ }
38
+ }
39
+ var range;
40
+ var NS_XHTML = "http://www.w3.org/1999/xhtml";
41
+ var doc = typeof document === "undefined" ? void 0 : document;
42
+ var HAS_TEMPLATE_SUPPORT = !!doc && "content" in doc.createElement("template");
43
+ var HAS_RANGE_SUPPORT = !!doc && doc.createRange && "createContextualFragment" in doc.createRange();
44
+ function createFragmentFromTemplate(str) {
45
+ var template = doc.createElement("template");
46
+ template.innerHTML = str;
47
+ return template.content.childNodes[0];
48
+ }
49
+ function createFragmentFromRange(str) {
50
+ if (!range) {
51
+ range = doc.createRange();
52
+ range.selectNode(doc.body);
53
+ }
54
+ return range.createContextualFragment(str).childNodes[0];
55
+ }
56
+ function createFragmentFromWrap(str) {
57
+ var fragment = doc.createElement("body");
58
+ fragment.innerHTML = str;
59
+ return fragment.childNodes[0];
60
+ }
61
+ /**
62
+ * This is about the same
63
+ * var html = new DOMParser().parseFromString(str, 'text/html');
64
+ * return html.body.firstChild;
65
+ *
66
+ * @method toElement
67
+ * @param {String} str
68
+ */
69
+ function toElement(str) {
70
+ str = str.trim();
71
+ if (HAS_TEMPLATE_SUPPORT) return createFragmentFromTemplate(str);
72
+ else if (HAS_RANGE_SUPPORT) return createFragmentFromRange(str);
73
+ return createFragmentFromWrap(str);
74
+ }
75
+ /**
76
+ * Returns true if two node's names are the same.
77
+ *
78
+ * NOTE: We don't bother checking `namespaceURI` because you will never find two HTML elements with the same
79
+ * nodeName and different namespace URIs.
80
+ *
81
+ * @param {Element} a
82
+ * @param {Element} b The target element
83
+ * @return {boolean}
84
+ */
85
+ function compareNodeNames(fromEl, toEl) {
86
+ var fromNodeName = fromEl.nodeName;
87
+ var toNodeName = toEl.nodeName;
88
+ var fromCodeStart, toCodeStart;
89
+ if (fromNodeName === toNodeName) return true;
90
+ fromCodeStart = fromNodeName.charCodeAt(0);
91
+ toCodeStart = toNodeName.charCodeAt(0);
92
+ if (fromCodeStart <= 90 && toCodeStart >= 97) return fromNodeName === toNodeName.toUpperCase();
93
+ else if (toCodeStart <= 90 && fromCodeStart >= 97) return toNodeName === fromNodeName.toUpperCase();
94
+ else return false;
95
+ }
96
+ /**
97
+ * Create an element, optionally with a known namespace URI.
98
+ *
99
+ * @param {string} name the element name, e.g. 'div' or 'svg'
100
+ * @param {string} [namespaceURI] the element's namespace URI, i.e. the value of
101
+ * its `xmlns` attribute or its inferred namespace.
102
+ *
103
+ * @return {Element}
104
+ */
105
+ function createElementNS(name, namespaceURI) {
106
+ return !namespaceURI || namespaceURI === NS_XHTML ? doc.createElement(name) : doc.createElementNS(namespaceURI, name);
107
+ }
108
+ /**
109
+ * Copies the children of one DOM element to another DOM element
110
+ */
111
+ function moveChildren(fromEl, toEl) {
112
+ var curChild = fromEl.firstChild;
113
+ while (curChild) {
114
+ var nextChild = curChild.nextSibling;
115
+ toEl.appendChild(curChild);
116
+ curChild = nextChild;
117
+ }
118
+ return toEl;
119
+ }
120
+ function syncBooleanAttrProp(fromEl, toEl, name) {
121
+ if (fromEl[name] !== toEl[name]) {
122
+ fromEl[name] = toEl[name];
123
+ if (fromEl[name]) fromEl.setAttribute(name, "");
124
+ else fromEl.removeAttribute(name);
125
+ }
126
+ }
127
+ var specialElHandlers = {
128
+ OPTION: function(fromEl, toEl) {
129
+ var parentNode = fromEl.parentNode;
130
+ if (parentNode) {
131
+ var parentName = parentNode.nodeName.toUpperCase();
132
+ if (parentName === "OPTGROUP") {
133
+ parentNode = parentNode.parentNode;
134
+ parentName = parentNode && parentNode.nodeName.toUpperCase();
135
+ }
136
+ if (parentName === "SELECT" && !parentNode.hasAttribute("multiple")) {
137
+ if (fromEl.hasAttribute("selected") && !toEl.selected) {
138
+ fromEl.setAttribute("selected", "selected");
139
+ fromEl.removeAttribute("selected");
140
+ }
141
+ parentNode.selectedIndex = -1;
142
+ }
143
+ }
144
+ syncBooleanAttrProp(fromEl, toEl, "selected");
145
+ },
146
+ /**
147
+ * The "value" attribute is special for the <input> element since it sets
148
+ * the initial value. Changing the "value" attribute without changing the
149
+ * "value" property will have no effect since it is only used to the set the
150
+ * initial value. Similar for the "checked" attribute, and "disabled".
151
+ */
152
+ INPUT: function(fromEl, toEl) {
153
+ syncBooleanAttrProp(fromEl, toEl, "checked");
154
+ syncBooleanAttrProp(fromEl, toEl, "disabled");
155
+ if (fromEl.value !== toEl.value) fromEl.value = toEl.value;
156
+ if (!toEl.hasAttribute("value")) fromEl.removeAttribute("value");
157
+ },
158
+ TEXTAREA: function(fromEl, toEl) {
159
+ var newValue = toEl.value;
160
+ if (fromEl.value !== newValue) fromEl.value = newValue;
161
+ var firstChild = fromEl.firstChild;
162
+ if (firstChild) {
163
+ var oldValue = firstChild.nodeValue;
164
+ if (oldValue == newValue || !newValue && oldValue == fromEl.placeholder) return;
165
+ firstChild.nodeValue = newValue;
166
+ }
167
+ },
168
+ SELECT: function(fromEl, toEl) {
169
+ if (!toEl.hasAttribute("multiple")) {
170
+ var selectedIndex = -1;
171
+ var i = 0;
172
+ var curChild = fromEl.firstChild;
173
+ var optgroup;
174
+ var nodeName;
175
+ while (curChild) {
176
+ nodeName = curChild.nodeName && curChild.nodeName.toUpperCase();
177
+ if (nodeName === "OPTGROUP") {
178
+ optgroup = curChild;
179
+ curChild = optgroup.firstChild;
180
+ if (!curChild) {
181
+ curChild = optgroup.nextSibling;
182
+ optgroup = null;
183
+ }
184
+ } else {
185
+ if (nodeName === "OPTION") {
186
+ if (curChild.hasAttribute("selected")) {
187
+ selectedIndex = i;
188
+ break;
189
+ }
190
+ i++;
191
+ }
192
+ curChild = curChild.nextSibling;
193
+ if (!curChild && optgroup) {
194
+ curChild = optgroup.nextSibling;
195
+ optgroup = null;
196
+ }
197
+ }
198
+ }
199
+ fromEl.selectedIndex = selectedIndex;
200
+ }
201
+ }
202
+ };
203
+ var ELEMENT_NODE = 1;
204
+ var DOCUMENT_FRAGMENT_NODE$1 = 11;
205
+ var TEXT_NODE = 3;
206
+ var COMMENT_NODE = 8;
207
+ function noop() {}
208
+ function defaultGetNodeKey(node) {
209
+ if (node) return node.getAttribute && node.getAttribute("id") || node.id;
210
+ }
211
+ function morphdomFactory(morphAttrs) {
212
+ return function morphdom(fromNode, toNode, options) {
213
+ if (!options) options = {};
214
+ if (typeof toNode === "string") {
215
+ if (fromNode.nodeName === "#document" || fromNode.nodeName === "HTML" || fromNode.nodeName === "BODY") {
216
+ var toNodeHtml = toNode;
217
+ toNode = doc.createElement("html");
218
+ toNode.innerHTML = toNodeHtml;
219
+ } else toNode = toElement(toNode);
220
+ } else if (toNode.nodeType === DOCUMENT_FRAGMENT_NODE$1) toNode = toNode.firstElementChild;
221
+ var getNodeKey = options.getNodeKey || defaultGetNodeKey;
222
+ var onBeforeNodeAdded = options.onBeforeNodeAdded || noop;
223
+ var onNodeAdded = options.onNodeAdded || noop;
224
+ var onBeforeElUpdated = options.onBeforeElUpdated || noop;
225
+ var onElUpdated = options.onElUpdated || noop;
226
+ var onBeforeNodeDiscarded = options.onBeforeNodeDiscarded || noop;
227
+ var onNodeDiscarded = options.onNodeDiscarded || noop;
228
+ var onBeforeElChildrenUpdated = options.onBeforeElChildrenUpdated || noop;
229
+ var skipFromChildren = options.skipFromChildren || noop;
230
+ var addChild = options.addChild || function(parent, child) {
231
+ return parent.appendChild(child);
232
+ };
233
+ var childrenOnly = options.childrenOnly === true;
234
+ var fromNodesLookup = Object.create(null);
235
+ var keyedRemovalList = [];
236
+ function addKeyedRemoval(key) {
237
+ keyedRemovalList.push(key);
238
+ }
239
+ function walkDiscardedChildNodes(node, skipKeyedNodes) {
240
+ if (node.nodeType === ELEMENT_NODE) {
241
+ var curChild = node.firstChild;
242
+ while (curChild) {
243
+ var key = void 0;
244
+ if (skipKeyedNodes && (key = getNodeKey(curChild))) addKeyedRemoval(key);
245
+ else {
246
+ onNodeDiscarded(curChild);
247
+ if (curChild.firstChild) walkDiscardedChildNodes(curChild, skipKeyedNodes);
248
+ }
249
+ curChild = curChild.nextSibling;
250
+ }
251
+ }
252
+ }
253
+ /**
254
+ * Removes a DOM node out of the original DOM
255
+ *
256
+ * @param {Node} node The node to remove
257
+ * @param {Node} parentNode The nodes parent
258
+ * @param {Boolean} skipKeyedNodes If true then elements with keys will be skipped and not discarded.
259
+ * @return {undefined}
260
+ */
261
+ function removeNode(node, parentNode, skipKeyedNodes) {
262
+ if (onBeforeNodeDiscarded(node) === false) return;
263
+ if (parentNode) parentNode.removeChild(node);
264
+ onNodeDiscarded(node);
265
+ walkDiscardedChildNodes(node, skipKeyedNodes);
266
+ }
267
+ function indexTree(node) {
268
+ if (node.nodeType === ELEMENT_NODE || node.nodeType === DOCUMENT_FRAGMENT_NODE$1) {
269
+ var curChild = node.firstChild;
270
+ while (curChild) {
271
+ var key = getNodeKey(curChild);
272
+ if (key) fromNodesLookup[key] = curChild;
273
+ indexTree(curChild);
274
+ curChild = curChild.nextSibling;
275
+ }
276
+ }
277
+ }
278
+ indexTree(fromNode);
279
+ function handleNodeAdded(el) {
280
+ onNodeAdded(el);
281
+ var curChild = el.firstChild;
282
+ while (curChild) {
283
+ var nextSibling = curChild.nextSibling;
284
+ var key = getNodeKey(curChild);
285
+ if (key) {
286
+ var unmatchedFromEl = fromNodesLookup[key];
287
+ if (unmatchedFromEl && compareNodeNames(curChild, unmatchedFromEl)) {
288
+ curChild.parentNode.replaceChild(unmatchedFromEl, curChild);
289
+ morphEl(unmatchedFromEl, curChild);
290
+ } else handleNodeAdded(curChild);
291
+ } else handleNodeAdded(curChild);
292
+ curChild = nextSibling;
293
+ }
294
+ }
295
+ function cleanupFromEl(fromEl, curFromNodeChild, curFromNodeKey) {
296
+ while (curFromNodeChild) {
297
+ var fromNextSibling = curFromNodeChild.nextSibling;
298
+ if (curFromNodeKey = getNodeKey(curFromNodeChild)) addKeyedRemoval(curFromNodeKey);
299
+ else removeNode(curFromNodeChild, fromEl, true);
300
+ curFromNodeChild = fromNextSibling;
301
+ }
302
+ }
303
+ function morphEl(fromEl, toEl, childrenOnly) {
304
+ var toElKey = getNodeKey(toEl);
305
+ if (toElKey) delete fromNodesLookup[toElKey];
306
+ if (!childrenOnly) {
307
+ var beforeUpdateResult = onBeforeElUpdated(fromEl, toEl);
308
+ if (beforeUpdateResult === false) return;
309
+ else if (beforeUpdateResult instanceof HTMLElement) {
310
+ fromEl = beforeUpdateResult;
311
+ indexTree(fromEl);
312
+ }
313
+ morphAttrs(fromEl, toEl);
314
+ onElUpdated(fromEl);
315
+ if (onBeforeElChildrenUpdated(fromEl, toEl) === false) return;
316
+ }
317
+ if (fromEl.nodeName !== "TEXTAREA") morphChildren(fromEl, toEl);
318
+ else specialElHandlers.TEXTAREA(fromEl, toEl);
319
+ }
320
+ function morphChildren(fromEl, toEl) {
321
+ var skipFrom = skipFromChildren(fromEl, toEl);
322
+ var curToNodeChild = toEl.firstChild;
323
+ var curFromNodeChild = fromEl.firstChild;
324
+ var curToNodeKey;
325
+ var curFromNodeKey;
326
+ var fromNextSibling;
327
+ var toNextSibling;
328
+ var matchingFromEl;
329
+ outer: while (curToNodeChild) {
330
+ toNextSibling = curToNodeChild.nextSibling;
331
+ curToNodeKey = getNodeKey(curToNodeChild);
332
+ while (!skipFrom && curFromNodeChild) {
333
+ fromNextSibling = curFromNodeChild.nextSibling;
334
+ if (curToNodeChild.isSameNode && curToNodeChild.isSameNode(curFromNodeChild)) {
335
+ curToNodeChild = toNextSibling;
336
+ curFromNodeChild = fromNextSibling;
337
+ continue outer;
338
+ }
339
+ curFromNodeKey = getNodeKey(curFromNodeChild);
340
+ var curFromNodeType = curFromNodeChild.nodeType;
341
+ var isCompatible = void 0;
342
+ if (curFromNodeType === curToNodeChild.nodeType) {
343
+ if (curFromNodeType === ELEMENT_NODE) {
344
+ if (curToNodeKey) {
345
+ if (curToNodeKey !== curFromNodeKey) {
346
+ if (matchingFromEl = fromNodesLookup[curToNodeKey]) {
347
+ if (fromNextSibling === matchingFromEl) isCompatible = false;
348
+ else {
349
+ fromEl.insertBefore(matchingFromEl, curFromNodeChild);
350
+ if (curFromNodeKey) addKeyedRemoval(curFromNodeKey);
351
+ else removeNode(curFromNodeChild, fromEl, true);
352
+ curFromNodeChild = matchingFromEl;
353
+ curFromNodeKey = getNodeKey(curFromNodeChild);
354
+ }
355
+ } else isCompatible = false;
356
+ }
357
+ } else if (curFromNodeKey) isCompatible = false;
358
+ isCompatible = isCompatible !== false && compareNodeNames(curFromNodeChild, curToNodeChild);
359
+ if (isCompatible) morphEl(curFromNodeChild, curToNodeChild);
360
+ } else if (curFromNodeType === TEXT_NODE || curFromNodeType == COMMENT_NODE) {
361
+ isCompatible = true;
362
+ if (curFromNodeChild.nodeValue !== curToNodeChild.nodeValue) curFromNodeChild.nodeValue = curToNodeChild.nodeValue;
363
+ }
364
+ }
365
+ if (isCompatible) {
366
+ curToNodeChild = toNextSibling;
367
+ curFromNodeChild = fromNextSibling;
368
+ continue outer;
369
+ }
370
+ if (curFromNodeKey) addKeyedRemoval(curFromNodeKey);
371
+ else removeNode(curFromNodeChild, fromEl, true);
372
+ curFromNodeChild = fromNextSibling;
373
+ }
374
+ if (curToNodeKey && (matchingFromEl = fromNodesLookup[curToNodeKey]) && compareNodeNames(matchingFromEl, curToNodeChild)) {
375
+ if (!skipFrom) addChild(fromEl, matchingFromEl);
376
+ morphEl(matchingFromEl, curToNodeChild);
377
+ } else {
378
+ var onBeforeNodeAddedResult = onBeforeNodeAdded(curToNodeChild);
379
+ if (onBeforeNodeAddedResult !== false) {
380
+ if (onBeforeNodeAddedResult) curToNodeChild = onBeforeNodeAddedResult;
381
+ if (curToNodeChild.actualize) curToNodeChild = curToNodeChild.actualize(fromEl.ownerDocument || doc);
382
+ addChild(fromEl, curToNodeChild);
383
+ handleNodeAdded(curToNodeChild);
384
+ }
385
+ }
386
+ curToNodeChild = toNextSibling;
387
+ curFromNodeChild = fromNextSibling;
388
+ }
389
+ cleanupFromEl(fromEl, curFromNodeChild, curFromNodeKey);
390
+ var specialElHandler = specialElHandlers[fromEl.nodeName];
391
+ if (specialElHandler) specialElHandler(fromEl, toEl);
392
+ }
393
+ var morphedNode = fromNode;
394
+ var morphedNodeType = morphedNode.nodeType;
395
+ var toNodeType = toNode.nodeType;
396
+ if (!childrenOnly) {
397
+ if (morphedNodeType === ELEMENT_NODE) {
398
+ if (toNodeType === ELEMENT_NODE) {
399
+ if (!compareNodeNames(fromNode, toNode)) {
400
+ onNodeDiscarded(fromNode);
401
+ morphedNode = moveChildren(fromNode, createElementNS(toNode.nodeName, toNode.namespaceURI));
402
+ }
403
+ } else morphedNode = toNode;
404
+ } else if (morphedNodeType === TEXT_NODE || morphedNodeType === COMMENT_NODE) {
405
+ if (toNodeType === morphedNodeType) {
406
+ if (morphedNode.nodeValue !== toNode.nodeValue) morphedNode.nodeValue = toNode.nodeValue;
407
+ return morphedNode;
408
+ } else morphedNode = toNode;
409
+ }
410
+ }
411
+ if (morphedNode === toNode) onNodeDiscarded(fromNode);
412
+ else {
413
+ if (toNode.isSameNode && toNode.isSameNode(morphedNode)) return;
414
+ morphEl(morphedNode, toNode, childrenOnly);
415
+ if (keyedRemovalList) for (var i = 0, len = keyedRemovalList.length; i < len; i++) {
416
+ var elToRemove = fromNodesLookup[keyedRemovalList[i]];
417
+ if (elToRemove) removeNode(elToRemove, elToRemove.parentNode, false);
418
+ }
419
+ }
420
+ if (!childrenOnly && morphedNode !== fromNode && fromNode.parentNode) {
421
+ if (morphedNode.actualize) morphedNode = morphedNode.actualize(fromNode.ownerDocument || doc);
422
+ fromNode.parentNode.replaceChild(morphedNode, fromNode);
423
+ }
424
+ return morphedNode;
425
+ };
426
+ }
427
+ var morphdom = morphdomFactory(morphAttrs);
428
+ // src/html.ts
429
+ /** A piece of HTML that is not escaped again. `String(piece)` is its markup. */
430
+ var Html = class {
431
+ value;
432
+ constructor(value) {
433
+ this.value = value;
434
+ }
435
+ toString() {
436
+ return this.value;
437
+ }
438
+ };
439
+ const ESCAPE = {
440
+ "&": "&amp;",
441
+ "<": "&lt;",
442
+ ">": "&gt;",
443
+ "\"": "&quot;",
444
+ "'": "&#39;"
445
+ };
446
+ /** Text → HTML that shows it as text. */
447
+ const escape = (value) => String(value).replace(/[&<>"']/g, (c) => ESCAPE[c]);
448
+ /** Markup to use as it is: only for HTML that is safe already, never for text from outside. */
449
+ const raw = (value) => new Html(String(value ?? ""));
450
+ function part(value) {
451
+ if (value == null || value === false) return "";
452
+ if (value instanceof Html) return value.value;
453
+ if (Array.isArray(value)) return value.map(part).join("");
454
+ return escape(value);
455
+ }
456
+ function html(strings, ...values) {
457
+ let out = strings[0];
458
+ for (let i = 0; i < values.length; i++) out += part(values[i]) + strings[i + 1];
459
+ return new Html(out);
460
+ }
461
+ // src/client/page/view.ts
462
+ /** The bottom of the visible part of the page, in window coordinates. */
463
+ function viewBottom() {
464
+ const inset = parseFloat(getComputedStyle(document.documentElement).getPropertyValue("--wp-inset-bottom")) || 0;
465
+ return Math.max(0, innerHeight - inset);
466
+ }
467
+ const base = (() => {
468
+ try {
469
+ return JSON.parse(document.getElementById("wp-page")?.textContent ?? "{}");
470
+ } catch {
471
+ return {};
472
+ }
473
+ })().base ?? "";
474
+ /** A path of the project's server (`/api/events`) as this page requests it. */
475
+ const url = (path) => base + path;
476
+ /** A localStorage key, kept apart from other projects' on the same origin. */
477
+ const storageKey = (key) => base ? `${base}|${key}` : key;
478
+ // src/client/page/fresh.ts
479
+ const DWELL_MS = 600;
480
+ const FADE_MS = 2500;
481
+ const sigOf = /* @__PURE__ */ new WeakMap();
482
+ const unseen = /* @__PURE__ */ new Set();
483
+ const timers = /* @__PURE__ */ new WeakMap();
484
+ let storeKey = "";
485
+ let core$1;
486
+ const SERVER_MARKS = /* @__PURE__ */ new Set([
487
+ "data-wp-at",
488
+ "data-wp-key",
489
+ "data-wp-maximize",
490
+ "data-wp-other",
491
+ "data-wp-other-text",
492
+ "data-wp-quiet",
493
+ "data-wp-self",
494
+ "data-wp-sort"
495
+ ]);
496
+ /**
497
+ * FNV-1a over the block's HTML as the server sent it, ignoring anything quiet: content inside
498
+ * [data-wp-quiet] can appear, change or go without the block counting as changed. What the browser
499
+ * added is left out, so a block in the page and the same block in a new render have one signature:
500
+ * an island's content (it draws itself; its props are in its key), the page's own elements (a folded
501
+ * form's card), its marks (data-wp-* the server doesn't write: a form's state) and its classes for
502
+ * new content.
503
+ */
504
+ function signature(el) {
505
+ const clone = el.cloneNode(true);
506
+ for (const q of clone.querySelectorAll("[data-wp-quiet], .wp-folded")) q.remove();
507
+ for (const n of [clone, ...clone.querySelectorAll("*")]) {
508
+ for (const { name } of [...n.attributes]) if (name.startsWith("data-wp-") && !SERVER_MARKS.has(name)) n.removeAttribute(name);
509
+ if (n.getAttribute("role") === "tab") {
510
+ n.removeAttribute("aria-selected");
511
+ n.removeAttribute("tabindex");
512
+ }
513
+ n.classList.remove("wp-new", "wp-new-seen");
514
+ if (!n.classList.length) n.removeAttribute("class");
515
+ }
516
+ for (const island of clone.querySelectorAll("[data-wp-key]")) island.replaceChildren();
517
+ const s = clone.outerHTML;
518
+ let h = 2166136261;
519
+ for (let i = 0; i < s.length; i++) h = Math.imul(h ^ s.charCodeAt(i), 16777619);
520
+ return (h >>> 0).toString(36);
521
+ }
522
+ /** Signatures of the top-level blocks in an HTML string, in order. */
523
+ function signaturesOf(html) {
524
+ const t = document.createElement("template");
525
+ t.innerHTML = html;
526
+ return [...t.content.children].map(signature);
527
+ }
528
+ function loadSeen() {
529
+ try {
530
+ const raw = localStorage.getItem(storeKey);
531
+ return raw ? new Set(JSON.parse(raw)) : null;
532
+ } catch {
533
+ return null;
534
+ }
535
+ }
536
+ function saveSeen(main) {
537
+ try {
538
+ const seen = [...main.children].filter((el) => !unseen.has(el) && ![...unseen].some((u) => el.contains(u))).map((el) => sigOf.get(el)).filter(Boolean);
539
+ localStorage.setItem(storeKey, JSON.stringify(seen));
540
+ } catch {}
541
+ }
542
+ let mainEl;
543
+ /** In view enough to count as read: half the block, or half the screen for blocks taller than that. */
544
+ function inView$2(el) {
545
+ const r = el.getBoundingClientRect();
546
+ const bottom = viewBottom();
547
+ const overlap = Math.min(r.bottom, bottom) - Math.max(r.top, 0);
548
+ return overlap > 0 && overlap >= Math.min(r.height, bottom) * .5;
549
+ }
550
+ /** Start the dwell timer of unseen blocks in view; stop it for blocks that left the view. */
551
+ function check() {
552
+ const active = document.visibilityState === "visible";
553
+ for (const el of unseen) {
554
+ if (!el.isConnected) {
555
+ unseen.delete(el);
556
+ continue;
557
+ }
558
+ const pending = timers.has(el);
559
+ if (active && inView$2(el)) {
560
+ if (!pending) timers.set(el, window.setTimeout(() => {
561
+ timers.delete(el);
562
+ markSeen(el);
563
+ }, DWELL_MS));
564
+ } else if (pending) {
565
+ clearTimeout(timers.get(el));
566
+ timers.delete(el);
567
+ }
568
+ }
569
+ }
570
+ let checkFrame = 0;
571
+ const scheduleCheck = () => {
572
+ cancelAnimationFrame(checkFrame);
573
+ checkFrame = requestAnimationFrame(check);
574
+ };
575
+ addEventListener("scroll", scheduleCheck, { passive: true });
576
+ addEventListener("resize", scheduleCheck);
577
+ document.addEventListener("visibilitychange", scheduleCheck);
578
+ setInterval(() => {
579
+ if (unseen.size) check();
580
+ }, 500);
581
+ function markSeen(el) {
582
+ if (!unseen.delete(el)) return;
583
+ el.classList.add("wp-new-seen");
584
+ setTimeout(() => el.classList.remove("wp-new", "wp-new-seen"), FADE_MS);
585
+ saveSeen(mainEl);
586
+ update$1();
587
+ }
588
+ /**
589
+ * An item in a list: its bar where the bars of blocks are, not in the list's indent by its bullet.
590
+ * Set inline, so set again after every update (which takes the page's style attributes back).
591
+ */
592
+ function placeBar(el) {
593
+ if (el.parentElement === mainEl || !mainEl?.contains(el)) return;
594
+ const item = el;
595
+ let block = el;
596
+ while (block.parentElement && block.parentElement !== mainEl) block = block.parentElement;
597
+ item.style.removeProperty("--wp-new-at");
598
+ const base = parseFloat(getComputedStyle(item).getPropertyValue("--wp-new-at")) || 14;
599
+ const indent = item.getBoundingClientRect().left - block.getBoundingClientRect().left;
600
+ item.style.setProperty("--wp-new-at", `${base + indent}px`);
601
+ }
602
+ function markNew(el) {
603
+ if (el.matches("[data-wp-quiet]")) return;
604
+ el.classList.remove("wp-new-seen");
605
+ el.classList.add("wp-new");
606
+ placeBar(el);
607
+ unseen.add(el);
608
+ scheduleCheck();
609
+ }
610
+ /**
611
+ * Something that changed in place, outside a page update (an agent's chat message, edited: it says
612
+ * so with `wp-changed`): new until the reader has seen it, as a changed block is.
613
+ */
614
+ function markChanged(el) {
615
+ markNew(el);
616
+ update$1();
617
+ }
618
+ let upToast = null;
619
+ let downToast = null;
620
+ function split() {
621
+ const above = [], below = [];
622
+ for (const el of unseen) {
623
+ if (!el.isConnected) {
624
+ unseen.delete(el);
625
+ continue;
626
+ }
627
+ const r = el.getBoundingClientRect();
628
+ if (r.bottom < 60) above.push(el);
629
+ else if (r.top > viewBottom()) below.push(el);
630
+ }
631
+ const top = (el) => el.getBoundingClientRect().top;
632
+ above.sort((a, b) => top(b) - top(a));
633
+ below.sort((a, b) => top(a) - top(b));
634
+ return {
635
+ above,
636
+ below
637
+ };
638
+ }
639
+ let raf = 0;
640
+ function update$1() {
641
+ cancelAnimationFrame(raf);
642
+ raf = requestAnimationFrame(() => {
643
+ const { above, below } = split();
644
+ for (const [toast, list, arrow] of [[
645
+ upToast,
646
+ above,
647
+ "↑"
648
+ ], [
649
+ downToast,
650
+ below,
651
+ "↓"
652
+ ]]) {
653
+ if (!toast) continue;
654
+ if (list.length) {
655
+ toast.update(`${arrow} new (${list.length})`);
656
+ toast.show();
657
+ } else toast.hide();
658
+ }
659
+ core$1?.badge("new", unseen.size ? String(unseen.size) : null);
660
+ });
661
+ }
662
+ function go(dir) {
663
+ const { above, below } = split();
664
+ (dir === "up" ? above : below)[0]?.scrollIntoView({
665
+ behavior: "smooth",
666
+ block: "start"
667
+ });
668
+ }
669
+ const seeAll = () => {
670
+ for (const el of [...unseen]) markSeen(el);
671
+ };
672
+ addEventListener("scroll", update$1, { passive: true });
673
+ addEventListener("resize", update$1);
674
+ /** Below this share of blocks recognised from the last visit, the page counts as new to the reader. */
675
+ const RECOGNISED_MIN = .25;
676
+ /**
677
+ * First render: blocks the reader has not seen on a previous visit are new. On a first visit, or
678
+ * when so little is recognised that the page is effectively a different one (a rewrite, say),
679
+ * nothing is marked: marking every block tells the reader nothing.
680
+ */
681
+ function trackInitial(main, page, api) {
682
+ core$1 = api;
683
+ upToast = api.toast("", {
684
+ ms: 0,
685
+ kind: "alert",
686
+ name: "new-up",
687
+ order: 1,
688
+ onClick: () => go("up"),
689
+ onDismiss: seeAll
690
+ });
691
+ downToast = api.toast("", {
692
+ ms: 0,
693
+ kind: "alert",
694
+ name: "new-down",
695
+ order: 2,
696
+ onClick: () => go("down"),
697
+ onDismiss: seeAll
698
+ });
699
+ upToast.hide();
700
+ downToast.hide();
701
+ mainEl = main;
702
+ storeKey = storageKey(`wp-seen:${page}`);
703
+ const blocks = [...main.children];
704
+ const sigs = blocks.map(signature);
705
+ blocks.forEach((el, i) => sigOf.set(el, sigs[i]));
706
+ const seen = loadSeen();
707
+ const recognised = seen ? sigs.filter((s) => seen.has(s)).length : 0;
708
+ if (seen && recognised >= blocks.length * RECOGNISED_MIN) blocks.forEach((el, i) => {
709
+ if (!seen.has(sigs[i])) markNew(el);
710
+ });
711
+ saveSeen(main);
712
+ update$1();
713
+ }
714
+ /** An item's signature: its content, not its own attributes (its place in a sort) nor the times shown in it. */
715
+ function itemSignature(li) {
716
+ const clone = li.cloneNode(true);
717
+ for (const { name } of [...clone.attributes]) clone.removeAttribute(name);
718
+ for (const t of clone.querySelectorAll("time[data-ts]")) t.textContent = "";
719
+ return signature(clone);
720
+ }
721
+ /** The page's list items, but those in something quiet. */
722
+ const itemsOf = (root) => [...root.querySelectorAll("li")].filter((li) => !li.closest("[data-wp-quiet]"));
723
+ /** How many of each item signature are on the page: what the next update compares with. */
724
+ let itemsBefore = /* @__PURE__ */ new Map();
725
+ function countItems(main) {
726
+ mainEl = main;
727
+ itemsBefore = /* @__PURE__ */ new Map();
728
+ for (const li of itemsOf(main)) {
729
+ const sig = itemSignature(li);
730
+ itemsBefore.set(sig, (itemsBefore.get(sig) ?? 0) + 1);
731
+ }
732
+ }
733
+ /** The new items in a block that changed: the innermost ones, as an item new inside makes its parent differ too. */
734
+ function newItems(block, before) {
735
+ const fresh = itemsOf(block).filter((li) => {
736
+ const sig = itemSignature(li);
737
+ const left = before.get(sig) ?? 0;
738
+ if (left > 0) before.set(sig, left - 1);
739
+ return left === 0;
740
+ });
741
+ return fresh.filter((li) => !fresh.some((other) => other !== li && li.contains(other)));
742
+ }
743
+ /** After a live update: blocks whose content was not on the page before are new, or in a list, the items. */
744
+ function trackUpdate(main, previous, next) {
745
+ const before = /* @__PURE__ */ new Map();
746
+ for (const s of previous) before.set(s, (before.get(s) ?? 0) + 1);
747
+ const items = new Map(itemsBefore);
748
+ [...main.children].forEach((el, i) => {
749
+ const sig = next[i];
750
+ sigOf.set(el, sig);
751
+ const left = before.get(sig) ?? 0;
752
+ if (left > 0) return before.set(sig, left - 1);
753
+ const fresh = newItems(el, items);
754
+ if (fresh.length) fresh.forEach(markNew);
755
+ else markNew(el);
756
+ });
757
+ countItems(main);
758
+ for (const el of [...unseen]) if (!el.isConnected) unseen.delete(el);
759
+ for (const el of unseen) placeBar(el);
760
+ saveSeen(main);
761
+ update$1();
762
+ }
763
+ // src/client/reactive.ts
764
+ function reactive(get) {
765
+ const listeners = /* @__PURE__ */ new Set();
766
+ const value = (() => get());
767
+ value.on = (fn) => {
768
+ listeners.add(fn);
769
+ return () => {
770
+ listeners.delete(fn);
771
+ };
772
+ };
773
+ value.notify = () => {
774
+ const now = get();
775
+ for (const fn of [...listeners]) fn(now);
776
+ };
777
+ return value;
778
+ }
779
+ // src/client/page/theme.ts
780
+ const media = matchMedia("(prefers-color-scheme: dark)");
781
+ const resolve = () => document.documentElement.dataset.theme ?? (media.matches ? "dark" : "light");
782
+ let theme = resolve();
783
+ function update() {
784
+ const next = resolve();
785
+ if (next === theme) return;
786
+ theme = next;
787
+ currentTheme.notify();
788
+ }
789
+ media.addEventListener("change", update);
790
+ /** The theme in effect, as it changes (api.theme). */
791
+ const currentTheme = reactive(() => theme);
792
+ const themePreference = () => document.documentElement.dataset.theme ?? "auto";
793
+ function setThemePreference(pref) {
794
+ if (pref === "auto") delete document.documentElement.dataset.theme;
795
+ else document.documentElement.dataset.theme = pref;
796
+ try {
797
+ if (pref === "auto") localStorage.removeItem("wp-theme");
798
+ else localStorage.setItem("wp-theme", pref);
799
+ } catch {}
800
+ update();
801
+ }
802
+ // src/status.ts
803
+ /**
804
+ * Was this event written by the reader (a form submit, a comment), not by an agent? Agents write
805
+ * through the command line, which marks its events `from: 'cli'`: an agent's reply, a claim, a mark.
806
+ */
807
+ const fromReader = (event) => event.from !== "cli";
808
+ /**
809
+ * The agent's messages on a page the reader hasn't read: events from the agent of a type
810
+ * `isMessage` says is for the reader, not named by a `workpad:read` from the reader, not
811
+ * replaced by a later one (`replaces`), and, given the page's `chats`, not in a chat (`data.chat`)
812
+ * that is no longer among them.
813
+ */
814
+ function unreadMessages(events, isMessage, chats) {
815
+ const read = /* @__PURE__ */ new Set();
816
+ const replaced = /* @__PURE__ */ new Set();
817
+ for (const e of events) {
818
+ if (e.type === "workpad:read" && fromReader(e)) for (const id of e.data?.ids ?? []) read.add(String(id));
819
+ if (e.data?.replaces) replaced.add(String(e.data.replaces));
820
+ }
821
+ const offPage = (e) => !!chats && typeof e.data?.chat === "string" && !chats.has(e.data.chat);
822
+ return events.filter((e) => !fromReader(e) && isMessage(e.type) && !read.has(e.id) && !replaced.has(e.id) && !offPage(e));
823
+ }
824
+ /** How many things on a page wait for the reader: its open questions and unread messages. */
825
+ const awaiting = (p) => p.open.length + p.unread.length;
826
+ // src/client/forms.ts
827
+ /** One line quoting an answer: what was chosen, then what was written. */
828
+ /**
829
+ * An answer, told apart: the button it was sent with (none for a plain Send), what was chosen
830
+ * (options, short values), and what was written.
831
+ */
832
+ function answerParts(data, action) {
833
+ const chosen = [], written = [];
834
+ for (const [k, v] of Object.entries(data)) {
835
+ if (k.includes(":") || v == null || v === "" || v === false) continue;
836
+ if (Array.isArray(v)) {
837
+ if (v.length) chosen.push(v.join(", "));
838
+ } else if (v === true) continue;
839
+ else if (String(v).length > 60 || String(v).includes("\n")) written.push(String(v));
840
+ else chosen.push(String(v));
841
+ }
842
+ return {
843
+ action: action && !["Send", "Submit"].includes(action) ? action : null,
844
+ chosen,
845
+ written
846
+ };
847
+ }
848
+ let current$2 = [];
849
+ reactive(() => current$2);
850
+ // src/icons.ts
851
+ /** An inbox: what awaits the reader (the header's menu, the overview). */
852
+ const INBOX_ICON = "<svg viewBox=\"0 0 16 16\" width=\"13\" height=\"13\" aria-hidden=\"true\"><path d=\"M2 9.5 3.8 3.2A1 1 0 0 1 4.8 2.5h6.4a1 1 0 0 1 1 .7L14 9.5V13a.5.5 0 0 1-.5.5h-11A.5.5 0 0 1 2 13Zm0 0h3.5l1 1.5h3l1-1.5H14\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.4\" stroke-linejoin=\"round\"/></svg>";
853
+ /** Copy: two sheets (the list of who listens copies an agent's id with it). */
854
+ const COPY_ICON = "<svg viewBox=\"0 0 16 16\" width=\"13\" height=\"13\" aria-hidden=\"true\"><rect x=\"5.5\" y=\"5.5\" width=\"8\" height=\"8\" rx=\"1.5\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.4\"/><path d=\"M10.5 3.5v-.5A1.5 1.5 0 0 0 9 1.5H4A1.5 1.5 0 0 0 2.5 3v5A1.5 1.5 0 0 0 4 9.5h.5\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.4\"/></svg>";
855
+ /** Done: a check (what was copied). */
856
+ const CHECK_ICON = "<svg viewBox=\"0 0 16 16\" width=\"13\" height=\"13\" aria-hidden=\"true\"><path d=\"M3 8.5 6.5 12 13 4.5\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.6\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg>";
857
+ /** "Awaiting you: 2 things", and where: what the inbox says to a reader who hovers it. */
858
+ const awaitingLabel = (n, where = "") => `Awaiting you: ${n === 1 ? "1 question or message" : `${n} questions and messages`}${where}`;
859
+ // src/client/page/elsewhere.ts
860
+ /** A link to a page that scrolls it to its first waiting question. */
861
+ const WAITING_HASH = "#wp-waiting";
862
+ const box = document.createElement("div");
863
+ box.className = "wp-elsewhere";
864
+ box.hidden = true;
865
+ box.innerHTML = "<button type=\"button\" class=\"wp-elsewhere-toggle wp-awaiting\" aria-haspopup=\"true\" aria-expanded=\"false\"></button><ul class=\"wp-elsewhere-list\" hidden></ul>";
866
+ const toggle = box.querySelector("button");
867
+ toggle.innerHTML = `${INBOX_ICON}<span class="wp-elsewhere-count"></span>`;
868
+ const count = toggle.querySelector("span");
869
+ const list = box.querySelector("ul");
870
+ function open(yes) {
871
+ list.hidden = !yes;
872
+ toggle.setAttribute("aria-expanded", String(yes));
873
+ }
874
+ let current$1 = "";
875
+ /** This project's pages with something waiting, but this one. */
876
+ async function here() {
877
+ return (await (await fetch(url("/api/status"), { cache: "no-store" })).json()).filter((p) => p.page !== current$1).map((p) => ({
878
+ href: `${base}/${p.page.split("/").map(encodeURIComponent).join("/")}${WAITING_HASH}`,
879
+ title: p.title,
880
+ n: awaiting(p)
881
+ })).filter((w) => w.n > 0);
882
+ }
883
+ /**
884
+ * Under a shared server (see Entries in DESIGN.md): the other projects of this one's entry, by
885
+ * project, as the server's index has them; empty on a server of its own, or when it can't say.
886
+ */
887
+ async function others() {
888
+ if (!base) return [];
889
+ const entry = base.split("/")[1];
890
+ try {
891
+ const res = await fetch(`/api/index?entry=${encodeURIComponent(entry ?? "")}`, { cache: "no-store" });
892
+ if (!res.ok) return [];
893
+ return (await res.json()).filter((p) => p.base !== base).map((p) => ({
894
+ label: p.label,
895
+ pages: p.pages.map((x) => ({
896
+ href: `${x.url}${WAITING_HASH}`,
897
+ title: x.title,
898
+ n: x.open.length + x.unread
899
+ })).filter((w) => w.n > 0)
900
+ })).filter((g) => g.pages.length);
901
+ } catch {
902
+ return [];
903
+ }
904
+ }
905
+ async function load() {
906
+ let mine;
907
+ let rest;
908
+ try {
909
+ [mine, rest] = await Promise.all([here(), others()]);
910
+ } catch {
911
+ return;
912
+ }
913
+ const all = [...mine, ...rest.flatMap((g) => g.pages)];
914
+ const total = all.reduce((sum, w) => sum + w.n, 0);
915
+ box.hidden = total === 0;
916
+ if (!total) open(false);
917
+ count.textContent = String(total);
918
+ toggle.title = awaitingLabel(total, ` on ${all.length === 1 ? "another page" : `${all.length} other pages`}`);
919
+ toggle.setAttribute("aria-label", toggle.title);
920
+ const item = (w) => {
921
+ const li = document.createElement("li");
922
+ const a = document.createElement("a");
923
+ a.href = w.href;
924
+ a.textContent = `${w.title} (${w.n})`;
925
+ li.append(a);
926
+ return li;
927
+ };
928
+ const heading = (text) => Object.assign(document.createElement("li"), {
929
+ className: "wp-elsewhere-group",
930
+ textContent: text,
931
+ title: text
932
+ });
933
+ list.replaceChildren(...rest.length && mine.length ? [heading("here")] : [], ...mine.map(item), ...rest.flatMap((g) => [heading(g.label), ...g.pages.map(item)]));
934
+ }
935
+ let timer$1 = 0;
936
+ let stale = false;
937
+ const reload = () => {
938
+ clearTimeout(timer$1);
939
+ if (document.hidden) return void (stale = true);
940
+ timer$1 = window.setTimeout(load, 100);
941
+ };
942
+ document.addEventListener("visibilitychange", () => {
943
+ if (document.hidden || !stale) return;
944
+ stale = false;
945
+ reload();
946
+ });
947
+ function trackElsewhere(root, handle, core) {
948
+ current$1 = handle.id;
949
+ const nav = root.querySelector(".wp-nav");
950
+ if (!nav) return;
951
+ (nav.querySelector("[data-wp-slot=header]") ?? nav.querySelector(".wp-theme"))?.before(box);
952
+ toggle.addEventListener("click", () => open(!!list.hidden));
953
+ document.addEventListener("click", (e) => {
954
+ if (!box.contains(e.target)) open(false);
955
+ });
956
+ document.addEventListener("keydown", (e) => {
957
+ if (e.key === "Escape" && !list.hidden) {
958
+ open(false);
959
+ toggle.focus();
960
+ }
961
+ });
962
+ core.events.on(reload);
963
+ core.listeners.on(reload);
964
+ handle.onChange(reload);
965
+ load();
966
+ if (base) document.addEventListener("wp-elsewhere", reload);
967
+ }
968
+ // src/client/page/waiting.ts
969
+ let main$2;
970
+ let api$1;
971
+ let forms = [];
972
+ const reopened = /* @__PURE__ */ new Map();
973
+ const inState = (state) => forms.filter((f) => f.state === state && f.form.isConnected).map((f) => f.form);
974
+ /** Where an unread message is on the page: its own element, else the one holding it. */
975
+ function messageTarget(id) {
976
+ const own = document.querySelector(`[data-wp-message="${CSS.escape(id)}"]`);
977
+ if (own && own.getClientRects().length) return own;
978
+ return [...document.querySelectorAll("[data-wp-holds]")].find((el) => el.dataset.wpHolds.split(" ").includes(id)) ?? null;
979
+ }
980
+ /** What waits for the reader, top to bottom: open forms and unread messages. */
981
+ function targets(kind = "all") {
982
+ const list = [.../* @__PURE__ */ new Set([...kind === "all" ? inState("open") : [], ...api$1.unread().map((e) => messageTarget(e.id)).filter((el) => !!el)])];
983
+ const top = (el) => el.getBoundingClientRect().top;
984
+ return list.sort((a, b) => top(a) - top(b));
985
+ }
986
+ let waitingToast;
987
+ let unreadToast;
988
+ let toastTimer = 0;
989
+ let unreadShown = false;
990
+ let dismissed = null;
991
+ const chatsOpen = /* @__PURE__ */ new Set();
992
+ function card(form, name, last, state) {
993
+ let el = form.querySelector(":scope > .wp-folded");
994
+ if (!el) {
995
+ el = document.createElement("div");
996
+ el.className = "wp-folded";
997
+ el.innerHTML = "<div class=\"wp-folded-head\"><span class=\"wp-folded-choice\"></span><span class=\"wp-folded-change\"></span></div><ul class=\"wp-folded-choices\"></ul><div class=\"wp-folded-text\"></div><button type=\"button\" class=\"wp-folded-chat\"></button>";
998
+ form.prepend(el);
999
+ }
1000
+ const { action, chosen, written } = answerParts(last.data, last.action);
1001
+ const list = action || chosen.length > 1 ? chosen : [];
1002
+ const head = action ?? (chosen.length > 1 ? "answered" : chosen[0] ?? written.shift() ?? "answered");
1003
+ el.querySelector(".wp-folded-choice").textContent = `✓ ${head}`;
1004
+ const choices = el.querySelector(".wp-folded-choices");
1005
+ choices.replaceChildren(...list.map((c) => Object.assign(document.createElement("li"), { textContent: c })));
1006
+ choices.hidden = !list.length;
1007
+ el.querySelector(".wp-folded-change").textContent = state === "received" ? "received · change" : "decided · change";
1008
+ const text = el.querySelector(".wp-folded-text");
1009
+ text.textContent = written.join("\n\n");
1010
+ text.hidden = !written.length;
1011
+ const messages = api$1.events().filter((e) => e.type === "chat:message" && e.data.chat === name).length;
1012
+ const thread = form.querySelector(":scope > [data-block=chat-thread]");
1013
+ const unreadHere = !!thread && api$1.unread().some((m) => thread.querySelector(`[data-wp-message="${CSS.escape(m.id)}"]`) || m.type === "chat:message" && m.data.chat === name);
1014
+ const box = thread?.querySelector("textarea");
1015
+ const writing = !!box && (document.activeElement === box || box.value.trim() !== "");
1016
+ if (unreadHere || writing) chatsOpen.add(name);
1017
+ const open = chatsOpen.has(name);
1018
+ form.toggleAttribute("data-wp-chat-open", open);
1019
+ const chat = el.querySelector(".wp-folded-chat");
1020
+ chat.hidden = !messages;
1021
+ chat.textContent = `💬 ${messages} message${messages === 1 ? "" : "s"} ${open ? "▾" : "▸"}`;
1022
+ chat.setAttribute("aria-expanded", String(open));
1023
+ }
1024
+ function show(list = forms) {
1025
+ forms = list;
1026
+ for (const { form, name, state, last } of forms) {
1027
+ const done = state === "received" || state === "handled";
1028
+ if (last && reopened.has(name) && reopened.get(name) !== last.id && done) reopened.delete(name);
1029
+ const folded = done && !reopened.has(name);
1030
+ form.toggleAttribute("data-wp-folded", folded);
1031
+ if (folded && last) card(form, name, last, state);
1032
+ else {
1033
+ form.querySelector(":scope > .wp-folded")?.remove();
1034
+ form.removeAttribute("data-wp-chat-open");
1035
+ }
1036
+ }
1037
+ const unread = api$1.unread().length;
1038
+ const n = inState("open").length + unread;
1039
+ const questions = inState("open").length;
1040
+ if (questions) {
1041
+ waitingToast.update(`→ unanswered (${questions})`);
1042
+ waitingToast.show();
1043
+ } else waitingToast.hide();
1044
+ api$1.badge("waiting", n ? `!${n}` : null, -1);
1045
+ clearTimeout(toastTimer);
1046
+ const ids = api$1.unread().map((e) => e.id);
1047
+ if (dismissed && (!unread || ids.some((id) => !dismissed.has(id)))) dismissed = null;
1048
+ if (dismissed) unreadToast.hide();
1049
+ else if (!unread) unreadToast.hide();
1050
+ else if (unreadShown) unreadToast.update(`→ unread (${unread})`);
1051
+ else toastTimer = window.setTimeout(() => {
1052
+ const left = api$1.unread().length;
1053
+ if (!left) return;
1054
+ unreadToast.update(`→ unread (${left})`);
1055
+ unreadToast.show();
1056
+ unreadShown = true;
1057
+ }, 1e3);
1058
+ if (!unread) unreadShown = false;
1059
+ if (arriving && n) {
1060
+ arriving = false;
1061
+ history.replaceState(history.state, "", location.pathname + location.search);
1062
+ requestAnimationFrame(() => {
1063
+ const first = targets()[0];
1064
+ if (first) jumpTo(first);
1065
+ });
1066
+ }
1067
+ }
1068
+ let arriving = location.hash === WAITING_HASH;
1069
+ setTimeout(() => {
1070
+ arriving = false;
1071
+ }, 5e3);
1072
+ let current = null;
1073
+ let scrolledTo = 0;
1074
+ function next(list) {
1075
+ const i = current ? list.indexOf(current) : -1;
1076
+ if (i >= 0 && Math.abs(scrollY - scrolledTo) < 40) return list[(i + 1) % list.length];
1077
+ return list.find((f) => f.getBoundingClientRect().top > viewBottom() / 2) ?? list[0];
1078
+ }
1079
+ function jump(what) {
1080
+ const target = next(what === "messages" ? targets("messages") : inState("open"));
1081
+ if (target) jumpTo(target);
1082
+ }
1083
+ function jumpTo(target) {
1084
+ current = target;
1085
+ const r = target.getBoundingClientRect();
1086
+ scrolledTo = Math.max(0, Math.min(scrollY + r.top + r.height / 2 - viewBottom() / 2, document.documentElement.scrollHeight - innerHeight));
1087
+ scrollTo({
1088
+ top: scrolledTo,
1089
+ behavior: "smooth"
1090
+ });
1091
+ if (target instanceof HTMLFormElement) {
1092
+ if (target.hasAttribute("data-wp-open")) target.querySelector("input:not([type=hidden]), textarea, select, button")?.focus({ preventScroll: true });
1093
+ } else target.dispatchEvent(new CustomEvent("wp-reveal", { bubbles: true }));
1094
+ }
1095
+ function trackWaiting(root, core) {
1096
+ main$2 = root;
1097
+ api$1 = core;
1098
+ waitingToast = api$1.toast("", {
1099
+ ms: 0,
1100
+ name: "waiting",
1101
+ order: -2,
1102
+ onClick: () => jump("open")
1103
+ });
1104
+ unreadToast = api$1.toast("", {
1105
+ ms: 0,
1106
+ name: "unread",
1107
+ order: -1,
1108
+ onClick: () => jump("messages"),
1109
+ onDismiss: () => {
1110
+ dismissed = new Set(api$1.unread().map((e) => e.id));
1111
+ unreadShown = false;
1112
+ }
1113
+ });
1114
+ waitingToast.hide();
1115
+ unreadToast.hide();
1116
+ main$2.addEventListener("click", (e) => {
1117
+ const target = e.target;
1118
+ const form = target.closest("form[data-wp-folded]");
1119
+ if (!form || target.closest("[data-block=chat-thread]")) return;
1120
+ e.preventDefault();
1121
+ if (target.closest(".wp-folded-chat")) {
1122
+ const name = form.getAttribute("name");
1123
+ if (chatsOpen.has(name) || form.hasAttribute("data-wp-chat-open")) {
1124
+ chatsOpen.delete(name);
1125
+ form.removeAttribute("data-wp-chat-open");
1126
+ } else chatsOpen.add(name);
1127
+ show(forms);
1128
+ return;
1129
+ }
1130
+ const name = form.getAttribute("name");
1131
+ const last = api$1.last(name);
1132
+ if (last) reopened.set(name, last.id);
1133
+ show(forms);
1134
+ form.querySelector("input:not([type=hidden]), textarea, select")?.focus({ preventScroll: true });
1135
+ });
1136
+ main$2.addEventListener("wp-reveal", (e) => {
1137
+ const target = e.target;
1138
+ const form = target.closest("form[data-wp-folded]");
1139
+ if (!form || !target.closest("[data-block=chat-thread]")) return;
1140
+ chatsOpen.add(form.getAttribute("name"));
1141
+ show(forms);
1142
+ });
1143
+ api$1.forms.on(show);
1144
+ api$1.events.on(() => show());
1145
+ show(api$1.forms());
1146
+ document.addEventListener("submit", (e) => {
1147
+ const form = e.target;
1148
+ const name = form.getAttribute("name");
1149
+ if (!name || !main$2.contains(form) || !forms.some((f) => f.form === form)) return;
1150
+ if (api$1.listeners().some((l) => l.type === name || l.type === null)) return;
1151
+ const sent = new MutationObserver(() => {
1152
+ if (form.dataset.wpState === "sending") return;
1153
+ sent.disconnect();
1154
+ if (form.dataset.wpState !== "sent") return;
1155
+ api$1.toast("Sent · nobody listening", {
1156
+ kind: "warn",
1157
+ name: "sent",
1158
+ details: "Your answer stays in the log until someone listens on this page."
1159
+ });
1160
+ });
1161
+ sent.observe(form, {
1162
+ attributes: true,
1163
+ attributeFilter: ["data-wp-state"]
1164
+ });
1165
+ }, { capture: true });
1166
+ }
1167
+ // src/client/page/live.ts
1168
+ /** A button that copies an agent's id, a check for a moment once it did. */
1169
+ function copyButton(id) {
1170
+ const button = document.createElement("button");
1171
+ button.type = "button";
1172
+ button.className = "wp-listeners-copy";
1173
+ button.title = "copy id";
1174
+ button.setAttribute("aria-label", `copy id ${id}`);
1175
+ button.innerHTML = COPY_ICON;
1176
+ button.addEventListener("click", async (e) => {
1177
+ e.stopPropagation();
1178
+ try {
1179
+ await navigator.clipboard.writeText(id);
1180
+ button.innerHTML = CHECK_ICON;
1181
+ button.dataset.copied = "";
1182
+ setTimeout(() => {
1183
+ button.innerHTML = COPY_ICON;
1184
+ delete button.dataset.copied;
1185
+ }, 1200);
1186
+ } catch {
1187
+ button.title = "could not copy";
1188
+ }
1189
+ });
1190
+ return button;
1191
+ }
1192
+ function trackLive(root, handle, api) {
1193
+ const dot = root.querySelector(".wp-live");
1194
+ if (!dot) return;
1195
+ const hasAnswers = handle.kind === "page" || handle.kind === "file";
1196
+ const show = () => {
1197
+ const live = document.documentElement.hasAttribute("data-wp-live");
1198
+ const listeners = hasAnswers ? whoListens(api.listeners()) : [];
1199
+ const agent = live && listeners.length > 0;
1200
+ dot.toggleAttribute("data-agent", agent);
1201
+ dot.title = !live ? "Reconnecting… the page may be out of date" : !hasAnswers ? "Live" : listeners.length ? `Live · ${listeners.length === 1 ? "one listens" : `${listeners.length} listen`} on this page` : "Live · nobody is listening right now; answers wait in the log";
1202
+ dot.setAttribute("aria-label", dot.title);
1203
+ };
1204
+ api.listeners.on(show);
1205
+ new MutationObserver(show).observe(document.documentElement, {
1206
+ attributes: true,
1207
+ attributeFilter: ["data-wp-live"]
1208
+ });
1209
+ show();
1210
+ if (hasAnswers) listenersPopup(dot, api);
1211
+ }
1212
+ /**
1213
+ * Who listens, one each: an agent listening several ways (its channel, a `listen` it ran besides)
1214
+ * is one agent; an unnamed process is one of its own.
1215
+ */
1216
+ const whoListens = (listeners) => {
1217
+ const seen = /* @__PURE__ */ new Set();
1218
+ return listeners.filter((l) => !l.agent || !seen.has(l.agent) && !!seen.add(l.agent));
1219
+ };
1220
+ /** The dot as a button: a click opens the list of who listens on the page, kept up to date while open. */
1221
+ function listenersPopup(dot, api) {
1222
+ dot.setAttribute("role", "button");
1223
+ dot.tabIndex = 0;
1224
+ const box = document.createElement("div");
1225
+ box.className = "wp-listeners";
1226
+ box.popover = "auto";
1227
+ document.body.append(box);
1228
+ const render = () => {
1229
+ const listeners = whoListens(api.listeners());
1230
+ box.replaceChildren();
1231
+ const title = document.createElement("div");
1232
+ title.className = "wp-listeners-title";
1233
+ title.textContent = listeners.length ? "Listening on this page" : "Nobody is listening";
1234
+ box.append(title);
1235
+ if (!listeners.length) {
1236
+ const p = document.createElement("p");
1237
+ p.textContent = "Answers wait in the log for whoever listens next.";
1238
+ box.append(p);
1239
+ return;
1240
+ }
1241
+ const list = document.createElement("ul");
1242
+ for (const l of listeners) {
1243
+ const li = document.createElement("li");
1244
+ const name = document.createElement("span");
1245
+ name.className = "wp-listeners-who";
1246
+ name.textContent = l.name ?? l.agent ?? "unnamed";
1247
+ li.title = l.agent ?? "listening without --agent, WORKPAD_AGENT or an agent plugin naming it";
1248
+ li.append(name);
1249
+ if (l.agent) {
1250
+ const button = copyButton(l.agent);
1251
+ li.append(button);
1252
+ li.dataset.copy = "";
1253
+ li.addEventListener("click", () => button.click());
1254
+ }
1255
+ list.append(li);
1256
+ }
1257
+ box.append(list);
1258
+ };
1259
+ const place = () => {
1260
+ const r = dot.getBoundingClientRect();
1261
+ const edge = 16 + (innerWidth - document.documentElement.clientWidth);
1262
+ box.style.top = `${r.bottom + 14}px`;
1263
+ box.style.left = `${Math.max(edge, Math.min(r.right - box.offsetWidth + 12, innerWidth - box.offsetWidth - edge))}px`;
1264
+ };
1265
+ const toggle = () => {
1266
+ if (box.matches(":popover-open")) return box.hidePopover();
1267
+ render();
1268
+ box.showPopover();
1269
+ place();
1270
+ };
1271
+ dot.addEventListener("click", toggle);
1272
+ dot.addEventListener("keydown", (e) => {
1273
+ if (e.key === "Enter" || e.key === " ") {
1274
+ e.preventDefault();
1275
+ toggle();
1276
+ }
1277
+ });
1278
+ api.listeners.on(() => {
1279
+ if (box.matches(":popover-open")) render();
1280
+ });
1281
+ }
1282
+ // src/client/page/sort.ts
1283
+ const KEY$1 = (name) => storageKey(`wp-sort:${name}`);
1284
+ function sortList(select) {
1285
+ const list = select.closest("section")?.querySelector("ul");
1286
+ if (!list) return;
1287
+ const by = select.value;
1288
+ const value = (li) => by === "title" ? li.dataset.title ?? "" : Number(by === "updated" ? li.dataset.updated : li.dataset.order);
1289
+ const rows = [...list.children];
1290
+ rows.sort((a, b) => {
1291
+ const x = value(a), y = value(b);
1292
+ if (by === "updated") return y - x;
1293
+ return typeof x === "string" ? x.localeCompare(y) : x - y;
1294
+ });
1295
+ list.append(...rows);
1296
+ }
1297
+ function applySorts() {
1298
+ for (const select of document.querySelectorAll("select[data-wp-sort]")) {
1299
+ let kept = null;
1300
+ try {
1301
+ kept = localStorage.getItem(KEY$1(select.dataset.wpSort));
1302
+ } catch {}
1303
+ if (kept && [...select.options].some((o) => o.value === kept)) select.value = kept;
1304
+ sortList(select);
1305
+ }
1306
+ }
1307
+ function trackSorts() {
1308
+ document.addEventListener("change", (e) => {
1309
+ const select = e.target;
1310
+ if (!select.matches?.("select[data-wp-sort]")) return;
1311
+ try {
1312
+ localStorage.setItem(KEY$1(select.dataset.wpSort), select.value);
1313
+ } catch {}
1314
+ sortList(select);
1315
+ });
1316
+ applySorts();
1317
+ }
1318
+ // src/client/page/board.ts
1319
+ const KEY = storageKey("wp-board");
1320
+ const VIEWS = ["state", "project"];
1321
+ const isView = (v) => VIEWS.includes(v);
1322
+ function chosen() {
1323
+ const asked = new URLSearchParams(location.search).get("columns");
1324
+ if (isView(asked)) return asked;
1325
+ try {
1326
+ const kept = localStorage.getItem(KEY);
1327
+ if (isView(kept)) return kept;
1328
+ } catch {}
1329
+ return "state";
1330
+ }
1331
+ /** Show `view`, and say which on the switch (written again by a live update, so asked each time). */
1332
+ function applyBoard(view = document.documentElement.dataset.wpBoard ?? chosen()) {
1333
+ if (!document.querySelector(".wp-board")) return;
1334
+ document.documentElement.dataset.wpBoard = view;
1335
+ for (const b of document.querySelectorAll("button[data-wp-board]")) b.setAttribute("aria-pressed", String(b.dataset.wpBoard === view));
1336
+ }
1337
+ let query = new URLSearchParams(location.search).get("q") ?? "";
1338
+ const ITEMS = ".wp-board-card, .wp-folded-documents .wp-index li, .wp-board-empty li";
1339
+ /** Narrow the overview to `query` (all of it with none); asked again after each live update. */
1340
+ function applySearch() {
1341
+ const input = document.querySelector(".wp-board-search");
1342
+ if (!input) return;
1343
+ if (input.value !== query && document.activeElement !== input) input.value = query;
1344
+ const words = query.toLowerCase().split(/\s+/).filter(Boolean);
1345
+ const hit = (text) => words.every((w) => text.includes(w));
1346
+ document.documentElement.toggleAttribute("data-wp-searching", words.length > 0);
1347
+ for (const board of document.querySelectorAll(".wp-board")) {
1348
+ let columns = 0;
1349
+ for (const col of board.querySelectorAll(":scope > .wp-board-column")) {
1350
+ const head = (col.querySelector(".wp-board-head, :scope > summary")?.textContent ?? "").toLowerCase();
1351
+ const whole = words.length > 0 && hit(head);
1352
+ let shown = 0;
1353
+ for (const item of col.querySelectorAll(ITEMS)) {
1354
+ const show = !words.length || whole || hit(`${item.textContent ?? ""} ${head}`.toLowerCase());
1355
+ item.hidden = !show;
1356
+ if (show) shown++;
1357
+ }
1358
+ const folds = [...col.querySelectorAll("details")];
1359
+ if (col instanceof HTMLDetailsElement) folds.unshift(col);
1360
+ for (const d of folds) {
1361
+ const has = [...d.querySelectorAll(ITEMS)].some((i) => !i.hidden);
1362
+ if (words.length && has && !d.open) {
1363
+ d.open = true;
1364
+ d.dataset.wpSearchOpened = "";
1365
+ } else if ((!words.length || !has) && "wpSearchOpened" in d.dataset) {
1366
+ d.open = false;
1367
+ delete d.dataset.wpSearchOpened;
1368
+ }
1369
+ }
1370
+ col.hidden = words.length > 0 && !whole && shown === 0;
1371
+ if (!col.hidden) columns++;
1372
+ }
1373
+ board.dataset.wpMatches = String(columns);
1374
+ }
1375
+ const none = document.querySelector(".wp-board-nomatch");
1376
+ const current = document.querySelector(`.wp-board[data-board="${document.documentElement.dataset.wpBoard ?? "state"}"]`);
1377
+ if (none) none.hidden = !words.length || current?.dataset.wpMatches !== "0";
1378
+ }
1379
+ function setQuery(q) {
1380
+ query = q;
1381
+ const url = new URL(location.href);
1382
+ if (q) url.searchParams.set("q", q);
1383
+ else url.searchParams.delete("q");
1384
+ history.replaceState(history.state, "", url);
1385
+ applySearch();
1386
+ }
1387
+ function trackSearch() {
1388
+ document.addEventListener("input", (e) => {
1389
+ const input = e.target;
1390
+ if (input.matches?.(".wp-board-search")) setQuery(input.value);
1391
+ });
1392
+ document.addEventListener("keydown", (e) => {
1393
+ const input = document.querySelector(".wp-board-search");
1394
+ if (!input) return;
1395
+ const typing = e.target.closest?.("input, textarea, select, [contenteditable]");
1396
+ if (e.key === "/" && !typing && !e.metaKey && !e.ctrlKey && !e.altKey) {
1397
+ e.preventDefault();
1398
+ input.focus();
1399
+ input.select();
1400
+ } else if (e.key === "Escape" && e.target === input) {
1401
+ input.value = "";
1402
+ setQuery("");
1403
+ input.blur();
1404
+ }
1405
+ });
1406
+ applySearch();
1407
+ }
1408
+ function trackBoard() {
1409
+ document.addEventListener("click", (e) => {
1410
+ const view = (e.target.closest?.("button[data-wp-board]"))?.dataset.wpBoard;
1411
+ if (!isView(view)) return;
1412
+ try {
1413
+ localStorage.setItem(KEY, view);
1414
+ } catch {}
1415
+ const url = new URL(location.href);
1416
+ if (view === "state") url.searchParams.delete("columns");
1417
+ else url.searchParams.set("columns", view);
1418
+ history.replaceState(history.state, "", url);
1419
+ applyBoard(view);
1420
+ applySearch();
1421
+ });
1422
+ document.addEventListener("toggle", (e) => {
1423
+ const fold = e.target;
1424
+ if (fold.dataset?.wpFiles && fold.open) loadFiles(fold);
1425
+ }, true);
1426
+ applyBoard(chosen());
1427
+ trackSearch();
1428
+ }
1429
+ async function loadFiles(fold) {
1430
+ if (fold.dataset.wpLoaded) return;
1431
+ fold.dataset.wpLoaded = "loading";
1432
+ const count = fold.querySelector("summary .wp-meta");
1433
+ if (count) count.textContent = "…";
1434
+ try {
1435
+ const res = await fetch(`/api/files?base=${encodeURIComponent(fold.dataset.wpFiles)}`);
1436
+ const body = await res.json();
1437
+ if (!res.ok) throw new Error(body.error ?? res.statusText);
1438
+ if (count) count.textContent = String(body.count);
1439
+ fold.insertAdjacentHTML("beforeend", body.count ? body.html : "<p class=\"wp-meta\">No markdown files.</p>");
1440
+ fold.dataset.wpLoaded = "yes";
1441
+ applySearch();
1442
+ } catch (err) {
1443
+ delete fold.dataset.wpLoaded;
1444
+ if (count) count.textContent = "";
1445
+ fold.insertAdjacentHTML("beforeend", `<p class="wp-meta">Couldn't list the files: ${String(err.message)}</p>`);
1446
+ }
1447
+ }
1448
+ // src/client/page/sticky.ts
1449
+ function place$1(body) {
1450
+ const nav = document.querySelector(".wp-nav");
1451
+ const base = nav ? nav.getBoundingClientRect().height : 0;
1452
+ for (const summary of body.querySelectorAll("details > summary")) {
1453
+ let top = base, depth = 0;
1454
+ for (let d = summary.parentElement.parentElement?.closest("details"); d && body.contains(d); d = d.parentElement?.closest("details")) {
1455
+ const outer = d.querySelector(":scope > summary");
1456
+ if (outer && d.open) top += outer.getBoundingClientRect().height;
1457
+ depth++;
1458
+ }
1459
+ summary.style.setProperty("--wp-sticky-top", `${top}px`);
1460
+ summary.style.setProperty("--wp-sticky-z", String(Math.max(1, 4 - depth)));
1461
+ }
1462
+ }
1463
+ /** A click on a stuck title: once its details has closed, the title where it was stuck. */
1464
+ function keepTitle(e) {
1465
+ const summary = e.target.closest?.("summary");
1466
+ const details = summary?.parentElement;
1467
+ if (!summary || !(details instanceof HTMLDetailsElement) || !details.open) return;
1468
+ const top = parseFloat(summary.style.getPropertyValue("--wp-sticky-top")) || 0;
1469
+ if (details.getBoundingClientRect().top >= top - 1) return;
1470
+ requestAnimationFrame(() => scrollBy({ top: details.getBoundingClientRect().top - top }));
1471
+ }
1472
+ function trackSticky(main, onRendered) {
1473
+ const body = main.closest(".wp-body") ?? main;
1474
+ body.addEventListener("click", keepTitle);
1475
+ let frame = 0;
1476
+ const later = () => {
1477
+ cancelAnimationFrame(frame);
1478
+ frame = requestAnimationFrame(() => place$1(body));
1479
+ };
1480
+ body.addEventListener("toggle", later, true);
1481
+ addEventListener("resize", later);
1482
+ onRendered(later);
1483
+ new MutationObserver(later).observe(body, {
1484
+ childList: true,
1485
+ subtree: true
1486
+ });
1487
+ place$1(body);
1488
+ }
1489
+ // src/client/page/place.ts
1490
+ let main$1;
1491
+ let place = null;
1492
+ /** The control of the page the reader last clicked or changed. */
1493
+ let used = null;
1494
+ const typing = (el) => el instanceof HTMLElement && el.matches("input:not([type=radio], [type=checkbox], [type=button], [type=submit]), textarea, select, [contenteditable]");
1495
+ /** Laid out: not inside a closed <details> or otherwise not drawn. */
1496
+ const shown = (el) => el.isConnected && el.getClientRects().length > 0;
1497
+ /** The top of the view, below the header (which sticks there). */
1498
+ function viewTop() {
1499
+ return Math.max(0, document.querySelector(".wp-nav")?.getBoundingClientRect().bottom ?? 0);
1500
+ }
1501
+ /** A sticky title (an open details' summary) stays at the top while what is under it moves: never the place. */
1502
+ const stuck = (el) => {
1503
+ const position = getComputedStyle(el).position;
1504
+ return position === "sticky" || position === "fixed";
1505
+ };
1506
+ /** The middle of the view, below the header: where the reader reads. */
1507
+ const viewMiddle = () => (viewTop() + innerHeight) / 2;
1508
+ /** The innermost element at height `y` of the view: the first one reaching below it, and inside it, the same. */
1509
+ function atLine(y) {
1510
+ let found = null;
1511
+ for (let parent = main$1;;) {
1512
+ const next = [...parent.children].find((c) => {
1513
+ if (stuck(c)) return false;
1514
+ const r = c.getBoundingClientRect();
1515
+ return r.height > 0 && r.bottom > y;
1516
+ });
1517
+ if (!next) return found;
1518
+ found = next;
1519
+ if (next.getBoundingClientRect().top >= y) return found;
1520
+ parent = next;
1521
+ }
1522
+ }
1523
+ /** The elements around `el` in the page's content, innermost first, and where each is now. */
1524
+ function aroundOf(el) {
1525
+ const around = [];
1526
+ for (let at = el.parentElement; at && at !== main$1 && main$1.contains(at); at = at.parentElement) around.push({
1527
+ el: at,
1528
+ top: at.getBoundingClientRect().top
1529
+ });
1530
+ return around;
1531
+ }
1532
+ const placeAt = (el, top = el.getBoundingClientRect().top) => ({
1533
+ el,
1534
+ top,
1535
+ scrolled: scrollY,
1536
+ around: aroundOf(el)
1537
+ });
1538
+ /** In view, below the header: some of it between the top of the view and its bottom. */
1539
+ function inView$1(el) {
1540
+ const r = el.getBoundingClientRect();
1541
+ return r.bottom > viewTop() && r.top < innerHeight;
1542
+ }
1543
+ /**
1544
+ * What the reader is on: the field they type in, else the control they last used, each while in
1545
+ * view. Scrolled away from it (a chat box keeps the focus), they read elsewhere: the middle then.
1546
+ */
1547
+ function onNow() {
1548
+ const focused = document.activeElement;
1549
+ if (typing(focused) && shown(focused) && inView$1(focused)) return focused;
1550
+ for (const el of [focused, used]) if (el instanceof HTMLElement && el !== document.body && main$1.contains(el) && shown(el) && inView$1(el)) return el;
1551
+ return null;
1552
+ }
1553
+ function pick() {
1554
+ const el = onNow() ?? (scrollY > 0 ? atLine(viewMiddle()) : null);
1555
+ place = el ? placeAt(el) : null;
1556
+ }
1557
+ /** Put the place back where it was on screen, if it moved; then it is where it is. */
1558
+ function keep() {
1559
+ if (!place || place.scrolled !== scrollY) return pick();
1560
+ if (!shown(place.el)) {
1561
+ const held = place.el.isConnected ? null : place.around.find((a) => shown(a.el));
1562
+ if (held) {
1563
+ const moved = held.el.getBoundingClientRect().top - held.top;
1564
+ if (Math.abs(moved) >= 1) scrollBy(0, moved);
1565
+ }
1566
+ return pick();
1567
+ }
1568
+ const moved = place.el.getBoundingClientRect().top - place.top;
1569
+ if (Math.abs(moved) >= 1) {
1570
+ scrollBy(0, moved);
1571
+ place.scrolled = scrollY;
1572
+ const now = place.el.getBoundingClientRect().top;
1573
+ if (Math.abs(now - place.top) >= 1) place.top = now;
1574
+ }
1575
+ place.around = aroundOf(place.el);
1576
+ }
1577
+ /** The top-level block an element is in, and the way down to it: the index of each child taken. */
1578
+ function pathOf(el) {
1579
+ const path = [];
1580
+ let at = el;
1581
+ while (at.parentElement && at.parentElement !== main$1) {
1582
+ path.unshift([...at.parentElement.children].indexOf(at));
1583
+ at = at.parentElement;
1584
+ }
1585
+ return at.parentElement === main$1 ? {
1586
+ block: [...main$1.children].indexOf(at),
1587
+ path
1588
+ } : null;
1589
+ }
1590
+ /** Which of the blocks with its signature block `i` is. */
1591
+ const nthOf = (sigs, i) => sigs.slice(0, i).filter((s) => s === sigs[i]).length;
1592
+ /** The index of the `nth` block with signature `sig`, or -1. */
1593
+ function indexOf(sigs, sig, nth) {
1594
+ let seen = 0;
1595
+ return sigs.findIndex((s) => s === sig && seen++ === nth);
1596
+ }
1597
+ /**
1598
+ * Before a page update that turns blocks with signatures `from` into `to`: note the place, and how to
1599
+ * find it if the update replaces it. Call what it returns once the update is in.
1600
+ */
1601
+ function beforeUpdate(from, to) {
1602
+ const focused = document.activeElement;
1603
+ if (focused instanceof HTMLElement && focused !== document.body && main$1.contains(focused) && shown(focused) && inView$1(focused)) place = placeAt(focused);
1604
+ else pick();
1605
+ const before = place;
1606
+ const at = before && main$1.contains(before.el) ? pathOf(before.el) : null;
1607
+ const blockTop = at ? main$1.children[at.block].getBoundingClientRect().top : 0;
1608
+ return () => {
1609
+ if (!before) return pick();
1610
+ if (before.el.isConnected) {
1611
+ place = before;
1612
+ return keep();
1613
+ }
1614
+ const now = document.activeElement;
1615
+ if (before.el === focused && now instanceof HTMLElement && now !== document.body && main$1.contains(now)) {
1616
+ place = {
1617
+ ...placeAt(now, before.top),
1618
+ scrolled: before.scrolled
1619
+ };
1620
+ return keep();
1621
+ }
1622
+ if (!at) return pick();
1623
+ const keptTo = new Set(to);
1624
+ let block = keptTo.has(from[at.block]) ? indexOf(to, from[at.block], nthOf(from, at.block)) : -1;
1625
+ if (block < 0) {
1626
+ let prev = at.block - 1;
1627
+ while (prev >= 0 && !keptTo.has(from[prev])) prev--;
1628
+ const base = prev < 0 ? -1 : indexOf(to, from[prev], nthOf(from, prev));
1629
+ if (prev < 0 || base >= 0) block = base + (at.block - prev);
1630
+ }
1631
+ const el = main$1.children[block];
1632
+ if (!el) return pick();
1633
+ let target = el;
1634
+ let whole = true;
1635
+ for (const i of at.path) {
1636
+ const child = target.children[i];
1637
+ if (!child) {
1638
+ whole = false;
1639
+ break;
1640
+ }
1641
+ target = child;
1642
+ }
1643
+ place = {
1644
+ ...whole ? placeAt(target, before.top) : placeAt(el, blockTop),
1645
+ scrolled: before.scrolled
1646
+ };
1647
+ keep();
1648
+ };
1649
+ }
1650
+ function trackPlace(root) {
1651
+ main$1 = root;
1652
+ document.documentElement.style.overflowAnchor = "none";
1653
+ addEventListener("scroll", keep, { passive: true });
1654
+ addEventListener("resize", pick);
1655
+ const use = (e) => {
1656
+ const el = e.target instanceof Element ? e.target.closest("input, button, select, textarea, label, summary") : null;
1657
+ if (!el || !main$1.contains(el)) return;
1658
+ used = el instanceof HTMLLabelElement && el.control && shown(el.control) ? el.control : el;
1659
+ pick();
1660
+ };
1661
+ document.addEventListener("click", use, true);
1662
+ document.addEventListener("change", use, true);
1663
+ document.addEventListener("focusin", pick);
1664
+ document.addEventListener("focusout", () => queueMicrotask(pick));
1665
+ let frames = 0;
1666
+ let frame = 0;
1667
+ const follow = () => {
1668
+ keep();
1669
+ frame = --frames > 0 ? requestAnimationFrame(follow) : 0;
1670
+ };
1671
+ const changed = () => {
1672
+ keep();
1673
+ frames = 30;
1674
+ if (!frame) frame = requestAnimationFrame(follow);
1675
+ };
1676
+ new MutationObserver(changed).observe(document.documentElement, {
1677
+ childList: true,
1678
+ subtree: true,
1679
+ characterData: true,
1680
+ attributes: true
1681
+ });
1682
+ document.addEventListener("load", changed, true);
1683
+ document.fonts?.addEventListener("loadingdone", changed);
1684
+ pick();
1685
+ }
1686
+ // src/client/page/window.ts
1687
+ const windows = () => [...document.querySelectorAll("#wp-main .wp-window")];
1688
+ let maximized = null;
1689
+ function apply() {
1690
+ const all = windows();
1691
+ if (maximized != null && !all[maximized]) maximized = null;
1692
+ all.forEach((win, i) => {
1693
+ const on = i === maximized;
1694
+ win.toggleAttribute("data-wp-maximized", on);
1695
+ const button = win.querySelector("[data-wp-maximize]");
1696
+ if (button) {
1697
+ button.title = on ? "Back into the page (Esc)" : "Fill the window";
1698
+ button.setAttribute("aria-label", button.title);
1699
+ button.setAttribute("aria-pressed", String(on));
1700
+ }
1701
+ });
1702
+ document.documentElement.toggleAttribute("data-wp-window-maximized", maximized != null);
1703
+ }
1704
+ function trackWindows(api) {
1705
+ document.addEventListener("click", (e) => {
1706
+ const win = e.target.closest?.("[data-wp-maximize]")?.closest(".wp-window");
1707
+ if (!win) return;
1708
+ const i = windows().indexOf(win);
1709
+ maximized = maximized === i ? null : i;
1710
+ apply();
1711
+ });
1712
+ document.addEventListener("keydown", (e) => {
1713
+ if (e.key === "Escape" && maximized != null) {
1714
+ maximized = null;
1715
+ apply();
1716
+ }
1717
+ });
1718
+ api.onRendered(apply);
1719
+ }
1720
+ // src/client/page/heading-link.ts
1721
+ /** The heading whose number was clicked, if the click was on one. */
1722
+ function numberOf(main, e) {
1723
+ const heading = e.target;
1724
+ if (!(heading instanceof HTMLElement) || heading.parentElement !== main) return null;
1725
+ if (!/^H[2-6]$/.test(heading.tagName) || !heading.id) return null;
1726
+ const range = document.createRange();
1727
+ range.selectNodeContents(heading);
1728
+ const first = range.getClientRects()[0];
1729
+ return first && e.clientX < first.left ? heading : null;
1730
+ }
1731
+ function trackHeadingLinks(main) {
1732
+ main.addEventListener("click", async (e) => {
1733
+ const heading = numberOf(main, e);
1734
+ if (!heading) return;
1735
+ const url = new URL(location.href);
1736
+ url.hash = heading.id;
1737
+ history.replaceState(history.state, "", url);
1738
+ try {
1739
+ await navigator.clipboard.writeText(url.href);
1740
+ heading.dataset.wpCopied = "";
1741
+ setTimeout(() => delete heading.dataset.wpCopied, 1200);
1742
+ } catch {}
1743
+ });
1744
+ }
1745
+ // src/client/read.ts
1746
+ let isMessage$1 = () => false;
1747
+ let getEvents = () => [];
1748
+ let chats = () => null;
1749
+ const sending = /* @__PURE__ */ new Set();
1750
+ const unread = () => unreadMessages(getEvents(), isMessage$1, chats()).filter((e) => !sending.has(e.id));
1751
+ /**
1752
+ * The chats the page's content shows, by name: the one under every form and each chat block; null
1753
+ * while there is no page content (a folder, raw text), when every chat's messages count.
1754
+ */
1755
+ function chatsShown() {
1756
+ const main = document.getElementById("wp-main");
1757
+ if (!main) return null;
1758
+ return new Set([...[...main.querySelectorAll("form[name]")].map((f) => f.getAttribute("name")), ...[...main.querySelectorAll("[data-chat]")].map((c) => c.getAttribute("data-chat"))].filter((name) => !!name));
1759
+ }
1760
+ const queued = /* @__PURE__ */ new Set();
1761
+ let timer = 0;
1762
+ function markRead(ids) {
1763
+ const open = new Set(unread().map((e) => e.id));
1764
+ const fresh = ids.filter((id) => open.has(id));
1765
+ if (!fresh.length) return;
1766
+ for (const id of fresh) {
1767
+ sending.add(id);
1768
+ queued.add(id);
1769
+ }
1770
+ clearTimeout(timer);
1771
+ timer = window.setTimeout(() => {
1772
+ const batch = [...queued];
1773
+ queued.clear();
1774
+ if (batch.length);
1775
+ }, 300);
1776
+ }
1777
+ const MOSTLY = .6;
1778
+ function mostlyInView(entry) {
1779
+ if (!entry.isIntersecting) return false;
1780
+ if (entry.intersectionRatio >= MOSTLY) return true;
1781
+ const viewport = entry.rootBounds?.height ?? window.innerHeight;
1782
+ return entry.intersectionRect.height >= MOSTLY * viewport;
1783
+ }
1784
+ const inView = /* @__PURE__ */ new Set();
1785
+ new IntersectionObserver((entries) => {
1786
+ for (const entry of entries) {
1787
+ const id = entry.target.dataset.wpMessage;
1788
+ if (mostlyInView(entry)) inView.add(id);
1789
+ else inView.delete(id);
1790
+ }
1791
+ readVisible();
1792
+ }, { threshold: Array.from({ length: 21 }, (_, i) => i / 20) });
1793
+ function readVisible() {
1794
+ if (document.visibilityState === "visible" && inView.size) markRead([...inView]);
1795
+ }
1796
+ // src/client/page/orphans.ts
1797
+ /** A message in a chat: the chat block's event. */
1798
+ const isMessage = (e) => e.type === "chat:message" && typeof e.data.chat === "string";
1799
+ function trackOrphanThreads(main, api) {
1800
+ const box = document.createElement("section");
1801
+ box.className = "wp-orphans";
1802
+ box.hidden = true;
1803
+ main.after(box);
1804
+ function draw() {
1805
+ const onPage = chatsShown() ?? /* @__PURE__ */ new Set();
1806
+ const threads = /* @__PURE__ */ new Map();
1807
+ for (const e of api.events()) {
1808
+ const chat = String(e.data.chat);
1809
+ if (!isMessage(e) || onPage.has(chat)) continue;
1810
+ threads.set(chat, [...threads.get(chat) ?? [], e]);
1811
+ }
1812
+ box.hidden = threads.size === 0;
1813
+ if (box.hidden) return box.replaceChildren();
1814
+ const open = box.querySelector("details")?.open ?? false;
1815
+ box.innerHTML = String(html`<details ${open ? raw("open") : ""}>
1816
+ <summary>${threads.size} chat${threads.size === 1 ? "" : "s"} no longer on this page</summary>
1817
+ ${[...threads].map(([chat, messages]) => {
1818
+ const replaced = new Set(messages.map((m) => m.data.replaces).filter(Boolean).map(String));
1819
+ return html`<div class="wp-orphan" data-chat="${chat}">
1820
+ <h3>${chat}</h3>
1821
+ ${messages.filter((m) => !replaced.has(m.id)).map((m) => {
1822
+ const who = m.from === "cli" ? "agent" : "you";
1823
+ return html`<div class="wp-orphan-message" data-from="${who}">
1824
+ <span class="wp-orphan-who">${who}</span
1825
+ ><span class="wp-orphan-text">${String(m.data.text ?? "")}</span>
1826
+ </div>`;
1827
+ })}
1828
+ </div>`;
1829
+ })}
1830
+ </details>`);
1831
+ }
1832
+ api.events.on(draw);
1833
+ api.onRendered(draw);
1834
+ draw();
1835
+ }
1836
+ // src/client/page/main.ts
1837
+ let main;
1838
+ let page = "";
1839
+ let api;
1840
+ let islands = {};
1841
+ const disposers = /* @__PURE__ */ new Map();
1842
+ async function mountOne(el) {
1843
+ const island = islands[el.dataset.wpIsland];
1844
+ el.dataset.wpMounted = "";
1845
+ if (!island) return;
1846
+ try {
1847
+ const mod = await import(new URL(island.client, document.baseURI).href);
1848
+ if (!el.isConnected) return;
1849
+ const mount = mod.default;
1850
+ if (typeof mount !== "function") throw new Error("the client module must export a mount(element, props, api) function as default");
1851
+ el.replaceChildren();
1852
+ const dispose = await mount(el, island.props, api);
1853
+ if (typeof dispose === "function") disposers.set(el, dispose);
1854
+ } catch (err) {
1855
+ console.error(`island ${island.block}:`, err);
1856
+ el.insertAdjacentHTML("afterbegin", String(html`<pre class="wp-error">block "${island.block}" failed to mount: ${err.message}</pre>`));
1857
+ }
1858
+ }
1859
+ /** Mount islands outermost first; nested islands show up once their parent has rendered. */
1860
+ async function mountIslands(root = main) {
1861
+ for (;;) {
1862
+ const pending = [...root.querySelectorAll("[data-wp-island]:not([data-wp-mounted])")].filter((el) => !el.parentElement?.closest("[data-wp-island]:not([data-wp-mounted])"));
1863
+ if (!pending.length) return;
1864
+ await Promise.all(pending.map(mountOne));
1865
+ }
1866
+ }
1867
+ function disposeWithin(node) {
1868
+ for (const [el, dispose] of disposers) if (node === el || node.contains(el)) {
1869
+ dispose();
1870
+ disposers.delete(el);
1871
+ }
1872
+ }
1873
+ const NEXT = {
1874
+ auto: "light",
1875
+ light: "dark",
1876
+ dark: "auto"
1877
+ };
1878
+ const svg = (d) => `<svg viewBox="0 0 16 16" width="13" height="13" aria-hidden="true">${d}</svg>`;
1879
+ const THEME_ICON = {
1880
+ auto: svg("<circle cx=\"8\" cy=\"8\" r=\"5.5\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.4\"/><path d=\"M8 2.5a5.5 5.5 0 0 1 0 11Z\" fill=\"currentColor\"/>"),
1881
+ light: svg("<circle cx=\"8\" cy=\"8\" r=\"2.8\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.4\"/><path d=\"M8 1.2v1.8M8 13v1.8M1.2 8H3M13 8h1.8M3.2 3.2l1.3 1.3M11.5 11.5l1.3 1.3M3.2 12.8l1.3-1.3M11.5 4.5l1.3-1.3\" stroke=\"currentColor\" stroke-width=\"1.4\" stroke-linecap=\"round\"/>"),
1882
+ dark: svg("<path d=\"M13.5 9.6A5.8 5.8 0 0 1 6.4 2.5a5.8 5.8 0 1 0 7.1 7.1Z\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.4\" stroke-linejoin=\"round\"/>")
1883
+ };
1884
+ const THEME_LABEL = {
1885
+ auto: "Theme: follows the system",
1886
+ light: "Theme: light",
1887
+ dark: "Theme: dark"
1888
+ };
1889
+ function themeToggle(root) {
1890
+ const button = root.querySelector(".wp-theme");
1891
+ if (!button) return;
1892
+ const show = () => {
1893
+ const pref = themePreference();
1894
+ button.innerHTML = THEME_ICON[pref];
1895
+ button.dataset.pref = pref;
1896
+ button.title = `${THEME_LABEL[pref]} (click for ${NEXT[pref]})`;
1897
+ button.setAttribute("aria-label", button.title);
1898
+ };
1899
+ show();
1900
+ button.addEventListener("click", () => {
1901
+ setThemePreference(NEXT[themePreference()]);
1902
+ show();
1903
+ });
1904
+ }
1905
+ function ago(ts) {
1906
+ const s = Math.round((Date.now() - ts) / 1e3);
1907
+ if (s < 10) return "just now";
1908
+ if (s < 60) return `${s}s ago`;
1909
+ if (s < 3600) return `${Math.round(s / 60)}m ago`;
1910
+ if (s < 86400) return `${Math.round(s / 3600)}h ago`;
1911
+ return new Date(ts).toLocaleDateString();
1912
+ }
1913
+ function tickTimes() {
1914
+ for (const t of document.querySelectorAll("time[data-ts]")) {
1915
+ const ts = Number(t.dataset.ts);
1916
+ t.textContent = ago(ts);
1917
+ t.title = new Date(ts).toLocaleString();
1918
+ }
1919
+ }
1920
+ let blockSigs = [];
1921
+ const FIELD = (n) => n instanceof HTMLInputElement || n instanceof HTMLTextAreaElement || n instanceof HTMLSelectElement;
1922
+ const KEEP_CLASSES = ["wp-new", "wp-new-seen"];
1923
+ /** Patch the page in place: focus, caret, typed values, open <details> and unchanged islands survive. */
1924
+ /**
1925
+ * A <details> element's identity across renders: its summary, the nearest heading above its
1926
+ * top-level block, and how many before it share both. Blocks are matched by position when the page
1927
+ * updates, so a block inserted above an open section would otherwise pair it with a different
1928
+ * element and close it; this finds the same section wherever it moved.
1929
+ */
1930
+ function detailsKeys(root) {
1931
+ const keys = /* @__PURE__ */ new Map();
1932
+ const seen = /* @__PURE__ */ new Map();
1933
+ for (const el of root.querySelectorAll("details")) {
1934
+ let block = el;
1935
+ while (block.parentElement && block.parentElement !== root) block = block.parentElement;
1936
+ let heading = "";
1937
+ for (let b = block; b; b = b.previousElementSibling) if (/^H[1-6]$/.test(b.tagName)) {
1938
+ heading = b.textContent?.trim() ?? "";
1939
+ break;
1940
+ }
1941
+ const base = `${heading}\u0000${el.querySelector(":scope > summary")?.textContent?.trim() ?? ""}`;
1942
+ const n = seen.get(base) ?? 0;
1943
+ seen.set(base, n + 1);
1944
+ keys.set(el, `${base}\u0000${n}`);
1945
+ }
1946
+ return keys;
1947
+ }
1948
+ /** Each block's key: its signature, and which of the blocks with that signature it is. */
1949
+ function keyBlocks(parent, sigs) {
1950
+ const seen = /* @__PURE__ */ new Map();
1951
+ [...parent.children].forEach((el, i) => {
1952
+ const sig = sigs[i];
1953
+ if (!sig) return;
1954
+ const nth = seen.get(sig) ?? 0;
1955
+ seen.set(sig, nth + 1);
1956
+ el.dataset.wpBlock = `${sig}#${nth}`;
1957
+ });
1958
+ }
1959
+ /** What has the focus, to give it back if the patch took it: the element, its caret, and how to find it again. */
1960
+ function focusOf() {
1961
+ const el = document.activeElement;
1962
+ if (!el || el === document.body || !main.contains(el)) return null;
1963
+ const form = el.closest("form")?.getAttribute("name");
1964
+ let start = null, end = null;
1965
+ try {
1966
+ start = el.selectionStart;
1967
+ end = el.selectionEnd;
1968
+ } catch {}
1969
+ return {
1970
+ el,
1971
+ form,
1972
+ name: el.getAttribute("name"),
1973
+ start,
1974
+ end
1975
+ };
1976
+ }
1977
+ function giveFocusBack(f) {
1978
+ if (!f || document.activeElement === f.el) return;
1979
+ let el = f.el.isConnected ? f.el : null;
1980
+ if (!el && f.form && f.name) el = main.querySelector(`form[name="${CSS.escape(f.form)}"] [name="${CSS.escape(f.name)}"]`);
1981
+ if (!el) return;
1982
+ el.focus({ preventScroll: true });
1983
+ if (f.start != null && "setSelectionRange" in el) try {
1984
+ el.setSelectionRange(f.start, f.end ?? f.start);
1985
+ } catch {}
1986
+ }
1987
+ /** Are two elements, before and after a patch, the same field of the same form? */
1988
+ function sameField(from, to) {
1989
+ if (from.tagName !== to.tagName || from.getAttribute("name") !== to.getAttribute("name")) return false;
1990
+ const formOf = (el) => el.closest("form")?.getAttribute("name") ?? null;
1991
+ if (formOf(from) !== formOf(to)) return false;
1992
+ const type = from.getAttribute("type");
1993
+ if ((type === "radio" || type === "checkbox") && (to.getAttribute("type") !== type || from.getAttribute("value") !== to.getAttribute("value"))) return false;
1994
+ return true;
1995
+ }
1996
+ function morph(html, sigs) {
1997
+ const open = /* @__PURE__ */ new Set();
1998
+ for (const [el, key] of detailsKeys(main)) if (el.open) open.add(key);
1999
+ const focus = focusOf();
2000
+ const next = main.cloneNode(false);
2001
+ next.innerHTML = html;
2002
+ keyBlocks(main, sigs.from);
2003
+ keyBlocks(next, sigs.to);
2004
+ for (const [el, key] of detailsKeys(next)) el.open = open.has(key);
2005
+ morphdom(main, next, {
2006
+ getNodeKey: (n) => n.dataset?.wpKey || n.dataset?.wpBlock || n.id || void 0,
2007
+ onBeforeElUpdated(from, to) {
2008
+ if (from.dataset.wpKey) {
2009
+ if (from.dataset.wpKey === to.dataset.wpKey && "wpMounted" in from.dataset) {
2010
+ from.dataset.wpIsland = to.dataset.wpIsland;
2011
+ return false;
2012
+ }
2013
+ disposeWithin(from);
2014
+ }
2015
+ if (FIELD(from)) {
2016
+ if (from === document.activeElement) return false;
2017
+ if (sameField(from, to)) {
2018
+ to.value = from.value;
2019
+ if (from instanceof HTMLInputElement) to.checked = from.checked;
2020
+ }
2021
+ }
2022
+ for (const { name, value } of [...from.attributes]) if (name.startsWith("data-wp-") && name !== "data-wp-mounted" && !to.hasAttribute(name)) to.setAttribute(name, value);
2023
+ for (const c of KEEP_CLASSES) if (from.classList.contains(c)) to.classList.add(c);
2024
+ return true;
2025
+ }
2026
+ });
2027
+ for (const [el, dispose] of disposers) if (!el.isConnected) {
2028
+ dispose();
2029
+ disposers.delete(el);
2030
+ }
2031
+ giveFocusBack(focus);
2032
+ }
2033
+ /** The new render of the page, patched in. */
2034
+ let leaving = false;
2035
+ addEventListener("pagehide", () => {
2036
+ leaving = true;
2037
+ });
2038
+ async function refresh() {
2039
+ let next;
2040
+ try {
2041
+ next = await currentPage.render();
2042
+ } catch (err) {
2043
+ if (leaving) return;
2044
+ if (/: 404$/.test(err.message)) {
2045
+ if (currentPage.data()?.mtime == null) return;
2046
+ leaving = true;
2047
+ return location.reload();
2048
+ }
2049
+ throw err;
2050
+ }
2051
+ const data = next.data;
2052
+ islands = data.islands;
2053
+ for (const href of data.styles) if (![...document.querySelectorAll("link[rel=stylesheet]")].some((l) => new URL(l.href).pathname === new URL(href, location.href).pathname)) document.head.insertAdjacentHTML("beforeend", String(html`<link rel="stylesheet" href="${href}" />`));
2054
+ const content = new DOMParser().parseFromString(next.html, "text/html").getElementById("wp-main")?.innerHTML ?? "";
2055
+ const nextSigs = signaturesOf(content);
2056
+ const restorePlace = beforeUpdate(blockSigs, nextSigs);
2057
+ morph(content, {
2058
+ from: blockSigs,
2059
+ to: nextSigs
2060
+ });
2061
+ applySorts();
2062
+ applyBoard();
2063
+ applySearch();
2064
+ restorePlace();
2065
+ const updated = document.getElementById("wp-updated");
2066
+ if (updated && data.mtime) updated.dataset.ts = String(data.mtime);
2067
+ if (next.title) core.title(next.title);
2068
+ trackUpdate(main, blockSigs, nextSigs);
2069
+ blockSigs = nextSigs;
2070
+ await mountIslands();
2071
+ tickTimes();
2072
+ api.rendered();
2073
+ }
2074
+ let currentPage;
2075
+ let core;
2076
+ const mount = async (root, handle, coreApi) => {
2077
+ currentPage = handle;
2078
+ core = coreApi;
2079
+ page = handle.id;
2080
+ main = root.querySelector("#wp-main");
2081
+ islands = handle.data().islands;
2082
+ document.addEventListener("wp-islands", (e) => Object.assign(islands, e.detail));
2083
+ main.addEventListener("wp-changed", (e) => markChanged(e.target));
2084
+ api = {
2085
+ ...core,
2086
+ theme: currentTheme
2087
+ };
2088
+ const isDir = handle.kind === "pages" || handle.kind === "folder";
2089
+ themeToggle(root);
2090
+ setInterval(tickTimes, 15e3);
2091
+ new MutationObserver(() => {
2092
+ if (main.querySelector("[data-wp-island]:not([data-wp-mounted])")) mountIslands();
2093
+ }).observe(main, {
2094
+ childList: true,
2095
+ subtree: true
2096
+ });
2097
+ handle.onChange(() => refresh());
2098
+ if (isDir) core.events.on(() => refresh());
2099
+ if (isDir) core.listeners.on(() => refresh());
2100
+ blockSigs = [...main.children].map(signature);
2101
+ countItems(main);
2102
+ if (handle.live) {
2103
+ if (!isDir) trackInitial(main, page, core);
2104
+ if (!isDir) trackWaiting(main, core);
2105
+ trackElsewhere(root, handle, core);
2106
+ trackLive(root, handle, core);
2107
+ }
2108
+ if (isDir) {
2109
+ trackSorts();
2110
+ core.onRendered(applySorts);
2111
+ trackBoard();
2112
+ }
2113
+ trackSticky(main, (fn) => core.onRendered(fn));
2114
+ trackPlace(main);
2115
+ trackHeadingLinks(main);
2116
+ trackWindows(core);
2117
+ if (!isDir && handle.live) trackOrphanThreads(main, core);
2118
+ await mountIslands();
2119
+ tickTimes();
2120
+ };
2121
+ export { mount as default };