bom-pi 0.0.0-stage → 0.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +33 -2
- package/apps/README.md +7 -0
- package/apps/web/README.md +21 -0
- package/apps/web/pocket-adapter.mjs +323 -0
- package/apps/web/public/LICENSE.pocket +21 -0
- package/apps/web/public/activity-fold.js +28 -0
- package/apps/web/public/agent-now.js +37 -0
- package/apps/web/public/agent-tile.js +79 -0
- package/apps/web/public/app.js +975 -0
- package/apps/web/public/apple-touch-icon.png +0 -0
- package/apps/web/public/artifact-bridge.js +687 -0
- package/apps/web/public/avatar.js +87 -0
- package/apps/web/public/back.js +554 -0
- package/apps/web/public/box-keys.js +216 -0
- package/apps/web/public/browser-panel.js +1097 -0
- package/apps/web/public/browser.js +68 -0
- package/apps/web/public/calls.js +139 -0
- package/apps/web/public/chat.js +919 -0
- package/apps/web/public/clock.js +34 -0
- package/apps/web/public/commands.js +578 -0
- package/apps/web/public/composer.js +2068 -0
- package/apps/web/public/diff-parse.js +672 -0
- package/apps/web/public/diff.js +1646 -0
- package/apps/web/public/dock.js +299 -0
- package/apps/web/public/extension-ui.js +2734 -0
- package/apps/web/public/files-panel.js +775 -0
- package/apps/web/public/files.js +368 -0
- package/apps/web/public/fonts/FiraCode-VF.woff2 +0 -0
- package/apps/web/public/fonts/Geist.woff2 +0 -0
- package/apps/web/public/fonts/IBMPlexMono-Variable-Italic.woff2 +0 -0
- package/apps/web/public/fonts/IBMPlexMono-Variable.woff2 +0 -0
- package/apps/web/public/fonts/InterVariable-Italic.woff2 +0 -0
- package/apps/web/public/fonts/InterVariable.woff2 +0 -0
- package/apps/web/public/fonts/Iosevka-Bold.woff2 +0 -0
- package/apps/web/public/fonts/Iosevka-BoldItalic.woff2 +0 -0
- package/apps/web/public/fonts/Iosevka-Italic.woff2 +0 -0
- package/apps/web/public/fonts/Iosevka-Regular.woff2 +0 -0
- package/apps/web/public/fonts/Iosevka-SemiBold.woff2 +0 -0
- package/apps/web/public/fonts/Iosevka-SemiBoldItalic.woff2 +0 -0
- package/apps/web/public/fonts/JetBrainsMono-Italic.woff2 +0 -0
- package/apps/web/public/fonts/JetBrainsMono.woff2 +0 -0
- package/apps/web/public/fonts/NerdFontsSymbolsMono.woff2 +0 -0
- package/apps/web/public/fonts/SOURCES.md +69 -0
- package/apps/web/public/gestures.js +610 -0
- package/apps/web/public/highlight.js +480 -0
- package/apps/web/public/history.js +70 -0
- package/apps/web/public/home.js +169 -0
- package/apps/web/public/icon-192.png +0 -0
- package/apps/web/public/icon-512.png +0 -0
- package/apps/web/public/icon-maskable-512.png +0 -0
- package/apps/web/public/icon.svg +16 -0
- package/apps/web/public/index.html +71 -0
- package/apps/web/public/launcher.js +1293 -0
- package/apps/web/public/linked-sessions.js +55 -0
- package/apps/web/public/live.js +39 -0
- package/apps/web/public/manifest.webmanifest +32 -0
- package/apps/web/public/model-refresh.js +73 -0
- package/apps/web/public/notify.js +251 -0
- package/apps/web/public/peeks.js +920 -0
- package/apps/web/public/pip-attachments.js +182 -0
- package/apps/web/public/pip-window.js +141 -0
- package/apps/web/public/pip.js +1217 -0
- package/apps/web/public/quote-reply.js +109 -0
- package/apps/web/public/quote-text.js +31 -0
- package/apps/web/public/rich.js +403 -0
- package/apps/web/public/run-frame.js +106 -0
- package/apps/web/public/safe-mode.js +71 -0
- package/apps/web/public/seen.js +169 -0
- package/apps/web/public/session-tree.js +117 -0
- package/apps/web/public/sessions.js +2695 -0
- package/apps/web/public/share.js +126 -0
- package/apps/web/public/sheets/appearance.js +820 -0
- package/apps/web/public/sheets/branch.js +353 -0
- package/apps/web/public/sheets/extensions.js +818 -0
- package/apps/web/public/sheets/file.js +318 -0
- package/apps/web/public/sheets/find.js +250 -0
- package/apps/web/public/sheets/folder.js +680 -0
- package/apps/web/public/sheets/gallery.js +2340 -0
- package/apps/web/public/sheets/hooks.js +350 -0
- package/apps/web/public/sheets/memory.js +531 -0
- package/apps/web/public/sheets/menu.js +580 -0
- package/apps/web/public/sheets/message.js +220 -0
- package/apps/web/public/sheets/model.js +412 -0
- package/apps/web/public/sheets/people.js +414 -0
- package/apps/web/public/sheets/pi-sessions.js +264 -0
- package/apps/web/public/sheets/providers.js +525 -0
- package/apps/web/public/sheets/running.js +130 -0
- package/apps/web/public/sheets/schedules.js +71 -0
- package/apps/web/public/sheets/session.js +249 -0
- package/apps/web/public/sheets/shortcuts.js +101 -0
- package/apps/web/public/sheets/spend.js +150 -0
- package/apps/web/public/sheets/text.js +53 -0
- package/apps/web/public/sheets/viewers.js +363 -0
- package/apps/web/public/sheets/worktree.js +50 -0
- package/apps/web/public/sheets.js +410 -0
- package/apps/web/public/signin.js +57 -0
- package/apps/web/public/slots.js +208 -0
- package/apps/web/public/store.js +1760 -0
- package/apps/web/public/style.css +18625 -0
- package/apps/web/public/subagents-board.js +879 -0
- package/apps/web/public/subagents.js +273 -0
- package/apps/web/public/sw.js +169 -0
- package/apps/web/public/taps.js +26 -0
- package/apps/web/public/theme-surface.d.ts +4 -0
- package/apps/web/public/theme-surface.js +266 -0
- package/apps/web/public/theme.js +845 -0
- package/apps/web/public/themes/lantern/colors.toml +25 -0
- package/apps/web/public/themes/lantern/direction.css +60 -0
- package/apps/web/public/themes/lantern/frame.css +254 -0
- package/apps/web/public/themes/lantern/theme.css +10 -0
- package/apps/web/public/themes/lantern/theme.json +7 -0
- package/apps/web/public/themes/pocket/theme.css +189 -0
- package/apps/web/public/themes/pocket/theme.json +6 -0
- package/apps/web/public/themes.js +556 -0
- package/apps/web/public/transcript.js +3348 -0
- package/apps/web/public/trust.js +295 -0
- package/apps/web/public/turns.js +507 -0
- package/apps/web/public/ui.js +1910 -0
- package/apps/web/public/voice.js +345 -0
- package/apps/web/server.mjs +774 -0
- package/package.json +43 -4
- package/packages/cli/src/bom-pi.mjs +452 -0
- package/packages/cli/templates/blank.factory.json +7 -0
- package/packages/cli/templates/dev.factory.json +11 -0
- package/packages/cli/templates/docs.factory.json +12 -0
- package/packages/cli/templates/ops.factory.json +14 -0
- package/packages/cli/templates/triage.factory.json +10 -0
- package/packages/core/src/daemon.mjs +2047 -0
- package/packages/core/src/limit-gate.mjs +192 -0
- package/packages/core/src/rpc-client.mjs +66 -0
- package/systemd/README.md +11 -0
|
@@ -0,0 +1,1910 @@
|
|
|
1
|
+
// Shared bits: htm binding, markdown, formatting, icons, the bottom sheet, and small controls (switches, menu rows).
|
|
2
|
+
|
|
3
|
+
import DOMPurify from "dompurify";
|
|
4
|
+
import htm from "htm";
|
|
5
|
+
import { marked } from "marked";
|
|
6
|
+
import { Component, createContext, h } from "preact";
|
|
7
|
+
import { useContext, useEffect, useLayoutEffect, useRef, useState } from "preact/hooks";
|
|
8
|
+
import { useDragToClose } from "./gestures.js";
|
|
9
|
+
import { highlight, langOf } from "./highlight.js";
|
|
10
|
+
import { actions, filesShown, notify, openSheet, store } from "./store.js";
|
|
11
|
+
|
|
12
|
+
export const html = htm.bind(h);
|
|
13
|
+
|
|
14
|
+
// ─── Images ──────────────────────────────────────────────────────────────────────
|
|
15
|
+
|
|
16
|
+
const currentConversation = () => store.state.view.conversation?.id;
|
|
17
|
+
|
|
18
|
+
/** An image file on the server (absolute, `~/…`, or relative to the session's folder), shown through the app. */
|
|
19
|
+
export const fileUrl = (path, conversationId = currentConversation()) =>
|
|
20
|
+
`/api/c/${conversationId}/file?path=${encodeURIComponent(path)}`;
|
|
21
|
+
|
|
22
|
+
/** The `index`th image stored in a message: a pasted image or one a tool returned. */
|
|
23
|
+
export const entryImageUrl = (entryId, index, conversationId = currentConversation()) =>
|
|
24
|
+
`/api/c/${conversationId}/image/${entryId}/${index}`;
|
|
25
|
+
|
|
26
|
+
/** Where the browser loads `` from. Web and data URLs stay; paths and file:// URLs point at the server. */
|
|
27
|
+
function imageSource(src, conversationId) {
|
|
28
|
+
const value = String(src ?? "").trim();
|
|
29
|
+
|
|
30
|
+
if (value === "" || conversationId === undefined || conversationId === null) {
|
|
31
|
+
return value;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
if (value.startsWith("/api/") || value.startsWith("/a/")) {
|
|
35
|
+
return value;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const file = /^file:\/\//i.test(value);
|
|
39
|
+
// A Windows path (C:\shot.png) is not a URL scheme.
|
|
40
|
+
const drive = /^[a-z]:[\\/]/i.test(value);
|
|
41
|
+
|
|
42
|
+
if (!file && !drive && /^([a-z][a-z0-9+.-]*:|\/\/)/i.test(value)) {
|
|
43
|
+
return value;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// file:///C:/shot.png names C:/shot.png.
|
|
47
|
+
let path = file
|
|
48
|
+
? value.replace(/^file:\/\/(localhost)?/i, "").replace(/^\/([a-z]:)/i, "$1")
|
|
49
|
+
: value;
|
|
50
|
+
|
|
51
|
+
try {
|
|
52
|
+
path = decodeURIComponent(path);
|
|
53
|
+
} catch {
|
|
54
|
+
// keep it as written
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
return fileUrl(path, conversationId);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** A tappable image thumbnail that opens full screen, or a chip when the image cannot load. */
|
|
61
|
+
export function Thumb({ src, alt = "image" }) {
|
|
62
|
+
const [broken, setBroken] = useState(false);
|
|
63
|
+
|
|
64
|
+
if (broken) {
|
|
65
|
+
return html`<span class="chip" title="This image could not be loaded">🖼 ${alt}</span>`;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
return html`<button
|
|
69
|
+
class="thumb"
|
|
70
|
+
type="button"
|
|
71
|
+
onClick=${() => openSheet({ type: "image", src, alt })}
|
|
72
|
+
>
|
|
73
|
+
<img
|
|
74
|
+
src=${src}
|
|
75
|
+
alt=${alt}
|
|
76
|
+
loading="lazy"
|
|
77
|
+
decoding="async"
|
|
78
|
+
onError=${() => setBroken(true)}
|
|
79
|
+
/>
|
|
80
|
+
</button>`;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// ─── Markdown ──────────────────────────────────────────────────────────────────
|
|
84
|
+
|
|
85
|
+
// Line breaks are each `Markdown`'s to choose (`breaks`).
|
|
86
|
+
marked.setOptions({ gfm: true });
|
|
87
|
+
|
|
88
|
+
const ESCAPES = { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" };
|
|
89
|
+
|
|
90
|
+
/** Text as HTML that shows it as written. */
|
|
91
|
+
const escapeHtml = (text) => String(text).replace(/[&<>"']/g, (char) => ESCAPES[char]);
|
|
92
|
+
|
|
93
|
+
/** A fence's language as it may be kept: a short name of safe characters, or nothing. */
|
|
94
|
+
const FENCE_NAME = /^[\w+#.-]{1,24}$/;
|
|
95
|
+
|
|
96
|
+
marked.use({
|
|
97
|
+
renderer: {
|
|
98
|
+
// Task list boxes as characters: the sanitizer drops form controls.
|
|
99
|
+
checkbox: ({ checked }) => (checked ? "☑ " : "☐ "),
|
|
100
|
+
// A code block keeps its language as data (the sanitizer drops classes), for colors and a label.
|
|
101
|
+
code({ text, lang, escaped }) {
|
|
102
|
+
const name = (lang ?? "").trim().split(/\s+/)[0];
|
|
103
|
+
const attribute = FENCE_NAME.test(name) ? ` data-lang="${name}"` : "";
|
|
104
|
+
|
|
105
|
+
return `<pre${attribute}><code>${escaped ? text : escapeHtml(text)}</code></pre>\n`;
|
|
106
|
+
},
|
|
107
|
+
},
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Replies are untrusted: a file or page Pi read can steer what it writes. No forms or controls, no media that loads by
|
|
112
|
+
* itself, and no style, class, id, or data hooks that could lay a fake screen over the app: a theme styles
|
|
113
|
+
* `[data-part="approval"]`, and a reply must not wear it. A code block's language is the one data attribute kept.
|
|
114
|
+
*/
|
|
115
|
+
const PURIFY = {
|
|
116
|
+
FORBID_TAGS: [
|
|
117
|
+
"form",
|
|
118
|
+
"input",
|
|
119
|
+
"button",
|
|
120
|
+
"select",
|
|
121
|
+
"textarea",
|
|
122
|
+
"dialog",
|
|
123
|
+
"style",
|
|
124
|
+
"audio",
|
|
125
|
+
"video",
|
|
126
|
+
"source",
|
|
127
|
+
"track",
|
|
128
|
+
"picture",
|
|
129
|
+
],
|
|
130
|
+
ALLOW_DATA_ATTR: false,
|
|
131
|
+
ADD_ATTR: ["data-lang"],
|
|
132
|
+
// `data-path` is the app's own mark for file paths (`sanitize`): a reply may not set it.
|
|
133
|
+
FORBID_ATTR: [
|
|
134
|
+
"style",
|
|
135
|
+
"class",
|
|
136
|
+
"id",
|
|
137
|
+
"srcset",
|
|
138
|
+
"background",
|
|
139
|
+
"poster",
|
|
140
|
+
"action",
|
|
141
|
+
"formaction",
|
|
142
|
+
"data-path",
|
|
143
|
+
],
|
|
144
|
+
RETURN_DOM_FRAGMENT: true,
|
|
145
|
+
};
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* The app's own sanitizer, with its settings read once (`setConfig`): given them on each call, it reads them again for
|
|
149
|
+
* each reply. Its own instance, so what it is set to and its hooks (below) change nothing for an extension's module that
|
|
150
|
+
* imports `dompurify` too.
|
|
151
|
+
*/
|
|
152
|
+
const purify = DOMPurify(window);
|
|
153
|
+
|
|
154
|
+
purify.setConfig(PURIFY);
|
|
155
|
+
|
|
156
|
+
/** Images the app serves for a conversation (files, stored images, artifacts), or inline data. Nothing else loads. */
|
|
157
|
+
const localImage = (src) =>
|
|
158
|
+
/^\/api\/c\/\d+\/(file\?|image\/)/.test(src) ||
|
|
159
|
+
/^\/a\/\d+\//.test(src) ||
|
|
160
|
+
/^data:image\//i.test(src);
|
|
161
|
+
|
|
162
|
+
/** Code blocks past this size show without colors: coloring them would hold up the conversation. */
|
|
163
|
+
export const COLOR_LIMIT = 200_000;
|
|
164
|
+
/** Code blocks longer than this many lines fold to their first lines, once they are written whole. */
|
|
165
|
+
const LONG_CODE = 40;
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* What a code block shows besides its code, if anything: `html` (a page, previewed), `svg` (an image), or `diff`. Its
|
|
169
|
+
* fence names it; a page or an image without a name is known by how it starts.
|
|
170
|
+
*/
|
|
171
|
+
function richKind(name, source) {
|
|
172
|
+
const lang = name.toLowerCase();
|
|
173
|
+
|
|
174
|
+
if (lang === "html" || lang === "htm" || lang === "xhtml") {
|
|
175
|
+
return "html";
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
if (lang === "diff" || lang === "patch") {
|
|
179
|
+
return "diff";
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
if (
|
|
183
|
+
lang === "svg" ||
|
|
184
|
+
((lang === "xml" || lang === "") && /^\s*(<\?xml[^>]*>\s*)?<svg[\s>]/i.test(source))
|
|
185
|
+
) {
|
|
186
|
+
return "svg";
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
if (lang === "" && /^\s*(<!doctype html|<html[\s>])/i.test(source)) {
|
|
190
|
+
return "html";
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
return undefined;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* A code block as the app draws it: a bar with its language (or "text") and a copy button above it, its code colored,
|
|
198
|
+
* and a long one folded. A block that shows something besides its code is marked with its kind for `markdownParts`.
|
|
199
|
+
*/
|
|
200
|
+
function codeBlock(pre, fold) {
|
|
201
|
+
const source = pre.textContent ?? "";
|
|
202
|
+
const name = FENCE_NAME.test(pre.dataset.lang ?? "") ? pre.dataset.lang : "";
|
|
203
|
+
const lang = langOf(name);
|
|
204
|
+
const code = pre.querySelector("code") ?? pre;
|
|
205
|
+
const wrap = document.createElement("div");
|
|
206
|
+
const copy = document.createElement("button");
|
|
207
|
+
const kind = richKind(name, source);
|
|
208
|
+
|
|
209
|
+
// The highlighter's output is the source, escaped, in spans of its own: nothing from the reply becomes markup.
|
|
210
|
+
if (lang && source.length <= COLOR_LIMIT) {
|
|
211
|
+
code.innerHTML = highlight(source, lang);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
wrap.className = "code";
|
|
215
|
+
wrap.dataset.part = "code-block";
|
|
216
|
+
copy.className = "copy";
|
|
217
|
+
copy.type = "button";
|
|
218
|
+
copy.dataset.copy = "";
|
|
219
|
+
copy.textContent = "Copy";
|
|
220
|
+
pre.replaceWith(wrap);
|
|
221
|
+
|
|
222
|
+
if (kind) {
|
|
223
|
+
wrap.dataset.kind = kind;
|
|
224
|
+
wrap.dataset.lang = name;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
const head = document.createElement("div");
|
|
228
|
+
const label = document.createElement("span");
|
|
229
|
+
|
|
230
|
+
head.className = "code-head";
|
|
231
|
+
head.dataset.part = "code-head";
|
|
232
|
+
label.className = "code-lang";
|
|
233
|
+
label.textContent = name || "text";
|
|
234
|
+
head.append(label, copy);
|
|
235
|
+
wrap.append(head, pre);
|
|
236
|
+
|
|
237
|
+
const lines = source.split("\n").length;
|
|
238
|
+
|
|
239
|
+
if (fold && lines > LONG_CODE) {
|
|
240
|
+
const more = document.createElement("button");
|
|
241
|
+
|
|
242
|
+
wrap.classList.add("long");
|
|
243
|
+
more.className = "code-more";
|
|
244
|
+
more.type = "button";
|
|
245
|
+
more.dataset.more = "";
|
|
246
|
+
more.textContent = `Show all ${lines} lines`;
|
|
247
|
+
wrap.append(more);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* Sanitized HTML, changed only through the DOM afterwards: editing the sanitized string could turn text inside an
|
|
253
|
+
* attribute into markup. An image from another site becomes a link, since its address could carry data out the moment
|
|
254
|
+
* it loads, and code blocks are drawn by `codeBlock` (folded when long, if `fold`). Returns the element holding it.
|
|
255
|
+
*/
|
|
256
|
+
function sanitize(html, fold) {
|
|
257
|
+
const fragment = purify.sanitize(html);
|
|
258
|
+
|
|
259
|
+
// `src/app.ts` in a reply opens the file: inline code that is a path, not code blocks.
|
|
260
|
+
for (const code of fragment.querySelectorAll("code")) {
|
|
261
|
+
// Code in a line of words, for themes; a code block is `code-block`.
|
|
262
|
+
if (!code.closest("pre")) {
|
|
263
|
+
code.dataset.part = "inline-code";
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
if (!code.closest("pre, a") && looksLikePath(code.textContent ?? "")) {
|
|
267
|
+
code.dataset.path = code.textContent;
|
|
268
|
+
// Keys open it too (`openFile` below).
|
|
269
|
+
code.tabIndex = 0;
|
|
270
|
+
code.setAttribute("role", "button");
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
// Local Markdown links open the same viewer as inline code paths.
|
|
275
|
+
for (const link of fragment.querySelectorAll("a[href]")) {
|
|
276
|
+
const path = linkedPath(link.getAttribute("href") ?? "");
|
|
277
|
+
|
|
278
|
+
if (path !== null) {
|
|
279
|
+
link.dataset.path = fromBase(path);
|
|
280
|
+
link.removeAttribute("target");
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
for (const pre of fragment.querySelectorAll("pre")) {
|
|
285
|
+
codeBlock(pre, fold);
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
for (const image of fragment.querySelectorAll("img")) {
|
|
289
|
+
const src = image.getAttribute("src") ?? "";
|
|
290
|
+
|
|
291
|
+
if (localImage(src)) {
|
|
292
|
+
continue;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
const label = `🖼 ${image.getAttribute("alt") || "image"}`;
|
|
296
|
+
let host;
|
|
297
|
+
|
|
298
|
+
try {
|
|
299
|
+
host = /^https?:\/\//i.test(src) ? new URL(src).host : undefined;
|
|
300
|
+
} catch {
|
|
301
|
+
host = undefined;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
// Inside a link already, or not a web address: the label alone.
|
|
305
|
+
if (host === undefined || image.closest("a")) {
|
|
306
|
+
image.replaceWith(label);
|
|
307
|
+
continue;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
const link = document.createElement("a");
|
|
311
|
+
|
|
312
|
+
link.href = src;
|
|
313
|
+
link.textContent = label;
|
|
314
|
+
link.title = `Image from ${host}`;
|
|
315
|
+
link.target = "_blank";
|
|
316
|
+
link.rel = "noopener noreferrer";
|
|
317
|
+
image.replaceWith(link);
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
const holder = document.createElement("div");
|
|
321
|
+
|
|
322
|
+
holder.append(fragment);
|
|
323
|
+
|
|
324
|
+
return holder;
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/**
|
|
328
|
+
* The parts of rendered markdown: runs of HTML, and between them the top-level code blocks that show more than code
|
|
329
|
+
* (`{ kind, lang, source, html }`), for `Markdown` to draw with the component `setRichBlock` gave it.
|
|
330
|
+
*/
|
|
331
|
+
function partsOf(holder) {
|
|
332
|
+
const parts = [];
|
|
333
|
+
let run = "";
|
|
334
|
+
|
|
335
|
+
for (const node of holder.childNodes) {
|
|
336
|
+
if (node.nodeType === Node.ELEMENT_NODE && node.matches(".code[data-kind]")) {
|
|
337
|
+
if (run.trim() !== "") {
|
|
338
|
+
parts.push({ html: run });
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
run = "";
|
|
342
|
+
parts.push({
|
|
343
|
+
kind: node.dataset.kind,
|
|
344
|
+
lang: node.dataset.lang,
|
|
345
|
+
source: node.querySelector("pre")?.textContent ?? "",
|
|
346
|
+
html: node.outerHTML,
|
|
347
|
+
});
|
|
348
|
+
continue;
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
run +=
|
|
352
|
+
node.nodeType === Node.ELEMENT_NODE
|
|
353
|
+
? node.outerHTML
|
|
354
|
+
: escapeHtml(node.textContent ?? "");
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
if (run.trim() !== "" || parts.length === 0) {
|
|
358
|
+
parts.push({ html: run });
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
return parts;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/** A reply that is a whole HTML page, not in a code block: shown as one, so it can be previewed rather than mangled. */
|
|
365
|
+
function fencePage(text) {
|
|
366
|
+
if (!/^\s*(<!doctype html|<html[\s>])/i.test(text)) {
|
|
367
|
+
return text;
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
const longest = Math.max(2, ...[...text.matchAll(/`+/g)].map((run) => run[0].length));
|
|
371
|
+
const fence = "`".repeat(longest + 1);
|
|
372
|
+
|
|
373
|
+
return `${fence}html\n${text.trim()}\n${fence}`;
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
/** The conversation whose markdown is being sanitized, for image paths relative to its folder. */
|
|
377
|
+
let rendering = null;
|
|
378
|
+
|
|
379
|
+
/**
|
|
380
|
+
* An element's attribute as the sanitizer reads it next. Before any of its checks (the URL check too), and before the
|
|
381
|
+
* attributes are read: a hook on each attribute would make it copy its lists of allowed names on each call.
|
|
382
|
+
*/
|
|
383
|
+
function rewrite(node, name, change) {
|
|
384
|
+
const value = node.getAttribute(name);
|
|
385
|
+
|
|
386
|
+
if (value !== null) {
|
|
387
|
+
const next = change(value.trim());
|
|
388
|
+
|
|
389
|
+
if (next !== value) {
|
|
390
|
+
node.setAttribute(name, next);
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
purify.addHook("beforeSanitizeAttributes", (node) => {
|
|
396
|
+
// Before the URL check, so file:// and plain paths become app URLs instead of being dropped.
|
|
397
|
+
if (node.nodeName === "IMG") {
|
|
398
|
+
rewrite(node, "src", (src) => imageSource(src, rendering));
|
|
399
|
+
} else if (node.nodeName === "A") {
|
|
400
|
+
// `app.ts:42` looks like a URL scheme to the sanitizer; `./app.ts:42` is the same local file.
|
|
401
|
+
rewrite(node, "href", (href) =>
|
|
402
|
+
/^[a-z][a-z0-9+.-]*:/i.test(href) && linkedPath(href) !== null ? `./${href}` : href,
|
|
403
|
+
);
|
|
404
|
+
}
|
|
405
|
+
});
|
|
406
|
+
|
|
407
|
+
purify.addHook("afterSanitizeAttributes", (node) => {
|
|
408
|
+
if (node.tagName === "A") {
|
|
409
|
+
node.setAttribute("target", "_blank");
|
|
410
|
+
node.setAttribute("rel", "noopener noreferrer");
|
|
411
|
+
} else if (node.tagName === "IMG") {
|
|
412
|
+
node.setAttribute("loading", "lazy");
|
|
413
|
+
node.setAttribute("decoding", "async");
|
|
414
|
+
}
|
|
415
|
+
});
|
|
416
|
+
|
|
417
|
+
const markdownCache = new Map();
|
|
418
|
+
|
|
419
|
+
const MARKDOWN_CACHE = 500;
|
|
420
|
+
|
|
421
|
+
/**
|
|
422
|
+
* Markdown as sanitized parts (`partsOf`). Cached, least recently used out first: a transcript renders its rows in
|
|
423
|
+
* order, and evicting the oldest insert would miss on every row once a thread outgrew the cache. Text still changing
|
|
424
|
+
* (`cache` false) is not kept, and its long code blocks are not folded while they grow. With `breaks`, a single line
|
|
425
|
+
* break is a new line rather than a space.
|
|
426
|
+
*/
|
|
427
|
+
function markdownParts(
|
|
428
|
+
text,
|
|
429
|
+
conversationId = currentConversation(),
|
|
430
|
+
cache = true,
|
|
431
|
+
base = null,
|
|
432
|
+
breaks = true,
|
|
433
|
+
) {
|
|
434
|
+
const key = `${conversationId ?? ""}\u0000${base ?? ""}\u0000${breaks ? "br" : ""}\u0000${text}`;
|
|
435
|
+
let out = markdownCache.get(key);
|
|
436
|
+
|
|
437
|
+
if (out !== undefined) {
|
|
438
|
+
markdownCache.delete(key);
|
|
439
|
+
markdownCache.set(key, out);
|
|
440
|
+
|
|
441
|
+
return out;
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
out = renderParts(fencePage(text), conversationId, base, breaks, cache);
|
|
445
|
+
|
|
446
|
+
if (cache) {
|
|
447
|
+
if (markdownCache.size >= MARKDOWN_CACHE) {
|
|
448
|
+
markdownCache.delete(markdownCache.keys().next().value);
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
markdownCache.set(key, out);
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
return out;
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
/** Markdown parsed, sanitized, and split into parts (`partsOf`), for the conversation and folder given. */
|
|
458
|
+
function renderParts(text, conversationId, base, breaks, fold) {
|
|
459
|
+
rendering = conversationId ?? null;
|
|
460
|
+
linkBase = base;
|
|
461
|
+
|
|
462
|
+
try {
|
|
463
|
+
return partsOf(sanitize(marked.parse(text, { async: false, breaks }), fold));
|
|
464
|
+
} finally {
|
|
465
|
+
rendering = null;
|
|
466
|
+
linkBase = null;
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
/**
|
|
471
|
+
* Markdown still growing, as parts: each top-level block (a paragraph, a list, a code block) drawn on its own, and kept
|
|
472
|
+
* in `kept` from one update to the next, so an update draws again only the blocks that changed, mostly the last. The
|
|
473
|
+
* blocks are found again in the whole text each time (block level only, which is quick), so a block that a later line
|
|
474
|
+
* turns into another (a paragraph into a heading, a list that goes on) is drawn as it is now. A reference link whose
|
|
475
|
+
* definition is in another block shows as written until the text is whole. Returns `{ key, parts }` for each block.
|
|
476
|
+
*/
|
|
477
|
+
function liveBlocks(text, conversationId, base, breaks, kept) {
|
|
478
|
+
const blocks = new marked.Lexer(marked.defaults)
|
|
479
|
+
.blockTokens(text.replace(/\r\n|\r/g, "\n"), [])
|
|
480
|
+
.filter((token) => token.type !== "space");
|
|
481
|
+
const next = new Map();
|
|
482
|
+
const out = blocks.map((token, index) => {
|
|
483
|
+
const parts =
|
|
484
|
+
next.get(token.raw) ??
|
|
485
|
+
kept.get(token.raw) ??
|
|
486
|
+
renderParts(token.raw, conversationId, base, breaks, false);
|
|
487
|
+
|
|
488
|
+
next.set(token.raw, parts);
|
|
489
|
+
|
|
490
|
+
return { key: index, parts };
|
|
491
|
+
});
|
|
492
|
+
|
|
493
|
+
kept.clear();
|
|
494
|
+
|
|
495
|
+
for (const [raw, parts] of next) {
|
|
496
|
+
kept.set(raw, parts);
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
return out;
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
/** What draws a code block that shows more than code (`rich.js`), given once at load: ui.js does not import it. */
|
|
503
|
+
let RichBlock = null;
|
|
504
|
+
|
|
505
|
+
export function setRichBlock(component) {
|
|
506
|
+
RichBlock = component;
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
/**
|
|
510
|
+
* Rendered markdown. `cache={false}` for text that is still changing, such as a streaming answer: its pages, images, and
|
|
511
|
+
* diffs show as code until it is whole. A single line break is a new line, as Pi's terminal shows a reply and GitHub a
|
|
512
|
+
* comment; `breaks={false}` for a Markdown file, where it is a space, as GitHub shows the file (hard-wrapped prose
|
|
513
|
+
* stays one paragraph).
|
|
514
|
+
*/
|
|
515
|
+
export function Markdown({
|
|
516
|
+
text,
|
|
517
|
+
class: className = "",
|
|
518
|
+
cache = true,
|
|
519
|
+
base = null,
|
|
520
|
+
breaks = true,
|
|
521
|
+
conversationId = currentConversation(),
|
|
522
|
+
}) {
|
|
523
|
+
const live = useRef(null);
|
|
524
|
+
|
|
525
|
+
// Growing text, block by block (`liveBlocks`); a whole page is fenced as one block (`fencePage`), as before.
|
|
526
|
+
if (!cache && fencePage(text) === text) {
|
|
527
|
+
const settings = `${conversationId ?? ""}\u0000${base ?? ""}\u0000${breaks}`;
|
|
528
|
+
|
|
529
|
+
if (live.current?.settings !== settings) {
|
|
530
|
+
live.current = { settings, kept: new Map() };
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
const blocks = liveBlocks(text, conversationId, base, breaks, live.current.kept);
|
|
534
|
+
|
|
535
|
+
return html`<div class=${`md ${className}`}>
|
|
536
|
+
${blocks.flatMap(({ key, parts }) =>
|
|
537
|
+
parts
|
|
538
|
+
.filter((part) => part.kind !== undefined || part.html.trim() !== "")
|
|
539
|
+
.map((part, index) => drawPart(part, `${key}.${index}`, true)),
|
|
540
|
+
)}
|
|
541
|
+
</div>`;
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
live.current = null;
|
|
545
|
+
const parts = markdownParts(text, conversationId, cache, base, breaks);
|
|
546
|
+
|
|
547
|
+
if (parts.length === 1 && parts[0].kind === undefined) {
|
|
548
|
+
return html`<div
|
|
549
|
+
class=${`md ${className}`}
|
|
550
|
+
dangerouslySetInnerHTML=${{ __html: parts[0].html }}
|
|
551
|
+
></div>`;
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
return html`<div class=${`md ${className}`}>
|
|
555
|
+
${parts.map((part, index) => drawPart(part, index, !cache))}
|
|
556
|
+
</div>`;
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
/** One part of rendered markdown (`partsOf`): a run of HTML, or a code block that shows more than code. */
|
|
560
|
+
const drawPart = (part, key, streaming) =>
|
|
561
|
+
part.kind === undefined || RichBlock === null
|
|
562
|
+
? html`<div
|
|
563
|
+
key=${key}
|
|
564
|
+
class="md-part"
|
|
565
|
+
dangerouslySetInnerHTML=${{ __html: part.html }}
|
|
566
|
+
></div>`
|
|
567
|
+
: html`<${RichBlock} key=${key} ...${part} streaming=${streaming} />`;
|
|
568
|
+
|
|
569
|
+
/** File types common enough that `name.ext` alone is surely a file, not code like `store.state`. */
|
|
570
|
+
const FILE_TYPES = new Set(
|
|
571
|
+
"ts tsx js jsx mjs cjs json jsonc md mdx txt css scss html htm py rs go java kt rb php cs c h cc cpp hpp swift sh bash zsh fish yml yaml toml ini cfg conf env lock sql xml svg png jpg jpeg gif webp pdf vue svelte astro lua zig dart ex exs erl hs ml nix gradle csv log diff patch".split(
|
|
572
|
+
" ",
|
|
573
|
+
),
|
|
574
|
+
);
|
|
575
|
+
|
|
576
|
+
/**
|
|
577
|
+
* Whether inline code names a file: `src/app.ts`, `./run.sh`, `~/notes.md`, `app.ts:42`, `package.json`. A path with
|
|
578
|
+
* folders needs an extension of some kind; a bare name needs a common one.
|
|
579
|
+
*/
|
|
580
|
+
function looksLikePath(text) {
|
|
581
|
+
if (text.length > 300) {
|
|
582
|
+
return false;
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
// Anchored at home, the top, or here: `~/.bashrc`, `/etc/hosts`, `./run`.
|
|
586
|
+
if (
|
|
587
|
+
/^(?:~|\.{1,2}|)\/[\w@.+-]+(?:\/[\w@.+-]+)*(?::\d+(?:-\d+)?)?$/.test(text) &&
|
|
588
|
+
text !== "/"
|
|
589
|
+
) {
|
|
590
|
+
return true;
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
if (/^(?:Makefile|Dockerfile|LICENSE|\.gitignore|\.env(?:\.\w+)?)$/.test(text)) {
|
|
594
|
+
return true;
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
const match =
|
|
598
|
+
/^((?:[\w@.+-]+\/)*)([\w@+-][\w@.+-]*\.([A-Za-z0-9]{1,10}))(?::\d+(?:-\d+)?)?$/.exec(text);
|
|
599
|
+
|
|
600
|
+
return match !== null && (match[1] !== "" || FILE_TYPES.has(match[3].toLowerCase()));
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
/** A local file link, using the same path recognition as inline code. App routes and URL schemes stay links. */
|
|
604
|
+
function linkedPath(href) {
|
|
605
|
+
let path;
|
|
606
|
+
|
|
607
|
+
try {
|
|
608
|
+
path = decodeURIComponent(href);
|
|
609
|
+
} catch {
|
|
610
|
+
return null;
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
const withoutLine = path.replace(/:\d+(?:-\d+)?$/, "");
|
|
614
|
+
|
|
615
|
+
if (
|
|
616
|
+
/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(withoutLine) ||
|
|
617
|
+
/^\/(?:api|a|s|login|join|share)(?:\/|[?#]|$)/.test(path)
|
|
618
|
+
) {
|
|
619
|
+
return null;
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
return looksLikePath(path) ? path : null;
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
/** The folder of the Markdown file being rendered (`Markdown`'s `base`): its relative links name its neighbors. */
|
|
626
|
+
let linkBase = null;
|
|
627
|
+
|
|
628
|
+
/** A linked path as the viewer opens it: relative to the Markdown file it is in, if any, else as written. */
|
|
629
|
+
function fromBase(path) {
|
|
630
|
+
if (linkBase === null || /^[~/]/.test(path)) {
|
|
631
|
+
return path;
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
const parts = linkBase.replace(/\/+$/, "").split("/");
|
|
635
|
+
|
|
636
|
+
for (const part of path.split("/")) {
|
|
637
|
+
if (part === "..") {
|
|
638
|
+
if (parts.length > 1) {
|
|
639
|
+
parts.pop();
|
|
640
|
+
}
|
|
641
|
+
} else if (part !== ".") {
|
|
642
|
+
parts.push(part);
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
return parts.join("/");
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
let fileRequests = 0;
|
|
650
|
+
|
|
651
|
+
/**
|
|
652
|
+
* Open a file (or folder) of the session in the viewer: in the Files tile while it is open, otherwise in a sheet.
|
|
653
|
+
* `path:42` opens it at line 42.
|
|
654
|
+
*/
|
|
655
|
+
export function openFile(path) {
|
|
656
|
+
const match = /^(.*?):(\d+)(?:-\d+)?$/.exec(path);
|
|
657
|
+
const target = { path: match ? match[1] : path, line: match ? Number(match[2]) : undefined };
|
|
658
|
+
|
|
659
|
+
if (filesShown()) {
|
|
660
|
+
// From the tile's Changes tab, back from the file goes back there (files-panel.js).
|
|
661
|
+
store.set((state) => ({
|
|
662
|
+
sheet: null,
|
|
663
|
+
filesTab: "files",
|
|
664
|
+
filesTarget: { ...target, from: state.filesTab, n: (state.filesTarget?.n ?? 0) + 1 },
|
|
665
|
+
}));
|
|
666
|
+
|
|
667
|
+
return;
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
// `n` differs for each request, so asking again for the open file reads it again (`FileView`'s `refresh`).
|
|
671
|
+
openSheet({ type: "file", id: target.path, line: target.line, n: ++fileRequests });
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
/**
|
|
675
|
+
* Whether a click or key asks to show a path in the file manager rather than the viewer: Ctrl (⌘ on a Mac) held, by the
|
|
676
|
+
* owner, whose machine the server runs on.
|
|
677
|
+
*/
|
|
678
|
+
export const revealAsked = (event) =>
|
|
679
|
+
(APPLE ? event.metaKey : event.ctrlKey) && store.state.me?.role === "owner";
|
|
680
|
+
|
|
681
|
+
/** Show a file (or folder) of the session in the file manager of the machine the server runs on, selected. */
|
|
682
|
+
export function revealFile(path) {
|
|
683
|
+
const match = /^(.*?):(\d+)(?:-\d+)?$/.exec(path);
|
|
684
|
+
|
|
685
|
+
actions.reveal(match ? match[1] : path).then(
|
|
686
|
+
() => notify("info", "Shown in the file manager on the server's machine."),
|
|
687
|
+
(error) => notify("error", error.message ?? String(error)),
|
|
688
|
+
);
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
/** File paths in rendered markdown open in the viewer, or with Ctrl (⌘) held, in the file manager. */
|
|
692
|
+
document.addEventListener("click", (event) => {
|
|
693
|
+
const target = event.target.closest?.(".md code[data-path], .md a[data-path]");
|
|
694
|
+
|
|
695
|
+
if (!target) {
|
|
696
|
+
return;
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
if (revealAsked(event)) {
|
|
700
|
+
event.preventDefault();
|
|
701
|
+
event.stopPropagation();
|
|
702
|
+
revealFile(target.dataset.path);
|
|
703
|
+
|
|
704
|
+
return;
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
// A file link stays in the app even when selecting its text keeps it from opening: its href is a path, not a page.
|
|
708
|
+
event.preventDefault();
|
|
709
|
+
|
|
710
|
+
const selection = getSelection();
|
|
711
|
+
|
|
712
|
+
// Selecting a link's text does not change the selection elsewhere: only one in it holds the file back.
|
|
713
|
+
if (selection?.toString() && selection.containsNode(target, true)) {
|
|
714
|
+
return;
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
event.stopPropagation();
|
|
718
|
+
openFile(target.dataset.path);
|
|
719
|
+
});
|
|
720
|
+
|
|
721
|
+
// Enter or Space on a file path in inline code opens it, as a tap does: it is a button for keys.
|
|
722
|
+
document.addEventListener("keydown", (event) => {
|
|
723
|
+
const target = event.target.closest?.(".md code[data-path]");
|
|
724
|
+
|
|
725
|
+
if (target && (event.key === "Enter" || event.key === " ") && !event.repeat) {
|
|
726
|
+
event.preventDefault();
|
|
727
|
+
|
|
728
|
+
if (revealAsked(event)) {
|
|
729
|
+
revealFile(target.dataset.path);
|
|
730
|
+
} else {
|
|
731
|
+
openFile(target.dataset.path);
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
});
|
|
735
|
+
|
|
736
|
+
/** Images in rendered markdown open full screen, unless they are links. */
|
|
737
|
+
document.addEventListener("click", (event) => {
|
|
738
|
+
const image = event.target.closest?.(".md img");
|
|
739
|
+
|
|
740
|
+
if (!image || image.closest("a") || image.classList.contains("broken")) {
|
|
741
|
+
return;
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
openSheet({ type: "image", src: image.currentSrc || image.src, alt: image.alt });
|
|
745
|
+
});
|
|
746
|
+
|
|
747
|
+
/** A markdown image that cannot load says so instead of showing a broken icon. */
|
|
748
|
+
document.addEventListener(
|
|
749
|
+
"error",
|
|
750
|
+
(event) => {
|
|
751
|
+
const image = event.target;
|
|
752
|
+
|
|
753
|
+
if (
|
|
754
|
+
image?.tagName !== "IMG" ||
|
|
755
|
+
!image.closest(".md") ||
|
|
756
|
+
image.classList.contains("broken")
|
|
757
|
+
) {
|
|
758
|
+
return;
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
image.classList.add("broken");
|
|
762
|
+
const note = document.createElement("span");
|
|
763
|
+
|
|
764
|
+
note.className = "image-missing";
|
|
765
|
+
note.textContent = `🖼 ${image.alt || "Image"} could not be loaded`;
|
|
766
|
+
image.after(note);
|
|
767
|
+
},
|
|
768
|
+
true,
|
|
769
|
+
);
|
|
770
|
+
|
|
771
|
+
/** Copy buttons inside rendered markdown, handled once for the whole page. */
|
|
772
|
+
document.addEventListener("click", (event) => {
|
|
773
|
+
const button = event.target.closest?.("[data-copy]");
|
|
774
|
+
|
|
775
|
+
if (!button) {
|
|
776
|
+
return;
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
const pre = button.closest(".code")?.querySelector("pre");
|
|
780
|
+
|
|
781
|
+
copyText(pre?.innerText ?? "").then(
|
|
782
|
+
() => {
|
|
783
|
+
button.textContent = "Copied";
|
|
784
|
+
setTimeout(() => (button.textContent = "Copy"), 1200);
|
|
785
|
+
},
|
|
786
|
+
() => notify("error", "Could not copy."),
|
|
787
|
+
);
|
|
788
|
+
});
|
|
789
|
+
|
|
790
|
+
/** A long code block's button shows all of it, and folds it again. */
|
|
791
|
+
document.addEventListener("click", (event) => {
|
|
792
|
+
const button = event.target.closest?.("[data-more]");
|
|
793
|
+
const block = button?.closest(".code");
|
|
794
|
+
|
|
795
|
+
if (!block) {
|
|
796
|
+
return;
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
const open = block.classList.toggle("open");
|
|
800
|
+
|
|
801
|
+
button.textContent = open
|
|
802
|
+
? "Fold"
|
|
803
|
+
: `Show all ${block.querySelector("pre")?.textContent.split("\n").length ?? ""} lines`;
|
|
804
|
+
});
|
|
805
|
+
|
|
806
|
+
/** Copy text, with a fallback for plain-http addresses, where the clipboard API does not exist. */
|
|
807
|
+
export async function copyText(text) {
|
|
808
|
+
if (navigator.clipboard?.writeText) {
|
|
809
|
+
return navigator.clipboard.writeText(text);
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
const area = document.createElement("textarea");
|
|
813
|
+
|
|
814
|
+
area.value = text;
|
|
815
|
+
area.style.cssText = "position:fixed;opacity:0;top:0;left:0";
|
|
816
|
+
document.body.append(area);
|
|
817
|
+
area.select();
|
|
818
|
+
const ok = document.execCommand("copy");
|
|
819
|
+
|
|
820
|
+
area.remove();
|
|
821
|
+
|
|
822
|
+
if (!ok) {
|
|
823
|
+
throw new Error("Could not copy.");
|
|
824
|
+
}
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
/** How full a context is, as Pi's own TUI colors its footer: `warn` above 70%, `err` above 90%. */
|
|
828
|
+
export function contextLevel(percent) {
|
|
829
|
+
if (percent > 90) {
|
|
830
|
+
return "err";
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
if (percent > 70) {
|
|
834
|
+
return "warn";
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
return "";
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
export function formatTokens(count) {
|
|
841
|
+
if (count === undefined || count === null) {
|
|
842
|
+
return "?";
|
|
843
|
+
}
|
|
844
|
+
|
|
845
|
+
if (count >= 1_000_000) {
|
|
846
|
+
return `${(count / 1_000_000).toFixed(count % 1_000_000 === 0 ? 0 : 1)}M`;
|
|
847
|
+
}
|
|
848
|
+
|
|
849
|
+
if (count >= 1000) {
|
|
850
|
+
return `${Math.round(count / 1000)}k`;
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
return String(count);
|
|
854
|
+
}
|
|
855
|
+
|
|
856
|
+
export function formatBytes(bytes) {
|
|
857
|
+
if (bytes < 1024) {
|
|
858
|
+
return `${bytes} B`;
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
if (bytes < 1024 * 1024) {
|
|
862
|
+
return `${(bytes / 1024).toFixed(1)} KB`;
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
// Times as this device writes them, each format made once: making one costs more than using it, and a transcript
|
|
869
|
+
// writes a time for each message.
|
|
870
|
+
const TIME = new Intl.DateTimeFormat([], { hour: "numeric", minute: "2-digit" });
|
|
871
|
+
const DAY = new Intl.DateTimeFormat([], { month: "short", day: "numeric" });
|
|
872
|
+
const WEEKDAY = new Intl.DateTimeFormat([], { weekday: "short" });
|
|
873
|
+
|
|
874
|
+
/** Whether a date is today, on this device's clock. */
|
|
875
|
+
function isToday(date) {
|
|
876
|
+
const now = new Date();
|
|
877
|
+
|
|
878
|
+
return (
|
|
879
|
+
date.getDate() === now.getDate() &&
|
|
880
|
+
date.getMonth() === now.getMonth() &&
|
|
881
|
+
date.getFullYear() === now.getFullYear()
|
|
882
|
+
);
|
|
883
|
+
}
|
|
884
|
+
|
|
885
|
+
/** When something happened, on this device's clock: "10:42" today, "Oct 3 10:42" before. */
|
|
886
|
+
export function clockTime(date) {
|
|
887
|
+
const time = TIME.format(date);
|
|
888
|
+
|
|
889
|
+
return isToday(date) ? time : `${DAY.format(date)} ${time}`;
|
|
890
|
+
}
|
|
891
|
+
|
|
892
|
+
/** A time ahead, on this device's clock: "14:30" today, "Mon 09:00" this week, "Oct 20 09:00" later. */
|
|
893
|
+
export function formatWhen(ms) {
|
|
894
|
+
const at = new Date(ms);
|
|
895
|
+
const time = TIME.format(at);
|
|
896
|
+
|
|
897
|
+
if (isToday(at)) {
|
|
898
|
+
return time;
|
|
899
|
+
}
|
|
900
|
+
|
|
901
|
+
const day = ms - Date.now() < 6 * 86_400_000 ? WEEKDAY.format(at) : DAY.format(at);
|
|
902
|
+
|
|
903
|
+
return `${day} ${time}`;
|
|
904
|
+
}
|
|
905
|
+
|
|
906
|
+
/** The minute now, for what shows a time ago: a memo that keys on it draws again as the minute turns (`useMinute`). */
|
|
907
|
+
const minuteNow = () => Math.floor(Date.now() / 60_000);
|
|
908
|
+
|
|
909
|
+
/** Listeners to the minute's turn, and its timer while any listen. */
|
|
910
|
+
const minuteListeners = new Set();
|
|
911
|
+
let minuteTimer = 0;
|
|
912
|
+
|
|
913
|
+
function tickMinute() {
|
|
914
|
+
minuteTimer = setTimeout(tickMinute, 60_000 - (Date.now() % 60_000));
|
|
915
|
+
|
|
916
|
+
for (const listener of minuteListeners) {
|
|
917
|
+
listener(minuteNow());
|
|
918
|
+
}
|
|
919
|
+
}
|
|
920
|
+
|
|
921
|
+
/**
|
|
922
|
+
* The minute now, which draws the component again as it turns: memoized rows that show "5m" would otherwise keep it.
|
|
923
|
+
* One timer for every component that uses it.
|
|
924
|
+
*/
|
|
925
|
+
export function useMinute() {
|
|
926
|
+
const [minute, setMinute] = useState(minuteNow);
|
|
927
|
+
|
|
928
|
+
useEffect(() => {
|
|
929
|
+
minuteListeners.add(setMinute);
|
|
930
|
+
|
|
931
|
+
if (minuteListeners.size === 1) {
|
|
932
|
+
minuteTimer = setTimeout(tickMinute, 60_000 - (Date.now() % 60_000));
|
|
933
|
+
}
|
|
934
|
+
|
|
935
|
+
// A minute that turned before this effect ran.
|
|
936
|
+
setMinute(minuteNow());
|
|
937
|
+
|
|
938
|
+
return () => {
|
|
939
|
+
minuteListeners.delete(setMinute);
|
|
940
|
+
|
|
941
|
+
if (minuteListeners.size === 0) {
|
|
942
|
+
clearTimeout(minuteTimer);
|
|
943
|
+
}
|
|
944
|
+
};
|
|
945
|
+
}, []);
|
|
946
|
+
|
|
947
|
+
return minute;
|
|
948
|
+
}
|
|
949
|
+
|
|
950
|
+
export function timeAgo(ms) {
|
|
951
|
+
const seconds = Math.max(0, (Date.now() - ms) / 1000);
|
|
952
|
+
|
|
953
|
+
if (seconds < 45) {
|
|
954
|
+
return "now";
|
|
955
|
+
}
|
|
956
|
+
|
|
957
|
+
if (seconds < 3600) {
|
|
958
|
+
return `${Math.round(seconds / 60)}m`;
|
|
959
|
+
}
|
|
960
|
+
|
|
961
|
+
if (seconds < 86400) {
|
|
962
|
+
return `${Math.round(seconds / 3600)}h`;
|
|
963
|
+
}
|
|
964
|
+
|
|
965
|
+
if (seconds < 86400 * 30) {
|
|
966
|
+
return `${Math.round(seconds / 86400)}d`;
|
|
967
|
+
}
|
|
968
|
+
|
|
969
|
+
return new Date(ms).toLocaleDateString();
|
|
970
|
+
}
|
|
971
|
+
|
|
972
|
+
/** Markdown as plain text, for one-line previews such as a quote: no emphasis, code ticks, or markers. */
|
|
973
|
+
export function plainText(markdown) {
|
|
974
|
+
return String(markdown ?? "")
|
|
975
|
+
.replace(/```[^\n]*\n?([\s\S]*?)```/g, "$1")
|
|
976
|
+
.replace(/`([^`]*)`/g, "$1")
|
|
977
|
+
.replace(/!?\[([^\]]*)\]\([^)]*\)/g, "$1")
|
|
978
|
+
.replace(/(\*\*|__)(.+?)\1/g, "$2")
|
|
979
|
+
.replace(/(^|[\s(])[*_]([^*_\s][^*_]*?)[*_](?=[\s).,!?:;]|$)/gm, "$1$2")
|
|
980
|
+
.replace(/^[ \t]{0,3}(#{1,6}[ \t]+|>[ \t]?|[-*+][ \t]+|\d+\.[ \t]+)/gm, "");
|
|
981
|
+
}
|
|
982
|
+
|
|
983
|
+
/** What separates a message to Pi from the list of files attached to it, which the server adds. */
|
|
984
|
+
export const ATTACHMENTS_HEADING = "\n\nAttached files (saved on the server):\n";
|
|
985
|
+
|
|
986
|
+
/**
|
|
987
|
+
* A message to Pi in two: what the person wrote, and the list of attached files if any. One with files alone, sent
|
|
988
|
+
* before 0.14.0, has the heading without the blank line before it.
|
|
989
|
+
*/
|
|
990
|
+
export function splitAttachments(text) {
|
|
991
|
+
return (text.startsWith(ATTACHMENTS_HEADING.trimStart()) ? `\n\n${text}` : text).split(
|
|
992
|
+
ATTACHMENTS_HEADING,
|
|
993
|
+
);
|
|
994
|
+
}
|
|
995
|
+
|
|
996
|
+
/** What a person wrote in a message to Pi, without the list of attached files. */
|
|
997
|
+
export function writtenText(entry) {
|
|
998
|
+
return splitAttachments(entry.text)[0];
|
|
999
|
+
}
|
|
1000
|
+
|
|
1001
|
+
/** What Pi wrote in a reply: its text blocks, without thinking or tool calls. */
|
|
1002
|
+
export function replyText(entry) {
|
|
1003
|
+
return entry.blocks.flatMap((block) => (block.type === "text" ? [block.text] : [])).join("\n");
|
|
1004
|
+
}
|
|
1005
|
+
|
|
1006
|
+
/** `~/x` for paths under home. */
|
|
1007
|
+
export function shortPath(path, home) {
|
|
1008
|
+
if (!path) {
|
|
1009
|
+
return "";
|
|
1010
|
+
}
|
|
1011
|
+
|
|
1012
|
+
if (home && (path === home || path.startsWith(`${home}/`))) {
|
|
1013
|
+
return `~${path.slice(home.length)}`;
|
|
1014
|
+
}
|
|
1015
|
+
|
|
1016
|
+
return path;
|
|
1017
|
+
}
|
|
1018
|
+
|
|
1019
|
+
const ICONS = {
|
|
1020
|
+
menu: "M3 6h18M3 12h18M3 18h18",
|
|
1021
|
+
// PiP: a small orb with a glint.
|
|
1022
|
+
pip: "M12 20a8 8 0 100-16 8 8 0 000 16zM8.5 11a3.5 3.5 0 013.5-3.5",
|
|
1023
|
+
more: "M5 12h.01M12 12h.01M19 12h.01",
|
|
1024
|
+
close: "M6 6l12 12M18 6L6 18",
|
|
1025
|
+
reply: "M9 14L4 9l5-5M4 9h10a6 6 0 016 6v4",
|
|
1026
|
+
send: "M12 19V5M5 12l7-7 7 7",
|
|
1027
|
+
stop: "M7 7h10v10H7z",
|
|
1028
|
+
mic: "M12 3a3 3 0 00-3 3v6a3 3 0 006 0V6a3 3 0 00-3-3zM19 11a7 7 0 01-14 0M12 18v3",
|
|
1029
|
+
clip: "M21 11.5l-8.6 8.6a5 5 0 01-7.1-7.1l8.6-8.6a3.3 3.3 0 014.7 4.7l-8.6 8.6a1.7 1.7 0 01-2.4-2.4l7.9-7.9",
|
|
1030
|
+
plus: "M12 5v14M5 12h14",
|
|
1031
|
+
artifact: "M4 5h16v14H4zM4 9h16M8 5v4",
|
|
1032
|
+
folder: "M3 7a2 2 0 012-2h4l2 2h8a2 2 0 012 2v8a2 2 0 01-2 2H5a2 2 0 01-2-2z",
|
|
1033
|
+
file: "M14 3H7a2 2 0 00-2 2v14a2 2 0 002 2h10a2 2 0 002-2V8zM14 3v5h5",
|
|
1034
|
+
diff: "M14 3H7a2 2 0 00-2 2v14a2 2 0 002 2h10a2 2 0 002-2V8zM14 3v5h5M9 11.5h6M12 8.5v6M9 17.5h6",
|
|
1035
|
+
back: "M15 18l-6-6 6-6",
|
|
1036
|
+
clock: "M12 21a9 9 0 100-18 9 9 0 000 18zM12 7v5l3 2",
|
|
1037
|
+
chevron: "M9 6l6 6-6 6",
|
|
1038
|
+
down: "M6 9l6 6 6-6",
|
|
1039
|
+
up: "M12 19V5M5 12l7-7 7 7",
|
|
1040
|
+
eye: "M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12zM12 15a3 3 0 100-6 3 3 0 000 6z",
|
|
1041
|
+
search: "M11 18a7 7 0 100-14 7 7 0 000 14zM21 21l-4.3-4.3",
|
|
1042
|
+
shield: "M12 3l8 3v6c0 5-3.5 8-8 9-4.5-1-8-4-8-9V6z",
|
|
1043
|
+
external: "M14 4h6v6M20 4l-9 9M18 14v5a1 1 0 01-1 1H5a1 1 0 01-1-1V7a1 1 0 011-1h5",
|
|
1044
|
+
key: "M15 7a4 4 0 11-3.9 4.9L3 20v-3h3v-3h3l1.1-1.1A4 4 0 0115 7z",
|
|
1045
|
+
users: "M16 20v-1a4 4 0 00-4-4H6a4 4 0 00-4 4v1M9 11a4 4 0 100-8 4 4 0 000 8zM22 20v-1a4 4 0 00-3-3.9M16 3.1a4 4 0 010 7.8",
|
|
1046
|
+
sparkle: "M12 3l1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L5 10l5.2-1.8z",
|
|
1047
|
+
chat: "M21 12a8 8 0 01-11.6 7.1L4 20l1-4.6A8 8 0 1121 12z",
|
|
1048
|
+
fork: "M6 3v12M18 9a3 3 0 100-6 3 3 0 000 6zM6 21a3 3 0 100-6 3 3 0 000 6zM18 9a9 9 0 01-9 9",
|
|
1049
|
+
command: "M9 6a3 3 0 10-3 3h12a3 3 0 10-3-3v12a3 3 0 103-3H6a3 3 0 103 3z",
|
|
1050
|
+
sidebar: "M4 4h16v16H4zM9 4v16",
|
|
1051
|
+
tiles: "M3 5h12v14H3zM17 5h4v6h-4zM17 13h4v6h-4z",
|
|
1052
|
+
grid: "M4 4h6v6H4zM14 4h6v6h-6zM4 14h6v6H4zM14 14h6v6h-6z",
|
|
1053
|
+
pin: "M9 4h6M10 4v6l-3 4h10l-3-4V4M12 14v6",
|
|
1054
|
+
star: "M12 3.5l2.6 5.3 5.9.9-4.3 4.1 1 5.8-5.2-2.7-5.2 2.7 1-5.8-4.3-4.1 5.9-.9z",
|
|
1055
|
+
palette:
|
|
1056
|
+
"M12 3a9 9 0 100 18c1 0 1.5-.8 1.5-1.5 0-.4-.2-.8-.4-1.1-.3-.3-.4-.7-.4-1.1 0-.8.7-1.5 1.5-1.5H16a5 5 0 005-5c0-4.4-4-7.8-9-7.8zM7.5 12.5h.01M9.5 8h.01M14.5 8h.01M17 11.5h.01",
|
|
1057
|
+
pulse: "M3 12h4l2-6 4 12 2-6h6",
|
|
1058
|
+
keyboard: "M3 6h18v12H3zM7 10h.01M11 10h.01M15 10h.01M7 14h10",
|
|
1059
|
+
swatch: "M4 4h7v16H4zM11 9l6-4 3 5-9 6M11 16h9v4h-9",
|
|
1060
|
+
home: "M3 11l9-7 9 7M5 10v10h14V10",
|
|
1061
|
+
archive: "M3 4h18v4H3zM5 8v12h14V8M10 12h4",
|
|
1062
|
+
unarchive: "M3 4h18v4H3zM5 8v12h14V8M12 18v-6M9 15l3-3 3 3",
|
|
1063
|
+
unread: "M3 6h18v12H3zM3 7l9 5 9-5M20.5 3.5h.01",
|
|
1064
|
+
check: "M5 12l5 5L20 7",
|
|
1065
|
+
logout: "M15 4h4v16h-4M10 8l-4 4 4 4M6 12h10",
|
|
1066
|
+
globe: "M12 21a9 9 0 100-18 9 9 0 000 18zM3.5 9h17M3.5 15h17M12 3a14 14 0 010 18M12 3a14 14 0 000 18",
|
|
1067
|
+
reload: "M20 12a8 8 0 11-2.3-5.7M20 4v5h-5",
|
|
1068
|
+
copy: "M9 9h10a1 1 0 011 1v10a1 1 0 01-1 1H9a1 1 0 01-1-1V10a1 1 0 011-1zM5 15H4a1 1 0 01-1-1V4a1 1 0 011-1h10a1 1 0 011 1v1",
|
|
1069
|
+
undo: "M9 14L4 9l5-5M4 9h11a5 5 0 010 10h-4",
|
|
1070
|
+
phone: "M8 3h8a1 1 0 011 1v16a1 1 0 01-1 1H8a1 1 0 01-1-1V4a1 1 0 011-1zM11 18h2",
|
|
1071
|
+
tablet: "M5 4h14a1 1 0 011 1v14a1 1 0 01-1 1H5a1 1 0 01-1-1V5a1 1 0 011-1zM11 17h2",
|
|
1072
|
+
monitor: "M3 4h18v12H3zM8 20h8M12 16v4",
|
|
1073
|
+
terminal: "M4 5h16v14H4zM8 10l2 2-2 2M12 14h4",
|
|
1074
|
+
fit: "M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5",
|
|
1075
|
+
// Compact: two rules, and what is between them pressed toward the middle.
|
|
1076
|
+
compact: "M4 3h16M4 21h16M12 6v5M9 8l3 3 3-3M12 18v-5M9 16l3-3 3 3",
|
|
1077
|
+
// Taking turns: a steering wheel.
|
|
1078
|
+
wheel: "M12 3a9 9 0 1 0 0 18 9 9 0 1 0 0-18zM12 10a2 2 0 1 0 0 4 2 2 0 1 0 0-4zM3.3 11.2l6.7.6M20.7 11.2l-6.7.6M12 14v6.9",
|
|
1079
|
+
};
|
|
1080
|
+
|
|
1081
|
+
/** How far each key scrolls a sheet's body, by its height. */
|
|
1082
|
+
const SCROLL_KEYS = {
|
|
1083
|
+
ArrowDown: 0.1,
|
|
1084
|
+
ArrowUp: -0.1,
|
|
1085
|
+
PageDown: 0.9,
|
|
1086
|
+
PageUp: -0.9,
|
|
1087
|
+
" ": 0.9,
|
|
1088
|
+
End: 1e6,
|
|
1089
|
+
Home: -1e6,
|
|
1090
|
+
};
|
|
1091
|
+
|
|
1092
|
+
/**
|
|
1093
|
+
* The keys that scroll a page scroll a sheet focused as a whole (as it is when it opens), when its body holds nothing to
|
|
1094
|
+
* focus: a sheet only read, such as Keyboard shortcuts. One with controls keeps its keys (the menu's arrows).
|
|
1095
|
+
*/
|
|
1096
|
+
function scrollFromKeys(event) {
|
|
1097
|
+
const share = SCROLL_KEYS[event.key];
|
|
1098
|
+
const body = event.currentTarget.querySelector(":scope > .sheet-body");
|
|
1099
|
+
|
|
1100
|
+
if (
|
|
1101
|
+
share === undefined ||
|
|
1102
|
+
event.defaultPrevented ||
|
|
1103
|
+
event.target !== event.currentTarget ||
|
|
1104
|
+
!body ||
|
|
1105
|
+
body.querySelector("a[href], button, input, select, textarea, [tabindex]") ||
|
|
1106
|
+
event.altKey ||
|
|
1107
|
+
event.ctrlKey ||
|
|
1108
|
+
event.metaKey
|
|
1109
|
+
) {
|
|
1110
|
+
return;
|
|
1111
|
+
}
|
|
1112
|
+
|
|
1113
|
+
event.preventDefault();
|
|
1114
|
+
body.scrollTop += (event.shiftKey && event.key === " " ? -1 : 1) * share * body.clientHeight;
|
|
1115
|
+
}
|
|
1116
|
+
|
|
1117
|
+
/** An icon's SVG path, for marks drawn outside Preact (gestures.js); "" for a name that is not one of the icons. */
|
|
1118
|
+
export const iconPath = (name) =>
|
|
1119
|
+
typeof name === "string" && Object.hasOwn(ICONS, name) ? ICONS[name] : "";
|
|
1120
|
+
|
|
1121
|
+
/** Text with the letters at `hits` (indexes) marked, as matches of what someone searched for. */
|
|
1122
|
+
export function Marked({ text, hits }) {
|
|
1123
|
+
if (!hits || hits.length === 0) {
|
|
1124
|
+
return text;
|
|
1125
|
+
}
|
|
1126
|
+
|
|
1127
|
+
const set = new Set(hits);
|
|
1128
|
+
const parts = [];
|
|
1129
|
+
let run = "";
|
|
1130
|
+
let lit = false;
|
|
1131
|
+
|
|
1132
|
+
for (let index = 0; index < text.length; index++) {
|
|
1133
|
+
const on = set.has(index);
|
|
1134
|
+
|
|
1135
|
+
if (on !== lit && run !== "") {
|
|
1136
|
+
parts.push(lit ? html`<mark>${run}</mark>` : run);
|
|
1137
|
+
run = "";
|
|
1138
|
+
}
|
|
1139
|
+
|
|
1140
|
+
lit = on;
|
|
1141
|
+
run += text[index];
|
|
1142
|
+
}
|
|
1143
|
+
|
|
1144
|
+
if (run !== "") {
|
|
1145
|
+
parts.push(lit ? html`<mark>${run}</mark>` : run);
|
|
1146
|
+
}
|
|
1147
|
+
|
|
1148
|
+
return parts;
|
|
1149
|
+
}
|
|
1150
|
+
|
|
1151
|
+
/** One of the app's icons by `name`, or any 24×24 stroked path as `path` (extensions' own icons). */
|
|
1152
|
+
export function Icon({ name, path, size = 20, class: className = "", stroke = 2, part }) {
|
|
1153
|
+
return html`<svg
|
|
1154
|
+
class=${`icon ${className}`}
|
|
1155
|
+
data-part=${part}
|
|
1156
|
+
width=${size}
|
|
1157
|
+
height=${size}
|
|
1158
|
+
viewBox="0 0 24 24"
|
|
1159
|
+
fill="none"
|
|
1160
|
+
stroke="currentColor"
|
|
1161
|
+
stroke-width=${stroke}
|
|
1162
|
+
stroke-linecap="round"
|
|
1163
|
+
stroke-linejoin="round"
|
|
1164
|
+
aria-hidden="true"
|
|
1165
|
+
>
|
|
1166
|
+
<path d=${typeof path === "string" ? path : iconPath(name)} />
|
|
1167
|
+
</svg>`;
|
|
1168
|
+
}
|
|
1169
|
+
|
|
1170
|
+
/**
|
|
1171
|
+
* The app's loaders, after Omarchy's: a quadrant block that steps around a square like a terminal spinner, and a flat
|
|
1172
|
+
* bar that eases toward 70% the way Omarchy's boot screen does while it waits.
|
|
1173
|
+
*/
|
|
1174
|
+
export function Spinner({ label = "Working", hidden = false }) {
|
|
1175
|
+
// Hidden from screen readers beside words that say the same.
|
|
1176
|
+
return hidden
|
|
1177
|
+
? html`<span class="spinner" aria-hidden="true"></span>`
|
|
1178
|
+
: html`<span class="spinner" role="img" aria-label=${label}></span>`;
|
|
1179
|
+
}
|
|
1180
|
+
|
|
1181
|
+
/** A spinner with a short line about what is loading, for sheets and panels. */
|
|
1182
|
+
export function Loader({ label = "Loading" }) {
|
|
1183
|
+
return html`<div class="loader" role="status">
|
|
1184
|
+
<${Spinner} label=${label} />
|
|
1185
|
+
<span>${label}…</span>
|
|
1186
|
+
</div>`;
|
|
1187
|
+
}
|
|
1188
|
+
|
|
1189
|
+
/** The full-screen loader: π over Omarchy's boot bar, and what is happening under it. */
|
|
1190
|
+
export function Boot({ caption = "starting", detail = "", inline = false }) {
|
|
1191
|
+
return html`<div
|
|
1192
|
+
class=${`boot ${inline ? "inline" : ""}`}
|
|
1193
|
+
data-part="boot"
|
|
1194
|
+
role="status"
|
|
1195
|
+
aria-live="polite"
|
|
1196
|
+
>
|
|
1197
|
+
<div class="boot-mark" data-part="brand-mark" aria-hidden="true">π</div>
|
|
1198
|
+
<div class="boot-bar" aria-hidden="true"><span></span></div>
|
|
1199
|
+
<div class="boot-caption">${caption}</div>
|
|
1200
|
+
${detail && html`<div class="boot-detail">${detail}</div>`}
|
|
1201
|
+
</div>`;
|
|
1202
|
+
}
|
|
1203
|
+
|
|
1204
|
+
/** The element each edge was last published from (`useEdge`): one replacing another is not undone as the old goes. */
|
|
1205
|
+
const edges = new Map();
|
|
1206
|
+
|
|
1207
|
+
/**
|
|
1208
|
+
* A ref that keeps `name` (a CSS variable on the page's root) at where its element reaches, `measure(rect)` px, as it
|
|
1209
|
+
* or the window resizes; unset while the element is hidden or gone. PiP's window keeps clear of the session's top bar
|
|
1210
|
+
* with it (`--topbar-h`).
|
|
1211
|
+
*/
|
|
1212
|
+
export function useEdge(name, measure) {
|
|
1213
|
+
const [ref] = useState(() => {
|
|
1214
|
+
let stop = null;
|
|
1215
|
+
|
|
1216
|
+
const publish = (element) => {
|
|
1217
|
+
const root = document.documentElement;
|
|
1218
|
+
|
|
1219
|
+
const update = () => {
|
|
1220
|
+
// Another element took the name since (a frame queued before this one went): it says, not this one.
|
|
1221
|
+
if (edges.get(name) !== element) {
|
|
1222
|
+
return;
|
|
1223
|
+
}
|
|
1224
|
+
|
|
1225
|
+
const rect = element.getBoundingClientRect();
|
|
1226
|
+
|
|
1227
|
+
if (rect.height === 0) {
|
|
1228
|
+
root.style.removeProperty(name);
|
|
1229
|
+
} else {
|
|
1230
|
+
root.style.setProperty(name, `${Math.max(0, Math.round(measure(rect)))}px`);
|
|
1231
|
+
}
|
|
1232
|
+
};
|
|
1233
|
+
|
|
1234
|
+
// Its first measure too, once the page is laid out and before it paints: measured as it mounts, it would lay
|
|
1235
|
+
// out the page in the middle of a draw.
|
|
1236
|
+
const observer = new ResizeObserver(update);
|
|
1237
|
+
// A pane popping in (`popin` scales it) moves the element without resizing it: measured again as an
|
|
1238
|
+
// animation around it ends. Not for the others (a row that rose in, a group that unrolled).
|
|
1239
|
+
let frame = 0;
|
|
1240
|
+
|
|
1241
|
+
const settled = (event) => {
|
|
1242
|
+
if (!(event.target instanceof Node) || !event.target.contains(element)) {
|
|
1243
|
+
return;
|
|
1244
|
+
}
|
|
1245
|
+
|
|
1246
|
+
cancelAnimationFrame(frame);
|
|
1247
|
+
frame = requestAnimationFrame(update);
|
|
1248
|
+
};
|
|
1249
|
+
|
|
1250
|
+
edges.set(name, element);
|
|
1251
|
+
observer.observe(element);
|
|
1252
|
+
addEventListener("resize", update);
|
|
1253
|
+
document.addEventListener("animationend", settled);
|
|
1254
|
+
|
|
1255
|
+
return () => {
|
|
1256
|
+
observer.disconnect();
|
|
1257
|
+
removeEventListener("resize", update);
|
|
1258
|
+
document.removeEventListener("animationend", settled);
|
|
1259
|
+
cancelAnimationFrame(frame);
|
|
1260
|
+
|
|
1261
|
+
if (edges.get(name) === element) {
|
|
1262
|
+
edges.delete(name);
|
|
1263
|
+
root.style.removeProperty(name);
|
|
1264
|
+
}
|
|
1265
|
+
};
|
|
1266
|
+
};
|
|
1267
|
+
|
|
1268
|
+
return (element) => {
|
|
1269
|
+
stop?.();
|
|
1270
|
+
stop = element ? publish(element) : null;
|
|
1271
|
+
};
|
|
1272
|
+
});
|
|
1273
|
+
|
|
1274
|
+
return ref;
|
|
1275
|
+
}
|
|
1276
|
+
|
|
1277
|
+
/**
|
|
1278
|
+
* Say where a scroller has more than it shows: `data-more` is "up", "down", or "both" while it can scroll that way, and
|
|
1279
|
+
* gone while everything shows. The stylesheet fades that edge, so a list whose scrollbar is hidden still says it
|
|
1280
|
+
* scrolls. It follows scrolling, the scroller's size, and what is added to it or taken away. Returns a ref callback:
|
|
1281
|
+
* give it to the scroller as its `ref`.
|
|
1282
|
+
*/
|
|
1283
|
+
export function useScrollMore() {
|
|
1284
|
+
const [ref] = useState(() => {
|
|
1285
|
+
let stop = null;
|
|
1286
|
+
|
|
1287
|
+
const watch = (element) => {
|
|
1288
|
+
let frame = 0;
|
|
1289
|
+
|
|
1290
|
+
const update = () => {
|
|
1291
|
+
frame = 0;
|
|
1292
|
+
const up = element.scrollTop > 1;
|
|
1293
|
+
const down = element.scrollTop + element.clientHeight < element.scrollHeight - 1;
|
|
1294
|
+
const more = up && down ? "both" : up ? "up" : down ? "down" : null;
|
|
1295
|
+
|
|
1296
|
+
if (more === null) {
|
|
1297
|
+
element.removeAttribute("data-more");
|
|
1298
|
+
} else if (element.dataset.more !== more) {
|
|
1299
|
+
element.dataset.more = more;
|
|
1300
|
+
}
|
|
1301
|
+
};
|
|
1302
|
+
|
|
1303
|
+
const later = () => {
|
|
1304
|
+
frame ||= requestAnimationFrame(update);
|
|
1305
|
+
};
|
|
1306
|
+
|
|
1307
|
+
const sizes = new ResizeObserver(later);
|
|
1308
|
+
const content = new MutationObserver(later);
|
|
1309
|
+
|
|
1310
|
+
sizes.observe(element);
|
|
1311
|
+
content.observe(element, { childList: true, subtree: true });
|
|
1312
|
+
element.addEventListener("scroll", later, { passive: true });
|
|
1313
|
+
later();
|
|
1314
|
+
|
|
1315
|
+
return () => {
|
|
1316
|
+
cancelAnimationFrame(frame);
|
|
1317
|
+
sizes.disconnect();
|
|
1318
|
+
content.disconnect();
|
|
1319
|
+
element.removeEventListener("scroll", later);
|
|
1320
|
+
};
|
|
1321
|
+
};
|
|
1322
|
+
|
|
1323
|
+
return (element) => {
|
|
1324
|
+
stop?.();
|
|
1325
|
+
stop = element ? watch(element) : null;
|
|
1326
|
+
};
|
|
1327
|
+
});
|
|
1328
|
+
|
|
1329
|
+
return ref;
|
|
1330
|
+
}
|
|
1331
|
+
|
|
1332
|
+
/**
|
|
1333
|
+
* Keep showing a value for `ms` after it goes away (null or undefined), so what it shows can animate out. Returns the
|
|
1334
|
+
* value to show and whether it is leaving.
|
|
1335
|
+
*/
|
|
1336
|
+
export function usePresence(value, ms = 200) {
|
|
1337
|
+
const [kept, setKept] = useState(value ?? null);
|
|
1338
|
+
const [leaving, setLeaving] = useState(false);
|
|
1339
|
+
const timer = useRef(0);
|
|
1340
|
+
|
|
1341
|
+
useEffect(() => {
|
|
1342
|
+
clearTimeout(timer.current);
|
|
1343
|
+
|
|
1344
|
+
if (value !== null && value !== undefined) {
|
|
1345
|
+
setKept(value);
|
|
1346
|
+
setLeaving(false);
|
|
1347
|
+
} else if (kept !== null) {
|
|
1348
|
+
if (document.documentElement.dataset.motion === "reduced") {
|
|
1349
|
+
setKept(null);
|
|
1350
|
+
|
|
1351
|
+
return;
|
|
1352
|
+
}
|
|
1353
|
+
|
|
1354
|
+
setLeaving(true);
|
|
1355
|
+
timer.current = setTimeout(() => {
|
|
1356
|
+
setKept(null);
|
|
1357
|
+
setLeaving(false);
|
|
1358
|
+
}, ms);
|
|
1359
|
+
}
|
|
1360
|
+
}, [value]);
|
|
1361
|
+
useEffect(() => () => clearTimeout(timer.current), []);
|
|
1362
|
+
|
|
1363
|
+
return value !== null && value !== undefined
|
|
1364
|
+
? [value, false]
|
|
1365
|
+
: [kept, leaving || kept !== null];
|
|
1366
|
+
}
|
|
1367
|
+
|
|
1368
|
+
/**
|
|
1369
|
+
* Where a sliding indicator goes: the offset and size of the element matching `selector` inside `ref`. null when there
|
|
1370
|
+
* is none, or it is in a folded group. `instant` is true the first time it shows, so it appears in place instead of
|
|
1371
|
+
* sliding in from the top. `key` says which element is selected: it is measured again when `key` changes, and when the
|
|
1372
|
+
* list resizes or settles, not after every render. Measured after every render, each copy of the list laid the page out
|
|
1373
|
+
* early, and Back to the list on a phone froze the longer for it.
|
|
1374
|
+
*/
|
|
1375
|
+
export function useSlide(ref, selector, axis = "y", key = undefined) {
|
|
1376
|
+
const [box, setBox] = useState(null);
|
|
1377
|
+
const hidden = useRef(true);
|
|
1378
|
+
|
|
1379
|
+
const measure = () => {
|
|
1380
|
+
const target = ref.current?.querySelector(selector);
|
|
1381
|
+
const next =
|
|
1382
|
+
target && !target.closest(".closed")
|
|
1383
|
+
? axis === "y"
|
|
1384
|
+
? { at: target.offsetTop, size: target.offsetHeight }
|
|
1385
|
+
: { at: target.offsetLeft, size: target.offsetWidth }
|
|
1386
|
+
: null;
|
|
1387
|
+
|
|
1388
|
+
setBox((box) => (next?.at === box?.at && next?.size === box?.size ? box : next));
|
|
1389
|
+
};
|
|
1390
|
+
|
|
1391
|
+
useLayoutEffect(measure, [key]);
|
|
1392
|
+
// Rows move without a render while a group folds, or the window resizes: measure again when they settle.
|
|
1393
|
+
useEffect(() => {
|
|
1394
|
+
const host = ref.current;
|
|
1395
|
+
|
|
1396
|
+
if (!host) {
|
|
1397
|
+
return;
|
|
1398
|
+
}
|
|
1399
|
+
|
|
1400
|
+
const settle = (event) => event.target !== host && measure();
|
|
1401
|
+
// A theme's stylesheets can move the element without resizing the list.
|
|
1402
|
+
const again = () => measure();
|
|
1403
|
+
|
|
1404
|
+
host.addEventListener("transitionend", settle);
|
|
1405
|
+
document.addEventListener("pocket:theme", again);
|
|
1406
|
+
const observer =
|
|
1407
|
+
typeof ResizeObserver === "function" ? new ResizeObserver(() => measure()) : null;
|
|
1408
|
+
|
|
1409
|
+
observer?.observe(host);
|
|
1410
|
+
|
|
1411
|
+
return () => {
|
|
1412
|
+
host.removeEventListener("transitionend", settle);
|
|
1413
|
+
document.removeEventListener("pocket:theme", again);
|
|
1414
|
+
observer?.disconnect();
|
|
1415
|
+
};
|
|
1416
|
+
}, [ref.current]);
|
|
1417
|
+
const instant = hidden.current;
|
|
1418
|
+
|
|
1419
|
+
useEffect(() => {
|
|
1420
|
+
hidden.current = box === null;
|
|
1421
|
+
});
|
|
1422
|
+
|
|
1423
|
+
return box === null ? null : { ...box, instant };
|
|
1424
|
+
}
|
|
1425
|
+
|
|
1426
|
+
/** The bar a `useSlide` box draws. */
|
|
1427
|
+
export function Slide({ box, axis = "y" }) {
|
|
1428
|
+
if (!box) {
|
|
1429
|
+
return null;
|
|
1430
|
+
}
|
|
1431
|
+
|
|
1432
|
+
const style =
|
|
1433
|
+
axis === "y"
|
|
1434
|
+
? `transform:translateY(${box.at}px);height:${box.size}px`
|
|
1435
|
+
: `transform:translateX(${box.at}px);width:${box.size}px`;
|
|
1436
|
+
|
|
1437
|
+
return html`<span
|
|
1438
|
+
class=${`slide-${axis} ${box.instant ? "instant" : ""}`}
|
|
1439
|
+
data-part="segment-thumb"
|
|
1440
|
+
style=${style}
|
|
1441
|
+
aria-hidden="true"
|
|
1442
|
+
></span>`;
|
|
1443
|
+
}
|
|
1444
|
+
|
|
1445
|
+
/**
|
|
1446
|
+
* Which side of the screen an element stands on, `left` or `right`, as it is laid out now: a theme may move the sidebar
|
|
1447
|
+
* or the drawer to the right, and what is dragged by its edge must follow. Looked at again as the window resizes and
|
|
1448
|
+
* when a theme's stylesheets load (`pocket:theme`, from `theme.js`). `of` gives the element from the ref's.
|
|
1449
|
+
*/
|
|
1450
|
+
export function useSide(ref, of = (element) => element) {
|
|
1451
|
+
const [side, setSide] = useState("left");
|
|
1452
|
+
const look = useRef(null);
|
|
1453
|
+
|
|
1454
|
+
const watched = useRef(null);
|
|
1455
|
+
const watcher = useRef(null);
|
|
1456
|
+
|
|
1457
|
+
look.current = () => {
|
|
1458
|
+
const element = ref.current && of(ref.current);
|
|
1459
|
+
const box = element?.getBoundingClientRect();
|
|
1460
|
+
|
|
1461
|
+
if (box && box.width > 0) {
|
|
1462
|
+
setSide(box.left + box.width / 2 > innerWidth / 2 ? "right" : "left");
|
|
1463
|
+
}
|
|
1464
|
+
};
|
|
1465
|
+
|
|
1466
|
+
// Measured when the browser lays the element out anyway, before the frame is painted: as it comes, shows, or changes
|
|
1467
|
+
// size (a ResizeObserver says so). Measured after each draw instead, it laid the whole page out early, and opening a
|
|
1468
|
+
// session froze the longer for it on a phone.
|
|
1469
|
+
useLayoutEffect(() => {
|
|
1470
|
+
const element = ref.current && of(ref.current);
|
|
1471
|
+
|
|
1472
|
+
if (element === watched.current) {
|
|
1473
|
+
return;
|
|
1474
|
+
}
|
|
1475
|
+
|
|
1476
|
+
watched.current = element;
|
|
1477
|
+
watcher.current ??= new ResizeObserver(() => look.current());
|
|
1478
|
+
watcher.current.disconnect();
|
|
1479
|
+
|
|
1480
|
+
if (element) {
|
|
1481
|
+
watcher.current.observe(element);
|
|
1482
|
+
}
|
|
1483
|
+
});
|
|
1484
|
+
// And when the window or the theme changes, which can move it without resizing it.
|
|
1485
|
+
useLayoutEffect(() => {
|
|
1486
|
+
const again = () => look.current();
|
|
1487
|
+
|
|
1488
|
+
addEventListener("resize", again);
|
|
1489
|
+
document.addEventListener("pocket:theme", again);
|
|
1490
|
+
|
|
1491
|
+
return () => {
|
|
1492
|
+
removeEventListener("resize", again);
|
|
1493
|
+
document.removeEventListener("pocket:theme", again);
|
|
1494
|
+
watcher.current?.disconnect();
|
|
1495
|
+
};
|
|
1496
|
+
}, []);
|
|
1497
|
+
|
|
1498
|
+
return side;
|
|
1499
|
+
}
|
|
1500
|
+
|
|
1501
|
+
/**
|
|
1502
|
+
* A rail button's state for themes (`data-state`): `open` while what it opens shows, `busy` while it counts work that
|
|
1503
|
+
* goes on; both, or neither (undefined).
|
|
1504
|
+
*/
|
|
1505
|
+
export const railState = (open, busy = false) =>
|
|
1506
|
+
[open && "open", busy && "busy"].filter(Boolean).join(" ") || undefined;
|
|
1507
|
+
|
|
1508
|
+
/** Keys as they are on this device: ⌘ on Apple keyboards, Ctrl elsewhere. */
|
|
1509
|
+
export const APPLE = /Mac|iPhone|iPad/.test(navigator.platform ?? "");
|
|
1510
|
+
|
|
1511
|
+
const MOD = APPLE ? "⌘" : "Ctrl";
|
|
1512
|
+
|
|
1513
|
+
/** A keyboard shortcut as key caps: `Keys keys="Mod K"`. */
|
|
1514
|
+
export function Keys({ keys }) {
|
|
1515
|
+
return keys.split(" ").map((key) => html`<kbd>${key === "Mod" ? MOD : key}</kbd>`);
|
|
1516
|
+
}
|
|
1517
|
+
|
|
1518
|
+
/**
|
|
1519
|
+
* Something inside failed to render: show nothing there instead of taking the whole app down. A new `reset` value (the
|
|
1520
|
+
* sheet opened again) tries again.
|
|
1521
|
+
*/
|
|
1522
|
+
export class Boundary extends Component {
|
|
1523
|
+
state = { failed: false };
|
|
1524
|
+
|
|
1525
|
+
componentDidCatch(error) {
|
|
1526
|
+
console.error(error);
|
|
1527
|
+
this.setState({ failed: true });
|
|
1528
|
+
}
|
|
1529
|
+
|
|
1530
|
+
componentDidUpdate(previous) {
|
|
1531
|
+
if (this.state.failed && previous.reset !== this.props.reset) {
|
|
1532
|
+
this.setState({ failed: false });
|
|
1533
|
+
}
|
|
1534
|
+
}
|
|
1535
|
+
|
|
1536
|
+
render({ children }, { failed }) {
|
|
1537
|
+
return failed ? null : children;
|
|
1538
|
+
}
|
|
1539
|
+
}
|
|
1540
|
+
|
|
1541
|
+
/**
|
|
1542
|
+
* Whether the store changed in none of `keys` between two states. A change to nothing at all is a change:
|
|
1543
|
+
* `store.set({})` draws everything again (a media query that changed, say).
|
|
1544
|
+
*/
|
|
1545
|
+
function quietFor(keys, before, after) {
|
|
1546
|
+
if (before === after) {
|
|
1547
|
+
return false;
|
|
1548
|
+
}
|
|
1549
|
+
|
|
1550
|
+
let changed = false;
|
|
1551
|
+
|
|
1552
|
+
for (const key in after) {
|
|
1553
|
+
if (before[key] !== after[key]) {
|
|
1554
|
+
if (keys.has(key)) {
|
|
1555
|
+
return false;
|
|
1556
|
+
}
|
|
1557
|
+
|
|
1558
|
+
changed = true;
|
|
1559
|
+
}
|
|
1560
|
+
}
|
|
1561
|
+
|
|
1562
|
+
for (const key in before) {
|
|
1563
|
+
if (!(key in after)) {
|
|
1564
|
+
return false;
|
|
1565
|
+
}
|
|
1566
|
+
}
|
|
1567
|
+
|
|
1568
|
+
return changed;
|
|
1569
|
+
}
|
|
1570
|
+
|
|
1571
|
+
const sameProps = (a, b) =>
|
|
1572
|
+
Object.keys(a).length === Object.keys(b).length &&
|
|
1573
|
+
Object.keys(a).every((key) => Object.is(a[key], b[key]));
|
|
1574
|
+
|
|
1575
|
+
class DrawnFor extends Component {
|
|
1576
|
+
shouldComponentUpdate(next) {
|
|
1577
|
+
return !(
|
|
1578
|
+
next.component === this.props.component &&
|
|
1579
|
+
quietFor(next.keys, this.props.state, next.state) &&
|
|
1580
|
+
sameProps(this.props.props, next.props)
|
|
1581
|
+
);
|
|
1582
|
+
}
|
|
1583
|
+
|
|
1584
|
+
render({ component, props }) {
|
|
1585
|
+
return h(component, props);
|
|
1586
|
+
}
|
|
1587
|
+
}
|
|
1588
|
+
|
|
1589
|
+
/**
|
|
1590
|
+
* `component`, drawn again only when the store changes in one of `keys`, its props change, or `store.set({})` asks
|
|
1591
|
+
* everything to draw again: for big parts that read little of the store, such as the session list. `keys` must name
|
|
1592
|
+
* every key of the store it reads as it draws, and every key the functions it calls read (`prefs()` reads
|
|
1593
|
+
* `appearance`, `canSteer()` reads `me`): a key left out shows stale data. What it reads only in an event handler
|
|
1594
|
+
* does not count. Its own state draws it again as usual.
|
|
1595
|
+
*/
|
|
1596
|
+
export function drawnFor(keys, component) {
|
|
1597
|
+
const set = new Set(keys);
|
|
1598
|
+
const Wrapped = (props) => h(DrawnFor, { component, props, keys: set, state: store.state });
|
|
1599
|
+
|
|
1600
|
+
Wrapped.displayName = component.name;
|
|
1601
|
+
|
|
1602
|
+
return Wrapped;
|
|
1603
|
+
}
|
|
1604
|
+
|
|
1605
|
+
class Memo extends Component {
|
|
1606
|
+
shouldComponentUpdate(next) {
|
|
1607
|
+
const { ignored } = next;
|
|
1608
|
+
const before = this.props.props;
|
|
1609
|
+
const after = next.props;
|
|
1610
|
+
const keys = Object.keys(after).filter((key) => !ignored.includes(key));
|
|
1611
|
+
|
|
1612
|
+
return (
|
|
1613
|
+
next.component !== this.props.component ||
|
|
1614
|
+
Object.keys(before).length !== Object.keys(after).length ||
|
|
1615
|
+
keys.some((key) => !Object.is(before[key], after[key]))
|
|
1616
|
+
);
|
|
1617
|
+
}
|
|
1618
|
+
|
|
1619
|
+
render({ component, props }) {
|
|
1620
|
+
return h(component, props);
|
|
1621
|
+
}
|
|
1622
|
+
}
|
|
1623
|
+
|
|
1624
|
+
/**
|
|
1625
|
+
* `component`, drawn again only when its props change (each compared with `Object.is`) or its own state does. It must
|
|
1626
|
+
* read nothing else as it draws, such as `store.state`: what it needs comes as props. `ignored` names props it reads
|
|
1627
|
+
* only as it mounts, whose change alone does not draw it again.
|
|
1628
|
+
*/
|
|
1629
|
+
export function memo(component, ignored = []) {
|
|
1630
|
+
const Wrapped = (props) => h(Memo, { component, props, ignored });
|
|
1631
|
+
|
|
1632
|
+
Wrapped.displayName = component.name;
|
|
1633
|
+
|
|
1634
|
+
return Wrapped;
|
|
1635
|
+
}
|
|
1636
|
+
|
|
1637
|
+
/** Phones: sheets from the bottom edge, which drag back down to close, and menus that a swipe closes. */
|
|
1638
|
+
export const BOTTOM_SHEETS = matchMedia("(max-width: 699px)");
|
|
1639
|
+
|
|
1640
|
+
/**
|
|
1641
|
+
* Wide screens, where the sidebar and the home screen's splash show (style.css's 960px). Narrower, the app does not
|
|
1642
|
+
* draw them at all: hidden, they cost a phone the list's whole draw again.
|
|
1643
|
+
*/
|
|
1644
|
+
export const WIDE = matchMedia("(min-width: 960px)");
|
|
1645
|
+
|
|
1646
|
+
/** No pointer that hovers (a touch screen): what only hovering shows, such as a row's buttons, is not drawn. */
|
|
1647
|
+
export const NO_HOVER = matchMedia("(hover: none)");
|
|
1648
|
+
|
|
1649
|
+
// Each changing (a window resized, a phone turned, a mouse plugged in) draws the app again, with or without them: a sheet
|
|
1650
|
+
// open as the phone turns gets its drag to close, or lets go of it.
|
|
1651
|
+
for (const query of [WIDE, NO_HOVER, BOTTOM_SHEETS]) {
|
|
1652
|
+
query.addEventListener("change", () => store.set({}));
|
|
1653
|
+
}
|
|
1654
|
+
|
|
1655
|
+
/** The sheet host supplies a back action only when another sheet is under this one. */
|
|
1656
|
+
export const SheetBack = createContext(null);
|
|
1657
|
+
|
|
1658
|
+
/**
|
|
1659
|
+
* The open sheet's type and whether it is closing (`sheets.js`), which `Sheet` puts on itself for themes: `data-sheet`,
|
|
1660
|
+
* and `data-state="closing"`.
|
|
1661
|
+
*/
|
|
1662
|
+
export const SheetInfo = createContext(null);
|
|
1663
|
+
|
|
1664
|
+
/**
|
|
1665
|
+
* A scrim's press: it closes its layer only when it starts on the scrim itself, not on what the scrim holds, and only
|
|
1666
|
+
* with the main button (a right click opens the browser's menu, and must not close anything; on a Mac, Ctrl+click is
|
|
1667
|
+
* one).
|
|
1668
|
+
*/
|
|
1669
|
+
export const scrimPress = (close) => (event) =>
|
|
1670
|
+
event.button === 0 &&
|
|
1671
|
+
!(APPLE && event.ctrlKey) &&
|
|
1672
|
+
event.target === event.currentTarget &&
|
|
1673
|
+
close();
|
|
1674
|
+
|
|
1675
|
+
/** A bottom sheet on phones, a centered dialog on wide screens. */
|
|
1676
|
+
export function Sheet({ title, onClose, children, wide = false, actions = null, className = "" }) {
|
|
1677
|
+
const ref = useRef(null);
|
|
1678
|
+
const onBack = useContext(SheetBack);
|
|
1679
|
+
const info = useContext(SheetInfo);
|
|
1680
|
+
|
|
1681
|
+
useDragToClose(ref, { dir: "down", onClose, enabled: BOTTOM_SHEETS.matches });
|
|
1682
|
+
|
|
1683
|
+
// Not the Esc that ends an input method's composing, which belongs to the field.
|
|
1684
|
+
useEffect(() => {
|
|
1685
|
+
const onKey = (event) =>
|
|
1686
|
+
event.key === "Escape" && !event.isComposing && event.keyCode !== 229 && onClose();
|
|
1687
|
+
|
|
1688
|
+
addEventListener("keydown", onKey);
|
|
1689
|
+
|
|
1690
|
+
return () => removeEventListener("keydown", onKey);
|
|
1691
|
+
}, [onClose]);
|
|
1692
|
+
// Keys go to the sheet, not the message box behind it, unless something inside already took focus. Its field marked
|
|
1693
|
+
// autofocus takes them where a keyboard is at hand (the browser skips the attribute, the page already having focus);
|
|
1694
|
+
// on touch screens the sheet does, so no keyboard pops up over it.
|
|
1695
|
+
useEffect(() => {
|
|
1696
|
+
const sheet = ref.current;
|
|
1697
|
+
|
|
1698
|
+
if (sheet && !sheet.contains(document.activeElement)) {
|
|
1699
|
+
const field = matchMedia("(pointer: coarse)").matches
|
|
1700
|
+
? null
|
|
1701
|
+
: sheet.querySelector("[autofocus]");
|
|
1702
|
+
|
|
1703
|
+
(field ?? sheet).focus({ preventScroll: true });
|
|
1704
|
+
}
|
|
1705
|
+
}, []);
|
|
1706
|
+
|
|
1707
|
+
return html`<div
|
|
1708
|
+
class="overlay"
|
|
1709
|
+
data-part="scrim"
|
|
1710
|
+
data-for="sheet"
|
|
1711
|
+
onMouseDown=${scrimPress(onClose)}
|
|
1712
|
+
>
|
|
1713
|
+
<section
|
|
1714
|
+
class=${`sheet ${wide ? "wide" : ""} ${className}`}
|
|
1715
|
+
data-part="sheet"
|
|
1716
|
+
data-sheet=${info?.type ?? undefined}
|
|
1717
|
+
data-size=${wide ? "wide" : undefined}
|
|
1718
|
+
data-state=${info?.closing ? "closing" : undefined}
|
|
1719
|
+
ref=${ref}
|
|
1720
|
+
role="dialog"
|
|
1721
|
+
aria-modal="true"
|
|
1722
|
+
aria-label=${title}
|
|
1723
|
+
tabindex="-1"
|
|
1724
|
+
onKeyDown=${scrollFromKeys}
|
|
1725
|
+
>
|
|
1726
|
+
<header class="sheet-head" data-part="sheet-head">
|
|
1727
|
+
<div class="grip" aria-hidden="true"></div>
|
|
1728
|
+
${
|
|
1729
|
+
onBack &&
|
|
1730
|
+
html`<button class="icon-button sheet-back" onClick=${onBack} aria-label="Back">
|
|
1731
|
+
<${Icon} name="back" size=${18} />
|
|
1732
|
+
</button>`
|
|
1733
|
+
}
|
|
1734
|
+
<h2>${title}</h2>
|
|
1735
|
+
${actions}
|
|
1736
|
+
<button class="icon-button" onClick=${onClose} aria-label="Close">
|
|
1737
|
+
<${Icon} name="close" />
|
|
1738
|
+
</button>
|
|
1739
|
+
</header>
|
|
1740
|
+
<div class="sheet-body" data-part="sheet-body">${children}</div>
|
|
1741
|
+
</section>
|
|
1742
|
+
</div>`;
|
|
1743
|
+
}
|
|
1744
|
+
|
|
1745
|
+
/** What Tab reaches in `box`, in order. */
|
|
1746
|
+
function tabStops(box) {
|
|
1747
|
+
const all = box.querySelectorAll(
|
|
1748
|
+
'a[href], button, input, select, textarea, iframe, summary, [tabindex], [contenteditable="true"]',
|
|
1749
|
+
);
|
|
1750
|
+
|
|
1751
|
+
return [...all].filter(
|
|
1752
|
+
(each) =>
|
|
1753
|
+
each.tabIndex >= 0 &&
|
|
1754
|
+
!each.disabled &&
|
|
1755
|
+
!each.closest("[inert]") &&
|
|
1756
|
+
(each.checkVisibility?.({ visibilityProperty: true, checkVisibilityCSS: true }) ??
|
|
1757
|
+
each.getClientRects().length > 0),
|
|
1758
|
+
);
|
|
1759
|
+
}
|
|
1760
|
+
|
|
1761
|
+
// Tab stays in the dialog on top (a sheet, a menu, the Files tile or Browser panel over the app), as in a browser's own
|
|
1762
|
+
// modal dialog: past its last control it goes round to the first, and from outside it goes in.
|
|
1763
|
+
addEventListener("keydown", (event) => {
|
|
1764
|
+
if (
|
|
1765
|
+
event.key !== "Tab" ||
|
|
1766
|
+
event.defaultPrevented ||
|
|
1767
|
+
event.altKey ||
|
|
1768
|
+
event.ctrlKey ||
|
|
1769
|
+
event.metaKey
|
|
1770
|
+
) {
|
|
1771
|
+
return;
|
|
1772
|
+
}
|
|
1773
|
+
|
|
1774
|
+
const box = [...document.querySelectorAll('[aria-modal="true"]')]
|
|
1775
|
+
.filter((each) => !each.closest("[inert]"))
|
|
1776
|
+
.at(-1);
|
|
1777
|
+
|
|
1778
|
+
if (!box) {
|
|
1779
|
+
return;
|
|
1780
|
+
}
|
|
1781
|
+
|
|
1782
|
+
const active = document.activeElement;
|
|
1783
|
+
|
|
1784
|
+
// Focus in a layer that comes after the dialog and is not one itself (PiP's window, or the drawer, over a covering
|
|
1785
|
+
// Files tile or Browser panel) is above it: Tab moves there, as before.
|
|
1786
|
+
if (
|
|
1787
|
+
active !== null &&
|
|
1788
|
+
!box.contains(active) &&
|
|
1789
|
+
box.compareDocumentPosition(active) & Node.DOCUMENT_POSITION_FOLLOWING
|
|
1790
|
+
) {
|
|
1791
|
+
return;
|
|
1792
|
+
}
|
|
1793
|
+
|
|
1794
|
+
const stops = tabStops(box);
|
|
1795
|
+
const toward = event.shiftKey
|
|
1796
|
+
? Node.DOCUMENT_POSITION_PRECEDING
|
|
1797
|
+
: Node.DOCUMENT_POSITION_FOLLOWING;
|
|
1798
|
+
const more =
|
|
1799
|
+
box.contains(active) &&
|
|
1800
|
+
stops.some((each) => each !== active && active.compareDocumentPosition(each) & toward);
|
|
1801
|
+
|
|
1802
|
+
if (!more) {
|
|
1803
|
+
event.preventDefault();
|
|
1804
|
+
(event.shiftKey ? stops.at(-1) : stops[0])?.focus();
|
|
1805
|
+
}
|
|
1806
|
+
});
|
|
1807
|
+
|
|
1808
|
+
/**
|
|
1809
|
+
* Where a menu opens from the control `selector` names: above it and aligned with it, or below it for a control near the
|
|
1810
|
+
* top of the screen, within what shows of the page (a phone's keyboard can cover it), and as tall as its rows need up to
|
|
1811
|
+
* a menu's height. Null, for the middle of the screen, when the control is gone or scrolled away, or has too little
|
|
1812
|
+
* room on either side.
|
|
1813
|
+
*/
|
|
1814
|
+
export function popAnchor(selector) {
|
|
1815
|
+
const rect = document.querySelector(selector)?.getBoundingClientRect();
|
|
1816
|
+
|
|
1817
|
+
if (!rect || rect.width === 0) {
|
|
1818
|
+
return null;
|
|
1819
|
+
}
|
|
1820
|
+
|
|
1821
|
+
const top = visualViewport?.offsetTop ?? 0;
|
|
1822
|
+
const bottom = top + (visualViewport?.height ?? innerHeight);
|
|
1823
|
+
|
|
1824
|
+
// Scrolled away above. One under a phone's keyboard opens from the keyboard's top edge.
|
|
1825
|
+
if (rect.bottom < top) {
|
|
1826
|
+
return null;
|
|
1827
|
+
}
|
|
1828
|
+
|
|
1829
|
+
const width = Math.min(420, innerWidth - 16);
|
|
1830
|
+
const left = Math.max(8, Math.min(rect.left, innerWidth - width - 8));
|
|
1831
|
+
const at = Math.min(rect.top, bottom - 8);
|
|
1832
|
+
const above = at - top - 14;
|
|
1833
|
+
|
|
1834
|
+
if (above >= 220) {
|
|
1835
|
+
return { left, bottom: innerHeight - at + 6, width, height: Math.min(540, above) };
|
|
1836
|
+
}
|
|
1837
|
+
|
|
1838
|
+
const below = bottom - rect.bottom - 14;
|
|
1839
|
+
|
|
1840
|
+
return below >= 220 && rect.bottom <= bottom
|
|
1841
|
+
? { left, top: rect.bottom + 6, width, height: Math.min(540, below), down: true }
|
|
1842
|
+
: null;
|
|
1843
|
+
}
|
|
1844
|
+
|
|
1845
|
+
/** A `popAnchor` as a menu's style: nothing for the middle of the screen. */
|
|
1846
|
+
export const anchorStyle = (anchor) =>
|
|
1847
|
+
anchor
|
|
1848
|
+
? `left:${anchor.left}px;${anchor.down ? `top:${anchor.top}px` : `bottom:${anchor.bottom}px`};width:${anchor.width}px;max-height:${anchor.height}px`
|
|
1849
|
+
: "";
|
|
1850
|
+
|
|
1851
|
+
/** The short name of a model for chips: "Claude Opus 5.5" stays, long ids lose their date suffix. */
|
|
1852
|
+
export function modelLabel(agent) {
|
|
1853
|
+
if (!agent?.model) {
|
|
1854
|
+
return "No model";
|
|
1855
|
+
}
|
|
1856
|
+
|
|
1857
|
+
return agent.modelName ?? agent.model.modelId.replace(/-\d{8}$/, "");
|
|
1858
|
+
}
|
|
1859
|
+
|
|
1860
|
+
/** An on and off switch, named for screen readers by `label`. */
|
|
1861
|
+
export function Switch({ on, disabled, label, onChange }) {
|
|
1862
|
+
return html`<button
|
|
1863
|
+
type="button"
|
|
1864
|
+
role="switch"
|
|
1865
|
+
aria-checked=${on ? "true" : "false"}
|
|
1866
|
+
aria-label=${label}
|
|
1867
|
+
class=${`switch ${on ? "on" : ""}`}
|
|
1868
|
+
disabled=${disabled}
|
|
1869
|
+
onClick=${onChange}
|
|
1870
|
+
>
|
|
1871
|
+
<span></span>
|
|
1872
|
+
</button>`;
|
|
1873
|
+
}
|
|
1874
|
+
|
|
1875
|
+
/** A row in a menu: a label, an optional hint on the right, and what a tap does. */
|
|
1876
|
+
export function item(label, run, hint) {
|
|
1877
|
+
return html`<button class="list-item" onClick=${run}>
|
|
1878
|
+
<span>${label}</span>
|
|
1879
|
+
${hint && html`<span class="muted small">${hint}</span>`}
|
|
1880
|
+
</button>`;
|
|
1881
|
+
}
|
|
1882
|
+
|
|
1883
|
+
/** Posted JSON laid out for people (Pi gets it compact); anything else as it came. */
|
|
1884
|
+
export function readable(text) {
|
|
1885
|
+
try {
|
|
1886
|
+
return JSON.stringify(JSON.parse(text), null, 2);
|
|
1887
|
+
} catch {
|
|
1888
|
+
return text;
|
|
1889
|
+
}
|
|
1890
|
+
}
|
|
1891
|
+
|
|
1892
|
+
/** A place's tile: its icon, with a count or a dot, and its label. */
|
|
1893
|
+
export function PlaceTile({ place }) {
|
|
1894
|
+
return html`<button
|
|
1895
|
+
type="button"
|
|
1896
|
+
class=${`place ${place.on ? "on" : ""}`}
|
|
1897
|
+
data-place=${place.id}
|
|
1898
|
+
aria-label=${place.count > 0 ? `${place.label}, ${place.count} ${place.counted ?? ""}`.trim() : place.badge ? `${place.label}, ${place.badge}` : place.dot ? `${place.label}, ${place.dotLabel ?? "a page open"}` : place.label}
|
|
1899
|
+
aria-pressed=${place.on === undefined ? undefined : place.on ? "true" : "false"}
|
|
1900
|
+
onClick=${place.run}
|
|
1901
|
+
>
|
|
1902
|
+
<span class="place-icon badge-host">
|
|
1903
|
+
<${Icon} name=${place.icon} path=${place.iconPath} size=${20} />
|
|
1904
|
+
${place.count > 0 && html`<span class="badge">${place.count}</span>`}
|
|
1905
|
+
${place.badge && html`<span class="badge">${place.badge}</span>`}
|
|
1906
|
+
${place.dot && html`<span class="browser-dot" aria-hidden="true"></span>`}
|
|
1907
|
+
</span>
|
|
1908
|
+
<span class="place-label">${place.label}</span>
|
|
1909
|
+
</button>`;
|
|
1910
|
+
}
|