samagotchi 0.185.0 → 0.187.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +37 -1
- data/bin/chi +2 -0
- data/docs/cli.md +1 -0
- data/docs/configuration.md +18 -0
- data/docs/guardrails.md +13 -0
- data/docs/internals/bridge.md +1 -0
- data/docs/internals/engine.md +15 -1
- data/docs/internals/inline-widgets.md +18 -0
- data/docs/internals/pages.md +172 -0
- data/docs/internals/prompt-caching.md +14 -0
- data/docs/internals/remote-sessions.md +7 -0
- data/docs/internals/web-frontend.md +5 -4
- data/docs/memory.md +7 -0
- data/docs/pages.md +150 -0
- data/docs/thin-clients.md +67 -2
- data/lib/samagotchi/bridge.rb +1 -1
- data/lib/samagotchi/bundles/system/manifest.yml +5 -2
- data/lib/samagotchi/bundles/system/self_map.md +5 -1
- data/lib/samagotchi/bundles/system/skill_pages.md +93 -0
- data/lib/samagotchi/config.rb +3 -1
- data/lib/samagotchi/context_absorber.rb +5 -2
- data/lib/samagotchi/engine.rb +9 -2
- data/lib/samagotchi/inline_widgets.rb +65 -0
- data/lib/samagotchi/llm/chat_loop.rb +16 -2
- data/lib/samagotchi/page_command.rb +234 -0
- data/lib/samagotchi/pages/builder.rb +187 -0
- data/lib/samagotchi/pages/launch.rb +187 -0
- data/lib/samagotchi/pages/runner.rb +154 -0
- data/lib/samagotchi/pages/store.rb +143 -0
- data/lib/samagotchi/pages.rb +119 -0
- data/lib/samagotchi/plain_reply.rb +75 -0
- data/lib/samagotchi/reply_for.rb +254 -0
- data/lib/samagotchi/run_options.rb +1 -0
- data/lib/samagotchi/session_access/ask.rb +5 -2
- data/lib/samagotchi/session_access/contract.rb +1 -1
- data/lib/samagotchi/session_access/exchange/token.rb +42 -7
- data/lib/samagotchi/session_access/exchange.rb +5 -2
- data/lib/samagotchi/session_access/local.rb +4 -2
- data/lib/samagotchi/session_access/remote.rb +5 -1
- data/lib/samagotchi/session_manager/delivery.rb +36 -6
- data/lib/samagotchi/steer.rb +30 -8
- data/lib/samagotchi/turn_anchors.rb +65 -17
- data/lib/samagotchi/turn_checkpoint.rb +5 -3
- data/lib/samagotchi/version.rb +1 -1
- data/lib/samagotchi/web/app.rb +6 -6
- data/lib/samagotchi/web/ask_routes.rb +62 -17
- data/lib/samagotchi/web/page_routes.rb +116 -0
- data/lib/samagotchi/web/participant_access.rb +1 -1
- data/lib/samagotchi/web/public/app.js +24 -84
- data/lib/samagotchi/web/public/index.html +3 -0
- data/lib/samagotchi/web/public/page_blocks.js +58 -0
- data/lib/samagotchi/web/public/page_links.js +33 -0
- data/lib/samagotchi/web/public/page_model.js +68 -0
- data/lib/samagotchi/web/public/page_route.js +24 -0
- data/lib/samagotchi/web/public/page_table.js +74 -0
- data/lib/samagotchi/web/public/page_table_model.js +76 -0
- data/lib/samagotchi/web/public/page_view.js +218 -0
- data/lib/samagotchi/web/public/pages.css +77 -0
- data/lib/samagotchi/web/public/pages_group.js +65 -0
- data/lib/samagotchi/web/public/peer_text.js +22 -5
- data/lib/samagotchi/web/public/views.js +161 -0
- data/lib/samagotchi/web/session_access_routes.rb +30 -2
- data/lib/samagotchi/web/session_control.rb +21 -2
- data/lib/samagotchi/web/viewer.rb +1 -1
- data/lib/samagotchi/worker.rb +2 -1
- metadata +23 -1
|
@@ -81,9 +81,11 @@ import { PROMPT_LINE_PX, PROMPT_MIN_PX } from "./composer_size.js";
|
|
|
81
81
|
import { mountComposer } from "./composer_mount.js";
|
|
82
82
|
import { hasHistory, historyLoader } from "./participant_history.js";
|
|
83
83
|
import { createCommandList } from "./command_list.js";
|
|
84
|
-
import {
|
|
85
|
-
import {
|
|
86
|
-
import {
|
|
84
|
+
import { sessionHash } from "./route.js";
|
|
85
|
+
import { createViews } from "./views.js";
|
|
86
|
+
import { createPageView } from "./page_view.js";
|
|
87
|
+
import { createPagesGroup } from "./pages_group.js";
|
|
88
|
+
import { installPageLinks } from "./page_links.js";
|
|
87
89
|
import { createOwnerClaim } from "./owner_claim.js";
|
|
88
90
|
import { createOwnerVerify } from "./owner_verify.js";
|
|
89
91
|
import { scopeDir, scopeTemplate } from "./scope.js";
|
|
@@ -92,7 +94,7 @@ import { render } from "./vendor/lit-html.js";
|
|
|
92
94
|
import { shouldFollowScroll } from "./scroll.js";
|
|
93
95
|
import { createStripHidden } from "./strip_hidden.js";
|
|
94
96
|
import { waitingOn } from "./notify.js";
|
|
95
|
-
import { applySessionEvent
|
|
97
|
+
import { applySessionEvent } from "./sessions_list.js";
|
|
96
98
|
import { createNotifications } from "./notifications.js";
|
|
97
99
|
import { renameShown, tabTitle, topBarTitle } from "./session_title.js";
|
|
98
100
|
import {
|
|
@@ -563,7 +565,7 @@ const sessionSync = createSessionSync({
|
|
|
563
565
|
store, historyEl, emptyEl, getSession, openStream,
|
|
564
566
|
liveTurn, turnDom, questionCards, contextChips, participantsControl,
|
|
565
567
|
view: sessionView,
|
|
566
|
-
page: { clearNotice, setSessionHash, setTurnRunning, setLiveStatus, replaceCard, addEndBubble },
|
|
568
|
+
page: { clearNotice, setSessionHash: (id) => setSessionHash(id), setTurnRunning, setLiveStatus, replaceCard, addEndBubble },
|
|
567
569
|
later: {
|
|
568
570
|
handlers: () => streamHandlers, composer: () => composer, focusPrompt: (opts) => focusPrompt(opts),
|
|
569
571
|
sessionActions: () => sessionActions, ownerClaim: () => ownerClaim,
|
|
@@ -776,90 +778,28 @@ window.addEventListener("resize", () => rename.reposition());
|
|
|
776
778
|
|
|
777
779
|
const { confirmDelete, leaveGoneSession, continueSelected, archiveOne, setArchived } = sessionActions;
|
|
778
780
|
|
|
779
|
-
//
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
leaveAllView(sessionHash(store.selected));
|
|
796
|
-
}
|
|
797
|
-
}
|
|
798
|
-
// Leave all sessions for a place of our own (a picked session, a new session):
|
|
799
|
-
// replace its history entry, since history.back() would come back later
|
|
800
|
-
// with the session the view was opened from.
|
|
801
|
-
function leaveAllView(hash) {
|
|
802
|
-
history.replaceState(null, "", location.pathname + location.search + hash);
|
|
803
|
-
allViewPushed = false;
|
|
804
|
-
applyView();
|
|
805
|
-
}
|
|
806
|
-
// The open session in the URL, so a reload or a copied link opens it again.
|
|
807
|
-
// Switching sessions replaces the entry; only all sessions pushes one.
|
|
808
|
-
function setSessionHash(id) {
|
|
809
|
-
if (allViewOpen()) return;
|
|
810
|
-
const hash = sessionHash(id);
|
|
811
|
-
if (location.hash === hash || (!hash && !location.hash)) return;
|
|
812
|
-
history.replaceState(null, "", location.pathname + location.search + hash);
|
|
813
|
-
}
|
|
814
|
-
// A #/s/<id> typed or pasted into the address bar, or reached by back.
|
|
815
|
-
// A claim link (claim_link.js; #/s/<id>?t=…&q=…, or the participant's
|
|
816
|
-
// #s=<id>&t=… opened in this browser) opens its session and, once drawn,
|
|
817
|
-
// shows the claim. The start page's own hash ("#/", or none) while one is
|
|
818
|
-
// open is the start page: the same clear the + button does, so the page and
|
|
819
|
-
// the composer stop addressing the session the URL has left behind.
|
|
820
|
-
function selectFromHash() {
|
|
821
|
-
const claim = claimFromHash(location.hash);
|
|
822
|
-
if (claim) ownerClaim.pending(claim);
|
|
823
|
-
// A participant's page has one session, whatever the hash names.
|
|
824
|
-
const intent = participant ? { kind: "session", id: participant.sessionId } : hashIntent(location.hash, { selected: store.selected, claim });
|
|
825
|
-
if (intent.kind === "session" && intent.id !== store.selected) select(intent.id);
|
|
826
|
-
else if (claim) ownerClaim.showPending();
|
|
827
|
-
else if (intent.kind === "start") clearSelection();
|
|
828
|
-
}
|
|
781
|
+
// A page, #/p/NAME, in place of the session area (page_view.js): the pages capability's.
|
|
782
|
+
const pageView = viewer.can("pages") ? createPageView({
|
|
783
|
+
root: $("#pageView"), api, toast: (text) => showToast(text), copyText, back: () => closePage(), gone: () => leavePage(),
|
|
784
|
+
backLabel: () => pageBackLabel(), phone: () => !!window.matchMedia?.("(max-width: 600px)").matches,
|
|
785
|
+
}) : null;
|
|
786
|
+
// The views by hash: All sessions, a page and the session's own (views.js).
|
|
787
|
+
const {
|
|
788
|
+
allViewOpen, openAllView, closeAllView, leaveAllView, setSessionHash, selectFromHash, applyView,
|
|
789
|
+
pageOpen, openPage, closePage, leavePage, pageBackLabel,
|
|
790
|
+
} = createViews({
|
|
791
|
+
participant, store, lists, topStripEl, pictures, eventsLive: () => !!eventsControl, refresh, updateSessionTitle,
|
|
792
|
+
select, clearSelection, ownerClaim: () => ownerClaim, pages: pageView, allViewOpened: () => pagesGroup?.load(),
|
|
793
|
+
});
|
|
794
|
+
// All sessions' Pages group (pages_group.js), and a #/p/ link opening its page in place (page_links.js).
|
|
795
|
+
const pagesGroup = pageView && createPagesGroup({ root: $("#pagesGroup"), filterEl: $("#filter"), api, open: (name) => openPage(name) });
|
|
796
|
+
if (pageView) installPageLinks([...turnRoots(), $("#pageView")], { open: (name) => openPage(name) });
|
|
829
797
|
// The page's claim links (owner_claim.js): one opened here, once drawn, and
|
|
830
798
|
// annotate's Copy link.
|
|
831
799
|
const ownerClaim = createOwnerClaim({
|
|
832
800
|
historyEl, store, claimTarget: () => participantsControl?.claimTarget() ?? null,
|
|
833
801
|
toast: (...args) => showToast(...args), copyText, allViewOpen, home: document.body.dataset.home || "",
|
|
834
802
|
});
|
|
835
|
-
function applyView() {
|
|
836
|
-
const open = allViewOpen();
|
|
837
|
-
if (!open) {
|
|
838
|
-
allViewPushed = false;
|
|
839
|
-
// A running batch ends on its own and clears the picks then.
|
|
840
|
-
if (lists.selecting.on && !lists.selecting.running) lists.leaveSelect();
|
|
841
|
-
topStripEl.scrollLeft = 0; // a phone's strip scrolls sideways to the tile
|
|
842
|
-
}
|
|
843
|
-
document.body.classList.toggle("all-view", open);
|
|
844
|
-
// The sessions pill is the view's button there: pressed while it is open.
|
|
845
|
-
$("#stripStatus").setAttribute("aria-pressed", String(open));
|
|
846
|
-
updateSessionTitle();
|
|
847
|
-
// Its chip was in the list just hidden (the strip, or all sessions).
|
|
848
|
-
lists.chainPop.close();
|
|
849
|
-
if (open) {
|
|
850
|
-
lists.familyPop.close(); pictures.close(); // the strip and #center (the picture viewer's parent) are hidden there
|
|
851
|
-
// The list is live; only its order can lag (upserts keep cards in
|
|
852
|
-
// place), so the all view opens in the server's order.
|
|
853
|
-
// A new list: the lists' redraw draws the all view (lists.render).
|
|
854
|
-
store.update({ sessions: sortedByUpdated(store.sessions) });
|
|
855
|
-
if (!eventsControl) refresh();
|
|
856
|
-
$("#filter").select();
|
|
857
|
-
}
|
|
858
|
-
}
|
|
859
|
-
window.addEventListener("hashchange", () => {
|
|
860
|
-
applyView();
|
|
861
|
-
selectFromHash();
|
|
862
|
-
});
|
|
863
803
|
|
|
864
804
|
// The composer's placeholder, hint, buttons and delivery row (composer_mode.js).
|
|
865
805
|
const composerMode = createComposerMode({
|
|
@@ -1354,7 +1294,7 @@ async function handleCancel() {
|
|
|
1354
1294
|
// The typed draft stays in the composer: paste in a session, then + new session
|
|
1355
1295
|
// starts from it (with the model picker). clearSelection leaves #prompt alone.
|
|
1356
1296
|
viewer.control($("#newBtn"), "sessions")?.addEventListener("click", () => {
|
|
1357
|
-
if (allViewOpen()) leaveAllView("");
|
|
1297
|
+
if (allViewOpen() || pageOpen()) leaveAllView("");
|
|
1358
1298
|
clearSelection();
|
|
1359
1299
|
startPage.loadModels({ asked: true });
|
|
1360
1300
|
});
|
|
@@ -25,6 +25,7 @@
|
|
|
25
25
|
<link rel="stylesheet" href="/assets/objectives.css">
|
|
26
26
|
<link rel="stylesheet" href="/assets/block_renderers.css">
|
|
27
27
|
<link rel="stylesheet" href="/assets/ws_preview.css">
|
|
28
|
+
<link rel="stylesheet" href="/assets/pages.css">
|
|
28
29
|
<style>
|
|
29
30
|
/* Icon masks shared by the phone info bar and the all view's cards (the stroke only shapes the mask; the icon takes currentColor); the image icon is composer.css's. */
|
|
30
31
|
:root{--icon-archive:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='none' stroke='black' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'%3E%3Crect x='2' y='2.75' width='12' height='3.5' rx='1'/%3E%3Cpath d='M3.25 6.25v6a1 1 0 0 0 1 1h7.5a1 1 0 0 0 1-1v-6M6.5 9h3'/%3E%3C/svg%3E");--icon-unarchive:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='none' stroke='black' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'%3E%3Crect x='2' y='2.75' width='12' height='3.5' rx='1'/%3E%3Cpath d='M3.25 6.25v6a1 1 0 0 0 1 1h7.5a1 1 0 0 0 1-1v-6M8 11.5V8.25M6.5 9.75 8 8.25l1.5 1.5'/%3E%3C/svg%3E")}
|
|
@@ -2313,7 +2314,9 @@ body.participant-view .bubble.user:not(.by-participant)>.origin-label{color:var(
|
|
|
2313
2314
|
</div>
|
|
2314
2315
|
</div>
|
|
2315
2316
|
</section>
|
|
2317
|
+
<section id="pageView" aria-label="Page"></section>
|
|
2316
2318
|
<section id="allView" aria-label="All sessions">
|
|
2319
|
+
<div id="pagesGroup" hidden></div>
|
|
2317
2320
|
<div id="allList"></div>
|
|
2318
2321
|
<div id="allPath" hidden>Stored in <code></code></div>
|
|
2319
2322
|
</section>
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
// A page's blocks as lit templates (docs/pages.md): a text block as the
|
|
2
|
+
// server's sanitised html (Markdown on) or as plain text with its line
|
|
3
|
+
// breaks, a walk in a widget host drawn by drawWalk (inline_widgets.js'
|
|
4
|
+
// shadow root and sheet), a table by +table+ (page_table.js), and a block of
|
|
5
|
+
// a type this page doesn't know (a newer chi's) as one muted line, never a
|
|
6
|
+
// blank or a throw. What a script wrote reaches the page as text or
|
|
7
|
+
// attributes only; the one markup is the server's sanitised html. A fenced
|
|
8
|
+
// block inside a text block stays source: no block watcher runs here.
|
|
9
|
+
import { html, nothing } from "./vendor/lit-html.js";
|
|
10
|
+
import { unsafeHTML } from "./vendor/directives/unsafe-html.js";
|
|
11
|
+
import { HOST, loadWidgetSheet } from "./inline_widgets.js";
|
|
12
|
+
import { drawWalk } from "./widget_walk.js";
|
|
13
|
+
|
|
14
|
+
// The class a walk's host carries, so drawWalks finds the hosts to fill.
|
|
15
|
+
export const WALK_HOST = "pg-walk";
|
|
16
|
+
|
|
17
|
+
function textBlock(block) {
|
|
18
|
+
if (typeof block.html === "string") return html`<div class="pg-text markdown">${unsafeHTML(block.html)}</div>`;
|
|
19
|
+
return html`<div class="pg-text pg-plain">${String(block.text ?? "")}</div>`;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// +table+: (block, index) => template (page_table.js), or null to show a
|
|
23
|
+
// table as an unknown block. +index+: the block's place on the page.
|
|
24
|
+
export function blockTemplate(block, { table = null } = {}, index = 0) {
|
|
25
|
+
const type = block && typeof block === "object" ? block.type : null;
|
|
26
|
+
if (type === "text") return textBlock(block);
|
|
27
|
+
if (type === "walk") return html`<div class="${HOST} ${WALK_HOST}" .pageWalk=${block.data}></div>`;
|
|
28
|
+
if (type === "table" && table) return table(block, index);
|
|
29
|
+
return html`<div class="pg-unknown">A ${String(type || "block")} block this chi web doesn't draw.</div>`;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function blocksTemplate(blocks, opts = {}) {
|
|
33
|
+
if (!Array.isArray(blocks) || !blocks.length) return nothing;
|
|
34
|
+
return blocks.map((block, index) => blockTemplate(block, opts, index));
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// Fills each walk host under +root+ whose data changed since its last draw
|
|
38
|
+
// (a redraw of the same page keeps the walk where the reader left it).
|
|
39
|
+
export async function drawWalks(root, { doc = document, win = window, sheet = () => loadWidgetSheet(win) } = {}) {
|
|
40
|
+
const hosts = [...root.querySelectorAll(`.${WALK_HOST}`)].filter((host) => host.pageWalk && host.drawnWalk !== host.pageWalk);
|
|
41
|
+
if (!hosts.length) return;
|
|
42
|
+
const css = await sheet();
|
|
43
|
+
for (const host of hosts) {
|
|
44
|
+
const data = host.pageWalk;
|
|
45
|
+
if (host.drawnWalk === data) continue;
|
|
46
|
+
host.drawnWalk = data;
|
|
47
|
+
const shadow = host.shadowRoot || host.attachShadow({ mode: "open" });
|
|
48
|
+
if (css) shadow.adoptedStyleSheets = [css];
|
|
49
|
+
try {
|
|
50
|
+
shadow.replaceChildren(drawWalk(data, doc));
|
|
51
|
+
} catch (e) {
|
|
52
|
+
const line = doc.createElement("div");
|
|
53
|
+
line.className = "pg-unknown";
|
|
54
|
+
line.textContent = `This walk can't be drawn: ${e?.message || e}`;
|
|
55
|
+
shadow.replaceChildren(line);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// A #/p/NAME link (in chi's answer, or on a page) opens the page in place
|
|
2
|
+
// (docs/pages.md): the sanitiser gives an answer's links target=_blank, so
|
|
3
|
+
// without this a page link would open a new tab (and leave the iPhone's Home
|
|
4
|
+
// Screen app for Safari). One delegated click handler per root, for anchors
|
|
5
|
+
// whose href starts with #/p/: a plain left click (button 0, no modifier
|
|
6
|
+
// key, not a ref link) opens the view and stops the new tab; a modified or
|
|
7
|
+
// middle click keeps the browser's own way. Other in-page links are left as
|
|
8
|
+
// they are. Installed only with the pages capability (app.js).
|
|
9
|
+
import { pageNameFromHash } from "./page_route.js";
|
|
10
|
+
|
|
11
|
+
// The page a click on +event+ asks for, or null when it isn't one this
|
|
12
|
+
// handler takes.
|
|
13
|
+
export function pageLinkTarget(event) {
|
|
14
|
+
if (event.defaultPrevented || event.button !== 0) return null;
|
|
15
|
+
if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return null;
|
|
16
|
+
const link = event.target?.closest?.("a[href]");
|
|
17
|
+
if (!link || link.hasAttribute("data-ref-kind")) return null;
|
|
18
|
+
const href = link.getAttribute("href") || "";
|
|
19
|
+
return href.startsWith("#/p/") ? pageNameFromHash(href) : null;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// +roots()+: the elements to listen on (the turn roots, the page view).
|
|
23
|
+
// +open(name)+: views.js openPage.
|
|
24
|
+
export function installPageLinks(roots, { open }) {
|
|
25
|
+
for (const root of roots) {
|
|
26
|
+
root?.addEventListener("click", (event) => {
|
|
27
|
+
const name = pageLinkTarget(event);
|
|
28
|
+
if (!name) return;
|
|
29
|
+
event.preventDefault();
|
|
30
|
+
open(name);
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
// What a page's header and state lines say, from the page's JSON
|
|
2
|
+
// (GET /api/pages/NAME): pure, so the words are testable without a DOM.
|
|
3
|
+
// page_view.js draws them. "Changed" is the server's (Pages::Stored#changed?,
|
|
4
|
+
// docs/internals/pages.md): the result on screen came from an older script.
|
|
5
|
+
import { relativeTime } from "./format.js";
|
|
6
|
+
|
|
7
|
+
const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
|
|
8
|
+
|
|
9
|
+
// A run's length: "0.8 s", "12 s", "< 0.1 s" (not "0.0 s"); "" without one.
|
|
10
|
+
export function durationText(ms) {
|
|
11
|
+
if (typeof ms !== "number" || !Number.isFinite(ms) || ms < 0) return "";
|
|
12
|
+
if (ms < 50) return "< 0.1 s";
|
|
13
|
+
return ms < 10_000 ? `${(ms / 1000).toFixed(1)} s` : `${Math.round(ms / 1000)} s`;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
// The header's meta: "ran 2 min ago · 0.8 s", "never ran"; null for a
|
|
17
|
+
// failed run (its line says when the kept result is from).
|
|
18
|
+
export function metaText(page, now = Date.now()) {
|
|
19
|
+
if (page.state === "failed") return null;
|
|
20
|
+
if (!page.ran_at) return "never ran";
|
|
21
|
+
const took = durationText(page.duration_ms);
|
|
22
|
+
return took ? `ran ${relativeTime(page.ran_at, now)} · ${took}` : `ran ${relativeTime(page.ran_at, now)}`;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// "21 Nov, 14:02", in the viewer's own time zone; "" for no time.
|
|
26
|
+
export function resultDate(iso) {
|
|
27
|
+
const t = iso ? Date.parse(iso) : NaN;
|
|
28
|
+
if (Number.isNaN(t)) return "";
|
|
29
|
+
const d = new Date(t);
|
|
30
|
+
const pad = (n) => String(n).padStart(2, "0");
|
|
31
|
+
return `${d.getDate()} ${MONTHS[d.getMonth()]}, ${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// The failed-run line in three parts, the message drawn as code between
|
|
35
|
+
// them: {lead: "The script failed at line 9: ", message, tail: " Showing the
|
|
36
|
+
// result from 21 Nov, 14:02."}; the tail is "" with no earlier result.
|
|
37
|
+
// null when the last run didn't fail.
|
|
38
|
+
export function failureParts(page) {
|
|
39
|
+
const error = page.state === "failed" ? page.error : null;
|
|
40
|
+
if (!error) return null;
|
|
41
|
+
const lead = Number.isInteger(error.line) ? `The script failed at line ${error.line}: ` : "The script failed: ";
|
|
42
|
+
const tail = page.ran_at ? ` Showing the result from ${resultDate(page.ran_at)}.` : "";
|
|
43
|
+
return { lead, message: String(error.message ?? ""), tail };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// The changed line (Scene 4), or null: shown when the result came from an
|
|
47
|
+
// older script, unless the last run failed on the script as it is now
|
|
48
|
+
// (then the failure line says enough).
|
|
49
|
+
export function changedText(page, now = Date.now()) {
|
|
50
|
+
if (!page.changed || !page.ran_at) return null;
|
|
51
|
+
if (page.state === "failed" && !page.changed_after_failure) return null;
|
|
52
|
+
const when = page.script_changed_at ? ` ${relativeTime(page.script_changed_at, now)}` : "";
|
|
53
|
+
return `The script changed${when}. This is the result of the earlier version; Refresh runs the new one.`;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// What Copy the error copies: "line 9: message", then the script's last
|
|
57
|
+
// words when the run's answer carried them.
|
|
58
|
+
export function errorCopy(page, stderr = "") {
|
|
59
|
+
const error = page.error;
|
|
60
|
+
if (!error) return "";
|
|
61
|
+
const head = Number.isInteger(error.line) ? `line ${error.line}: ${error.message}` : String(error.message);
|
|
62
|
+
return stderr ? `${head}\n\n${stderr.trimEnd()}` : head;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// Whether the blocks on screen are a kept result under a failure (dimmed).
|
|
66
|
+
export function keptAfterFailure(page) {
|
|
67
|
+
return page.state === "failed" && !!page.ran_at;
|
|
68
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// A page's place in the URL: #/p/NAME (docs/pages.md). Pure, so the hash
|
|
2
|
+
// rules are testable where app.js is not. hashIntent (hash_intent.js) is
|
|
3
|
+
// not changed: views.js reads a page hash before the session intent, and
|
|
4
|
+
// a page hash is "keep" to it.
|
|
5
|
+
|
|
6
|
+
const PAGE_HASH = /^#\/p\/([^/?#]+)$/;
|
|
7
|
+
|
|
8
|
+
export function pageHash(name) {
|
|
9
|
+
return `#/p/${name}`;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
// The NAME in +hash+ as it is written (never decoded: a name that isn't one
|
|
13
|
+
// opens the view's "no such page"), or null when it isn't a page hash.
|
|
14
|
+
export function pageNameFromHash(hash = "") {
|
|
15
|
+
const m = PAGE_HASH.exec(hash || "");
|
|
16
|
+
return m ? m[1] : null;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// The page +hash+ opens for this viewer, or null: never on a participant's
|
|
20
|
+
// page and never without the pages capability (the null-control rule).
|
|
21
|
+
export function openPageName(hash, { participant = null, canPages = false } = {}) {
|
|
22
|
+
if (participant || !canPages) return null;
|
|
23
|
+
return pageNameFromHash(hash);
|
|
24
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
// A page's table block as a lit template (docs/pages.md; page_table_model.js
|
|
2
|
+
// has its rules). Desktop: a real <table> in a box that scrolls sideways
|
|
3
|
+
// when it must, a column header sorts by that column (aria-sort), numbers
|
|
4
|
+
// right-aligned in tabular figures, the total row at the bottom whatever
|
|
5
|
+
// the sort, "N more rows were dropped" under it. Phone (decision D2 A): each
|
|
6
|
+
// row shows its first column and the key columns, and a tap opens the rest
|
|
7
|
+
// as label and value lines; rows keep the script's order there (no sort on
|
|
8
|
+
// a phone); the total is the last row. The view (page_view.js) keeps the
|
|
9
|
+
// sort and the opened rows; a cell reaches the page as text only.
|
|
10
|
+
import { html, nothing } from "./vendor/lit-html.js";
|
|
11
|
+
import { BLANK, cellText, numericColumn, phoneColumns, sortRows } from "./page_table_model.js";
|
|
12
|
+
|
|
13
|
+
const ARIA = { asc: "ascending", desc: "descending" };
|
|
14
|
+
const ARROW = { asc: " ↑", desc: " ↓" };
|
|
15
|
+
|
|
16
|
+
function cell(row, index, block) {
|
|
17
|
+
const text = cellText(row?.[index], block.columns[index]?.format);
|
|
18
|
+
return text === BLANK ? html`<span class="pg-blank">${BLANK}</span>` : text;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function droppedLine(block) {
|
|
22
|
+
const n = Number(block.dropped) || 0;
|
|
23
|
+
if (n <= 0) return nothing;
|
|
24
|
+
return html`<div class="pg-note">${n === 1 ? "1 more row was dropped" : `${n} more rows were dropped`}</div>`;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function desktop(block, { sort, onSort }) {
|
|
28
|
+
const columns = block.columns || [];
|
|
29
|
+
const numeric = columns.map((_c, i) => numericColumn(block, i));
|
|
30
|
+
const rows = sortRows(block.rows || [], sort ? sort.index : null, sort?.dir);
|
|
31
|
+
const cls = (i) => (numeric[i] && i > 0 ? "pg-num" : "");
|
|
32
|
+
const line = (row, className = "") => html`<tr class=${className}>${columns.map((_c, i) => html`<td class=${cls(i)}>${cell(row, i, block)}</td>`)}</tr>`;
|
|
33
|
+
return html`<div class="pg-table">
|
|
34
|
+
<div class="pg-scroll"><table>
|
|
35
|
+
<thead><tr>${columns.map((column, i) => {
|
|
36
|
+
const on = sort && sort.index === i ? sort.dir : null;
|
|
37
|
+
return html`<th class=${cls(i)} aria-sort=${on ? ARIA[on] : nothing}><button type="button" class="pg-sort"
|
|
38
|
+
@click=${() => onSort(i, numeric[i])}>${String(column.label ?? column.key ?? "")}${on ? ARROW[on] : ""}</button></th>`;
|
|
39
|
+
})}</tr></thead>
|
|
40
|
+
<tbody>${rows.map((row) => line(row))}</tbody>
|
|
41
|
+
${Array.isArray(block.total) ? html`<tfoot>${line(block.total, "pg-total")}</tfoot>` : nothing}
|
|
42
|
+
</table></div>
|
|
43
|
+
${droppedLine(block)}
|
|
44
|
+
</div>`;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function phone(block, { opened, onToggle }) {
|
|
48
|
+
const columns = block.columns || [];
|
|
49
|
+
const { keys, rest } = phoneColumns(block);
|
|
50
|
+
const label = (i) => String(columns[i]?.label ?? columns[i]?.key ?? "");
|
|
51
|
+
const shown = (row) => html`<span class="pg-k">${cell(row, 0, block)}</span>${keys.map((i) => html`<span class="pg-kv"><span class="pg-lab">${label(i)}</span>${cell(row, i, block)}</span>`)}`;
|
|
52
|
+
const style = `--pg-keys:${keys.length}`;
|
|
53
|
+
return html`<div class="pg-table">
|
|
54
|
+
<div class="pg-rows" role="list">
|
|
55
|
+
${(block.rows || []).map((row, r) => {
|
|
56
|
+
const open = opened.has(r);
|
|
57
|
+
if (!rest.length) return html`<div class="pg-row" role="listitem"><div class="pg-row-main" style=${style}>${shown(row)}</div></div>`;
|
|
58
|
+
return html`<div class="pg-row ${open ? "open" : ""}" role="listitem">
|
|
59
|
+
<button type="button" class="pg-row-main" style=${style} aria-expanded=${open ? "true" : "false"}
|
|
60
|
+
@click=${() => onToggle(r)}>${shown(row)}</button>
|
|
61
|
+
${open ? html`<div class="pg-cells">${rest.map((i) => html`<span><em>${label(i)}</em>${cell(row, i, block)}</span>`)}</div>` : nothing}
|
|
62
|
+
</div>`;
|
|
63
|
+
})}
|
|
64
|
+
${Array.isArray(block.total) ? html`<div class="pg-row pg-total" role="listitem"><div class="pg-row-main" style=${style}>${shown(block.total)}</div></div>` : nothing}
|
|
65
|
+
</div>
|
|
66
|
+
${droppedLine(block)}
|
|
67
|
+
</div>`;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// +phone+: the page's phone width; +sort+ {index, dir} or null and
|
|
71
|
+
// +onSort(index, numeric)+; +opened+ a Set of opened rows and +onToggle(row)+.
|
|
72
|
+
export function tableTemplate(block, { phone: narrow = false, sort = null, onSort = () => {}, opened = new Set(), onToggle = () => {} } = {}) {
|
|
73
|
+
return narrow ? phone(block, { opened, onToggle }) : desktop(block, { sort, onSort });
|
|
74
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
// A page's table as data (docs/pages.md): a cell's shown text, the sort and
|
|
2
|
+
// the phone's key columns. Pure: page_table.js draws them. The cells stay
|
|
3
|
+
// raw in the stored page (a number is a number), so the sort compares
|
|
4
|
+
// numbers as numbers; the words follow `chi page run`'s summary
|
|
5
|
+
// (PageCommand.cell): money $0.0000, count 1.2k / 3.4M, nil —.
|
|
6
|
+
|
|
7
|
+
export const BLANK = "—";
|
|
8
|
+
|
|
9
|
+
// 1.2k / 3.4M; under 1000 as it is (PageCommand.count).
|
|
10
|
+
export function countText(value) {
|
|
11
|
+
if (Math.abs(value) < 1000) return String(value);
|
|
12
|
+
const [n, unit] = Math.abs(value) < 1_000_000 ? [value / 1000, "k"] : [value / 1_000_000, "M"];
|
|
13
|
+
return `${n.toFixed(1).replace(/\.0$/, "")}${unit}`;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
// A cell as the page shows it.
|
|
17
|
+
export function cellText(value, format) {
|
|
18
|
+
if (value === null || value === undefined) return BLANK;
|
|
19
|
+
if (typeof value !== "number") return String(value);
|
|
20
|
+
if (format === "money") return `$${value.toFixed(4)}`;
|
|
21
|
+
if (format === "count") return countText(value);
|
|
22
|
+
return String(value);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// Whether column +index+ holds numbers (a format, or every cell that isn't
|
|
26
|
+
// blank a number): right-aligned, sorted high first.
|
|
27
|
+
export function numericColumn(block, index) {
|
|
28
|
+
const column = block.columns[index] || {};
|
|
29
|
+
if (column.format) return true;
|
|
30
|
+
const cells = (block.rows || []).map((row) => row[index]).filter((v) => v !== null && v !== undefined);
|
|
31
|
+
return cells.length > 0 && cells.every((v) => typeof v === "number");
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// The rows sorted by column +index+, +dir+ "asc" or "desc": numbers before
|
|
35
|
+
// text (numbers as numbers, text by locale), blanks last either way, rows
|
|
36
|
+
// that compare equal in their order (stable). The total is no row: it stays
|
|
37
|
+
// at the bottom. A null +index+ keeps the script's order.
|
|
38
|
+
export function sortRows(rows, index, dir = "asc") {
|
|
39
|
+
if (index === null || index === undefined) return rows.slice();
|
|
40
|
+
const sign = dir === "desc" ? -1 : 1;
|
|
41
|
+
const rank = (v) => {
|
|
42
|
+
if (v === null || v === undefined || v === "") return 2;
|
|
43
|
+
return typeof v === "number" ? 0 : 1;
|
|
44
|
+
};
|
|
45
|
+
return rows.map((row, at) => ({ row, at })).sort((a, b) => {
|
|
46
|
+
const x = a.row[index];
|
|
47
|
+
const y = b.row[index];
|
|
48
|
+
const rx = rank(x);
|
|
49
|
+
const ry = rank(y);
|
|
50
|
+
if (rx !== ry) return rx - ry;
|
|
51
|
+
let order = 0;
|
|
52
|
+
if (rx === 0) order = x - y;
|
|
53
|
+
else if (rx === 1) order = String(x).localeCompare(String(y));
|
|
54
|
+
return order === 0 ? a.at - b.at : sign * order;
|
|
55
|
+
}).map(({ row }) => row);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// The next sort after a click on column +index+: a new column starts high
|
|
59
|
+
// first for numbers and A to Z for text; the same column flips.
|
|
60
|
+
export function nextSort(sort, index, numeric) {
|
|
61
|
+
if (sort && sort.index === index) return { index, dir: sort.dir === "desc" ? "asc" : "desc" };
|
|
62
|
+
return { index, dir: numeric ? "desc" : "asc" };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// The columns a phone's row shows besides the first: those the script (or
|
|
66
|
+
// the builder's default) marked key_column; the rest open on a tap.
|
|
67
|
+
// @return {keys: [index], rest: [index]}
|
|
68
|
+
export function phoneColumns(block) {
|
|
69
|
+
const keys = [];
|
|
70
|
+
const rest = [];
|
|
71
|
+
(block.columns || []).forEach((column, i) => {
|
|
72
|
+
if (i === 0) return;
|
|
73
|
+
(column.key_column ? keys : rest).push(i);
|
|
74
|
+
});
|
|
75
|
+
return { keys, rest };
|
|
76
|
+
}
|