@bigmistqke/workpad 0.0.0-stage → 0.18.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +781 -2
- package/bin/workpad.ts +1526 -0
- package/dist/_virtual/_@oxc-project_runtime@0.156.0/helpers/esm/taggedTemplateLiteral.js +5 -0
- package/dist/bin/workpad.js +1202 -0
- package/dist/client/runtime.js +1194 -0
- package/dist/define.js +27 -0
- package/dist/plugins/alert/README.md +18 -0
- package/dist/plugins/alert/index.js +40 -0
- package/dist/plugins/alert/public/style.css +40 -0
- package/dist/plugins/ansi/README.md +36 -0
- package/dist/plugins/ansi/index.js +63 -0
- package/dist/plugins/ansi/public/style.css +28 -0
- package/dist/plugins/badge/README.md +32 -0
- package/dist/plugins/badge/index.js +28 -0
- package/dist/plugins/badge/public/style.css +30 -0
- package/dist/plugins/chat/README.md +81 -0
- package/dist/plugins/chat/index.js +96 -0
- package/dist/plugins/chat/public/client.js +3 -0
- package/dist/plugins/chat/public/style.css +143 -0
- package/dist/plugins/claude/README.md +116 -0
- package/dist/plugins/claude/channel.js +130 -0
- package/dist/plugins/claude/doctor.js +316 -0
- package/dist/plugins/claude/index.js +199 -0
- package/dist/plugins/claude/session.js +68 -0
- package/dist/plugins/code/README.md +54 -0
- package/dist/plugins/code/diff.js +75 -0
- package/dist/plugins/code/index.js +105 -0
- package/dist/plugins/code/public/client.js +1 -0
- package/dist/plugins/code/public/style.css +99 -0
- package/dist/plugins/comments/README.md +30 -0
- package/dist/plugins/comments/index.js +39 -0
- package/dist/plugins/comments/public/client.js +24 -0
- package/dist/plugins/comments/public/style.css +224 -0
- package/dist/plugins/details/README.md +24 -0
- package/dist/plugins/details/index.js +28 -0
- package/dist/plugins/details/public/style.css +7 -0
- package/dist/plugins/draft/README.md +14 -0
- package/dist/plugins/draft/index.js +27 -0
- package/dist/plugins/draft/public/style.css +21 -0
- package/dist/plugins/forge/README.md +22 -0
- package/dist/plugins/forge/index.js +83 -0
- package/dist/plugins/form/README.md +126 -0
- package/dist/plugins/form/index.js +179 -0
- package/dist/plugins/form/public/style.css +172 -0
- package/dist/plugins/grid/README.md +45 -0
- package/dist/plugins/grid/index.js +35 -0
- package/dist/plugins/grid/public/style.css +98 -0
- package/dist/plugins/iframe/README.md +18 -0
- package/dist/plugins/iframe/index.js +49 -0
- package/dist/plugins/iframe/public/style.css +28 -0
- package/dist/plugins/index.js +44 -0
- package/dist/plugins/lightbox/README.md +24 -0
- package/dist/plugins/lightbox/index.js +20 -0
- package/dist/plugins/lightbox/public/client.js +4 -0
- package/dist/plugins/lightbox/public/style.css +66 -0
- package/dist/plugins/mermaid/README.md +21 -0
- package/dist/plugins/mermaid/index.js +42 -0
- package/dist/plugins/mermaid/public/style.css +21 -0
- package/dist/plugins/opencode/README.md +48 -0
- package/dist/plugins/opencode/channel.js +92 -0
- package/dist/plugins/opencode/index.js +64 -0
- package/dist/plugins/opencode/shim.js +150 -0
- package/dist/plugins/quiet/README.md +26 -0
- package/dist/plugins/quiet/index.js +23 -0
- package/dist/plugins/tabs/README.md +44 -0
- package/dist/plugins/tabs/index.js +75 -0
- package/dist/plugins/tabs/public/client.js +1 -0
- package/dist/plugins/tabs/public/style.css +98 -0
- package/dist/plugins/terminal/README.md +63 -0
- package/dist/plugins/terminal/host.js +338 -0
- package/dist/plugins/terminal/index.js +170 -0
- package/dist/plugins/terminal/modes.js +32 -0
- package/dist/plugins/terminal/public/client.js +41 -0
- package/dist/plugins/terminal/public/style.css +511 -0
- package/dist/plugins/terminal/server.js +256 -0
- package/dist/plugins/terminal/sizes.js +58 -0
- package/dist/plugins/timeline/README.md +48 -0
- package/dist/plugins/timeline/index.js +83 -0
- package/dist/plugins/timeline/public/style.css +138 -0
- package/dist/plugins/toc/README.md +40 -0
- package/dist/plugins/toc/index.js +29 -0
- package/dist/plugins/toc/public/client.js +1 -0
- package/dist/plugins/toc/public/style.css +117 -0
- package/dist/plugins/window/README.md +51 -0
- package/dist/plugins/window/index.js +91 -0
- package/dist/solid/index.js +41 -0
- package/dist/src/agents.js +81 -0
- package/dist/src/anchors.js +52 -0
- package/dist/src/api.js +282 -0
- package/dist/src/archive.js +49 -0
- package/dist/src/auth.js +67 -0
- package/dist/src/build.js +159 -0
- package/dist/src/client/page/base.css +1762 -0
- package/dist/src/client/page/main.js +2121 -0
- package/dist/src/config.js +76 -0
- package/dist/src/document.js +93 -0
- package/dist/src/entries.js +264 -0
- package/dist/src/events.js +322 -0
- package/dist/src/files.js +47 -0
- package/dist/src/formstate.js +65 -0
- package/dist/src/help.js +213 -0
- package/dist/src/html.js +34 -0
- package/dist/src/hub.js +348 -0
- package/dist/src/icons.js +6 -0
- package/dist/src/listen.js +132 -0
- package/dist/src/listeners.js +64 -0
- package/dist/src/load.js +81 -0
- package/dist/src/loader.js +179 -0
- package/dist/src/migrate.js +314 -0
- package/dist/src/package.js +52 -0
- package/dist/src/pages/blocks.js +67 -0
- package/dist/src/pages/board.js +59 -0
- package/dist/src/pages/index.js +27 -0
- package/dist/src/pages/markdown.js +863 -0
- package/dist/src/pages/render.js +761 -0
- package/dist/src/pages/window.js +29 -0
- package/dist/src/plugins.js +283 -0
- package/dist/src/public.js +24 -0
- package/dist/src/rename.js +130 -0
- package/dist/src/running.js +146 -0
- package/dist/src/serve.js +188 -0
- package/dist/src/server.js +1105 -0
- package/dist/src/site.js +179 -0
- package/dist/src/state.js +155 -0
- package/dist/src/status.js +323 -0
- package/dist/src/thread.js +68 -0
- package/dist/src/watchdog.js +38 -0
- package/dist/src/ws.js +128 -0
- package/package.json +154 -4
- package/plugins/README.md +304 -0
- package/plugins/alert/README.md +18 -0
- package/plugins/alert/index.ts +50 -0
- package/plugins/alert/public/style.css +40 -0
- package/plugins/ansi/README.md +36 -0
- package/plugins/ansi/index.ts +95 -0
- package/plugins/ansi/public/style.css +28 -0
- package/plugins/badge/README.md +32 -0
- package/plugins/badge/index.ts +36 -0
- package/plugins/badge/public/style.css +30 -0
- package/plugins/chat/README.md +81 -0
- package/plugins/chat/autosize.ts +139 -0
- package/plugins/chat/client.tsx +187 -0
- package/plugins/chat/index.ts +146 -0
- package/plugins/chat/public/style.css +143 -0
- package/plugins/claude/README.md +116 -0
- package/plugins/claude/channel.ts +136 -0
- package/plugins/claude/doctor.ts +274 -0
- package/plugins/claude/index.ts +248 -0
- package/plugins/claude/session.ts +70 -0
- package/plugins/code/README.md +54 -0
- package/plugins/code/client.ts +73 -0
- package/plugins/code/diff.ts +96 -0
- package/plugins/code/index.ts +136 -0
- package/plugins/code/public/style.css +99 -0
- package/plugins/comments/README.md +30 -0
- package/plugins/comments/client.ts +723 -0
- package/plugins/comments/index.ts +48 -0
- package/plugins/comments/public/style.css +224 -0
- package/plugins/details/README.md +24 -0
- package/plugins/details/index.ts +30 -0
- package/plugins/details/public/style.css +7 -0
- package/plugins/draft/README.md +14 -0
- package/plugins/draft/index.ts +23 -0
- package/plugins/draft/public/style.css +21 -0
- package/plugins/forge/README.md +22 -0
- package/plugins/forge/index.ts +84 -0
- package/plugins/form/README.md +126 -0
- package/plugins/form/index.ts +199 -0
- package/plugins/form/public/style.css +172 -0
- package/plugins/grid/README.md +45 -0
- package/plugins/grid/index.ts +41 -0
- package/plugins/grid/public/style.css +98 -0
- package/plugins/iframe/README.md +18 -0
- package/plugins/iframe/index.ts +53 -0
- package/plugins/iframe/public/style.css +28 -0
- package/plugins/index.ts +49 -0
- package/plugins/lightbox/README.md +24 -0
- package/plugins/lightbox/client.ts +109 -0
- package/plugins/lightbox/index.ts +25 -0
- package/plugins/lightbox/public/style.css +66 -0
- package/plugins/mermaid/README.md +21 -0
- package/plugins/mermaid/index.ts +46 -0
- package/plugins/mermaid/public/style.css +21 -0
- package/plugins/opencode/README.md +48 -0
- package/plugins/opencode/channel.ts +112 -0
- package/plugins/opencode/index.ts +91 -0
- package/plugins/opencode/shim.ts +166 -0
- package/plugins/quiet/README.md +26 -0
- package/plugins/quiet/index.ts +28 -0
- package/plugins/tabs/README.md +44 -0
- package/plugins/tabs/client.ts +96 -0
- package/plugins/tabs/index.ts +103 -0
- package/plugins/tabs/public/style.css +98 -0
- package/plugins/terminal/README.md +63 -0
- package/plugins/terminal/client.ts +391 -0
- package/plugins/terminal/host.ts +434 -0
- package/plugins/terminal/index.ts +199 -0
- package/plugins/terminal/modes.ts +30 -0
- package/plugins/terminal/public/style.css +225 -0
- package/plugins/terminal/server.ts +266 -0
- package/plugins/terminal/sizes.ts +72 -0
- package/plugins/timeline/README.md +48 -0
- package/plugins/timeline/index.ts +82 -0
- package/plugins/timeline/public/style.css +138 -0
- package/plugins/toc/README.md +40 -0
- package/plugins/toc/client.ts +236 -0
- package/plugins/toc/index.ts +55 -0
- package/plugins/toc/public/style.css +117 -0
- package/plugins/window/README.md +51 -0
- package/plugins/window/index.ts +92 -0
- package/skills/workpad/SKILL.md +592 -0
- package/solid/index.tsx +80 -0
- package/src/agents.ts +134 -0
- package/src/anchors.ts +85 -0
- package/src/api.ts +444 -0
- package/src/archive.ts +75 -0
- package/src/auth.ts +99 -0
- package/src/build.ts +213 -0
- package/src/client/base.ts +19 -0
- package/src/client/forms.ts +420 -0
- package/src/client/markdown.ts +147 -0
- package/src/client/page/base.css +1762 -0
- package/src/client/page/board.ts +166 -0
- package/src/client/page/elsewhere.ts +153 -0
- package/src/client/page/fresh.ts +343 -0
- package/src/client/page/heading-link.ts +32 -0
- package/src/client/page/live.ts +134 -0
- package/src/client/page/main.ts +398 -0
- package/src/client/page/orphans.ts +64 -0
- package/src/client/page/place.ts +260 -0
- package/src/client/page/sort.ts +49 -0
- package/src/client/page/sticky.ts +58 -0
- package/src/client/page/theme.ts +36 -0
- package/src/client/page/view.ts +9 -0
- package/src/client/page/waiting.ts +278 -0
- package/src/client/page/window.ts +40 -0
- package/src/client/reactive.ts +19 -0
- package/src/client/read.ts +111 -0
- package/src/client/runtime.ts +499 -0
- package/src/client/scroll.ts +90 -0
- package/src/client/toast.ts +99 -0
- package/src/config.ts +111 -0
- package/src/define.ts +997 -0
- package/src/document.ts +191 -0
- package/src/entries.ts +352 -0
- package/src/events.ts +463 -0
- package/src/files.ts +74 -0
- package/src/formstate.ts +72 -0
- package/src/help.ts +240 -0
- package/src/html.ts +44 -0
- package/src/hub.ts +435 -0
- package/src/icons.ts +18 -0
- package/src/listen.ts +171 -0
- package/src/listeners.ts +89 -0
- package/src/load.ts +113 -0
- package/src/loader.ts +227 -0
- package/src/migrate.ts +352 -0
- package/src/package.ts +62 -0
- package/src/pages/blocks.ts +106 -0
- package/src/pages/board.ts +89 -0
- package/src/pages/index.ts +79 -0
- package/src/pages/markdown.ts +976 -0
- package/src/pages/render.ts +845 -0
- package/src/pages/window.ts +69 -0
- package/src/plugins.ts +319 -0
- package/src/public.ts +39 -0
- package/src/rename.ts +147 -0
- package/src/running.ts +171 -0
- package/src/serve.ts +221 -0
- package/src/server.ts +1385 -0
- package/src/site.ts +170 -0
- package/src/state.ts +327 -0
- package/src/status.ts +466 -0
- package/src/thread.ts +98 -0
- package/src/watchdog.ts +53 -0
- package/src/ws.ts +155 -0
|
@@ -0,0 +1,420 @@
|
|
|
1
|
+
// Named forms: workpad's one interaction primitive, in the browser. A `<form name>` without an
|
|
2
|
+
// `action` (one with an action submits normally) is a question; submitting it appends an event
|
|
3
|
+
// whose type is the form's name, the button its `action` and the fields its `data`. This holds on
|
|
4
|
+
// every page.
|
|
5
|
+
//
|
|
6
|
+
// What the core does with such a form, without drawing anything:
|
|
7
|
+
// - sends a submit as an event, shown at once (optimistic), and says how that went: `data-wp-state`
|
|
8
|
+
// is sending (shown, not yet confirmed), sent or failed (taken back);
|
|
9
|
+
// - keeps what the reader typed until it is sent (localStorage, per page and form), across
|
|
10
|
+
// re-renders and reloads;
|
|
11
|
+
// - puts the last answer back into the form, and its button in `data-wp-sent`;
|
|
12
|
+
// - marks where the form stands, from the log and the listeners, with one of these attributes:
|
|
13
|
+
// data-wp-open no answer yet, or the agent asks again (a listen asks for it by name after
|
|
14
|
+
// its answer was handled)
|
|
15
|
+
// data-wp-pending answered, but no agent has received the answer yet
|
|
16
|
+
// data-wp-received an agent received the answer, and hasn't handled it yet
|
|
17
|
+
// data-wp-handled the agent handled its latest answer; data-wp-outcome quotes it in one line
|
|
18
|
+
// data-wp-held an agent put it on hold (`workpad hold`): the attribute is the reason,
|
|
19
|
+
// said on the form too (`.wp-form-held`), as it doesn't wait for the reader now
|
|
20
|
+
// data-wp-settled answered elsewhere (`workpad settle`)
|
|
21
|
+
// and, for a few seconds after a send went through, `data-wp-just-sent`, to confirm it
|
|
22
|
+
//
|
|
23
|
+
// How that looks is the page's: it styles the attributes, and can follow `api.forms.on`. A form
|
|
24
|
+
// marked `data-wp-self` (or inside an element that is) keeps its own fields: no drafts and no last
|
|
25
|
+
// answer are written into it, for a block's component that shows them itself.
|
|
26
|
+
import type { Api, FormState, FormStatus } from '../define'
|
|
27
|
+
import { STATES, settleNested, isQuestionName, questionState } from '../status.ts'
|
|
28
|
+
import { reactive } from './reactive'
|
|
29
|
+
import { storageKey } from './base.ts'
|
|
30
|
+
|
|
31
|
+
type Data = Record<string, unknown>
|
|
32
|
+
|
|
33
|
+
let root: HTMLElement
|
|
34
|
+
let api: Api
|
|
35
|
+
let page = ''
|
|
36
|
+
|
|
37
|
+
/** The forms the core looks after: named (a name without a colon: see isQuestionName), without an action. */
|
|
38
|
+
const managed = (form: HTMLFormElement) =>
|
|
39
|
+
isQuestionName(form.getAttribute('name') ?? '') && !form.hasAttribute('action')
|
|
40
|
+
const forms = () => [...root.querySelectorAll('form')].filter(managed)
|
|
41
|
+
const keepsOwnFields = (form: HTMLFormElement) => !!form.closest('[data-wp-self]')
|
|
42
|
+
|
|
43
|
+
// ---- reading and writing a form ----------------------------------------------------------------
|
|
44
|
+
|
|
45
|
+
// An option for an answer not on the list (`:radio[Other]{name=… other}`): a radio or checkbox
|
|
46
|
+
// marked `data-wp-other`, with a text box (`data-wp-other-text`, no name of its own) in its label.
|
|
47
|
+
// It sends what was typed; typing picks it; an answer that is none of the other options goes back
|
|
48
|
+
// into its box.
|
|
49
|
+
const otherText = (option: HTMLInputElement) =>
|
|
50
|
+
option.closest('label')?.querySelector<HTMLInputElement>('[data-wp-other-text]') ?? null
|
|
51
|
+
const isOther = (el: Element): boolean => el instanceof HTMLInputElement && el.hasAttribute('data-wp-other')
|
|
52
|
+
|
|
53
|
+
function readForm(form: HTMLFormElement): Data {
|
|
54
|
+
const data: Data = {}
|
|
55
|
+
const elements = [...form.elements] as HTMLInputElement[]
|
|
56
|
+
const boxes: Record<string, number> = {}
|
|
57
|
+
for (const el of elements) if (el.name && el.type === 'checkbox') boxes[el.name] = (boxes[el.name] ?? 0) + 1
|
|
58
|
+
for (const el of elements) {
|
|
59
|
+
if (!el.name || el.type === 'submit' || el.type === 'button' || el.type === 'reset' || el.type === 'file') continue
|
|
60
|
+
// an other-option sends what was typed in its box: read, not written into the option (for a
|
|
61
|
+
// radio or checkbox that would change its value attribute, and so the page's HTML)
|
|
62
|
+
const value = isOther(el) ? (otherText(el)?.value.trim() ?? '') : el.value
|
|
63
|
+
if (el.type === 'checkbox') {
|
|
64
|
+
if (boxes[el.name] > 1) {
|
|
65
|
+
const list = (data[el.name] ??= []) as string[]
|
|
66
|
+
if (el.checked) list.push(value)
|
|
67
|
+
} else data[el.name] = el.checked
|
|
68
|
+
} else if (el.type === 'radio') {
|
|
69
|
+
if (el.checked) data[el.name] = value
|
|
70
|
+
else data[el.name] ??= null
|
|
71
|
+
} else if ((el as unknown) instanceof HTMLSelectElement && (el as unknown as HTMLSelectElement).multiple) {
|
|
72
|
+
data[el.name] = [...(el as unknown as HTMLSelectElement).selectedOptions].map(o => o.value)
|
|
73
|
+
} else data[el.name] = el.value
|
|
74
|
+
}
|
|
75
|
+
return data
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function writeForm(form: HTMLFormElement, data: Data) {
|
|
79
|
+
const elements = [...form.elements] as HTMLInputElement[]
|
|
80
|
+
// what the listed options of a name send, so an answer that is none of them is the other one's
|
|
81
|
+
const listed = (name: string) =>
|
|
82
|
+
elements
|
|
83
|
+
.filter(e => e.name === name && !isOther(e) && (e.type === 'radio' || e.type === 'checkbox'))
|
|
84
|
+
.map(e => e.value)
|
|
85
|
+
for (const el of elements) {
|
|
86
|
+
if (!el.name || !(el.name in data) || ['submit', 'button', 'hidden', 'file'].includes(el.type)) continue
|
|
87
|
+
const v = data[el.name]
|
|
88
|
+
if (isOther(el)) {
|
|
89
|
+
const own = listed(el.name)
|
|
90
|
+
const rest = (Array.isArray(v) ? v : [v]).filter(
|
|
91
|
+
x => typeof x === 'string' && x !== '' && !own.includes(x),
|
|
92
|
+
) as string[]
|
|
93
|
+
el.checked = rest.length > 0
|
|
94
|
+
const text = otherText(el)
|
|
95
|
+
if (text && text !== document.activeElement) text.value = rest.join(', ')
|
|
96
|
+
continue
|
|
97
|
+
}
|
|
98
|
+
if (el.type === 'checkbox') el.checked = Array.isArray(v) ? v.includes(el.value) : !!v
|
|
99
|
+
else if (el.type === 'radio') el.checked = v === el.value
|
|
100
|
+
else el.value = v == null ? '' : String(v)
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Typing in an other-option's box picks it (and an empty box, for a checkbox, unpicks it). */
|
|
105
|
+
function onOtherInput(e: Event) {
|
|
106
|
+
const text = e.target as HTMLInputElement
|
|
107
|
+
if (!text.matches?.('[data-wp-other-text]')) return
|
|
108
|
+
const option = text.closest('label')?.querySelector<HTMLInputElement>('[data-wp-other]')
|
|
109
|
+
if (!option) return
|
|
110
|
+
if (text.value.trim()) option.checked = true
|
|
111
|
+
else if (option.type === 'checkbox') option.checked = false
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// ---- drafts ------------------------------------------------------------------------------------
|
|
115
|
+
|
|
116
|
+
const draftKey = (form: HTMLFormElement) => storageKey(`wp-draft:${page}:${form.getAttribute('name')}`)
|
|
117
|
+
|
|
118
|
+
function saveDraft(e: Event) {
|
|
119
|
+
const form = (e.target as Element | null)?.closest?.('form')
|
|
120
|
+
if (!form || !managed(form) || !root.contains(form) || keepsOwnFields(form)) return
|
|
121
|
+
try {
|
|
122
|
+
localStorage.setItem(draftKey(form), JSON.stringify(readForm(form)))
|
|
123
|
+
} catch {
|
|
124
|
+
/* storage unavailable */
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** Unsent drafts back into their forms; a form being typed in is left alone. */
|
|
129
|
+
function restoreDrafts() {
|
|
130
|
+
for (const form of forms()) {
|
|
131
|
+
if (keepsOwnFields(form) || form.contains(document.activeElement)) continue
|
|
132
|
+
let draft: Data | null = null
|
|
133
|
+
try {
|
|
134
|
+
draft = JSON.parse(localStorage.getItem(draftKey(form)) ?? 'null')
|
|
135
|
+
} catch {
|
|
136
|
+
/* storage unavailable */
|
|
137
|
+
}
|
|
138
|
+
if (draft) writeForm(form, draft)
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const dropDraft = (form: HTMLFormElement) => {
|
|
143
|
+
try {
|
|
144
|
+
localStorage.removeItem(draftKey(form))
|
|
145
|
+
} catch {
|
|
146
|
+
/* storage unavailable */
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** Each form's last answer: its button in data-wp-sent, and with `prefill` its fields. */
|
|
151
|
+
function restoreLast(prefill: boolean) {
|
|
152
|
+
for (const form of forms()) {
|
|
153
|
+
const last = api.last(form.getAttribute('name')!)
|
|
154
|
+
if (!last) continue
|
|
155
|
+
form.dataset.wpSent = last.action ?? ''
|
|
156
|
+
if (prefill && !keepsOwnFields(form)) writeForm(form, last.data)
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** What each form is sending now, as sent: the same answer again is not sent twice. */
|
|
161
|
+
const inFlight = new WeakMap<HTMLFormElement, string>()
|
|
162
|
+
|
|
163
|
+
// The button that sent it says how that goes, in its own text and colour (`data-wp-send` on it):
|
|
164
|
+
// "Sending…" (grey) while on its way, "✓ Sent" (green) a moment once the server has it, then its own
|
|
165
|
+
// label again; "Try again" (red) when no try got through, until it is pressed. It keeps its width
|
|
166
|
+
// meanwhile.
|
|
167
|
+
type Send = 'sending' | 'sent' | 'failed'
|
|
168
|
+
/** A button's own label, while it says how a send goes. */
|
|
169
|
+
const labelOf = (button: HTMLButtonElement) => {
|
|
170
|
+
const el = document.createElement('div')
|
|
171
|
+
el.innerHTML = labels.get(button)!.html
|
|
172
|
+
return el.textContent?.trim() ?? ''
|
|
173
|
+
}
|
|
174
|
+
const SEND_TEXT: Record<Send, string> = { sending: 'Sending…', sent: '✓ Sent', failed: 'Try again' }
|
|
175
|
+
const labels = new WeakMap<HTMLButtonElement, { html: string; timer?: ReturnType<typeof setTimeout> }>()
|
|
176
|
+
|
|
177
|
+
function sendState(button: HTMLButtonElement | null, state: Send | null) {
|
|
178
|
+
if (!button) return
|
|
179
|
+
let saved = labels.get(button)
|
|
180
|
+
clearTimeout(saved?.timer)
|
|
181
|
+
if (!state) {
|
|
182
|
+
if (!saved) return
|
|
183
|
+
button.innerHTML = saved.html
|
|
184
|
+
button.style.minWidth = ''
|
|
185
|
+
delete button.dataset.wpSend
|
|
186
|
+
labels.delete(button)
|
|
187
|
+
return
|
|
188
|
+
}
|
|
189
|
+
if (!saved) {
|
|
190
|
+
saved = { html: button.innerHTML }
|
|
191
|
+
labels.set(button, saved)
|
|
192
|
+
button.style.minWidth = `${button.getBoundingClientRect().width}px`
|
|
193
|
+
}
|
|
194
|
+
button.dataset.wpSend = state
|
|
195
|
+
button.textContent = SEND_TEXT[state]
|
|
196
|
+
// confirmed: said for a moment, then the button is itself again
|
|
197
|
+
if (state === 'sent') saved.timer = setTimeout(() => sendState(button, null), 2000)
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// Optimistic: the answer is the form's at once (api.append puts it in the events, so the form is
|
|
201
|
+
// marked pending), with `data-wp-state="sending"` saying it is still on its way, and its button
|
|
202
|
+
// saying so (sendState); `sent` once the server has it, with the short `data-wp-just-sent` to
|
|
203
|
+
// confirm it. Should it not get through, the answer leaves the form again: `failed`, the button
|
|
204
|
+
// the form had before, the draft kept.
|
|
205
|
+
async function onSubmit(e: SubmitEvent) {
|
|
206
|
+
const form = e.target as HTMLFormElement
|
|
207
|
+
if (!managed(form) || !root.contains(form)) return
|
|
208
|
+
e.preventDefault()
|
|
209
|
+
const button = e.submitter as HTMLButtonElement | null
|
|
210
|
+
// its label as it is, not as it says how a send goes
|
|
211
|
+
const label = button ? (labels.get(button) ? labelOf(button) : button.textContent?.trim()) : null
|
|
212
|
+
const action = button ? button.value || label || null : null
|
|
213
|
+
const data = readForm(form)
|
|
214
|
+
const sent = JSON.stringify([action, data])
|
|
215
|
+
if (inFlight.get(form) === sent) return
|
|
216
|
+
inFlight.set(form, sent)
|
|
217
|
+
const before = form.dataset.wpSent
|
|
218
|
+
form.dataset.wpState = 'sending'
|
|
219
|
+
form.dataset.wpSent = action ?? ''
|
|
220
|
+
form.removeAttribute('data-wp-just-sent')
|
|
221
|
+
sendState(button, 'sending')
|
|
222
|
+
showStatus(form)
|
|
223
|
+
try {
|
|
224
|
+
await api.append(form.getAttribute('name')!, data, action)
|
|
225
|
+
if (inFlight.get(form) !== sent) return // a newer answer took its place
|
|
226
|
+
dropDraft(form)
|
|
227
|
+
form.dataset.wpState = 'sent'
|
|
228
|
+
sendState(button, 'sent')
|
|
229
|
+
// for the page to confirm the send: set for a few seconds after it
|
|
230
|
+
form.toggleAttribute('data-wp-just-sent', true)
|
|
231
|
+
clearTimeout(justSent.get(form))
|
|
232
|
+
justSent.set(
|
|
233
|
+
form,
|
|
234
|
+
setTimeout(() => {
|
|
235
|
+
form.removeAttribute('data-wp-just-sent')
|
|
236
|
+
showStatus(form)
|
|
237
|
+
}, 3000),
|
|
238
|
+
)
|
|
239
|
+
showStatus(form)
|
|
240
|
+
} catch (err) {
|
|
241
|
+
if (inFlight.get(form) !== sent) return
|
|
242
|
+
form.dataset.wpState = 'failed'
|
|
243
|
+
sendState(button, 'failed')
|
|
244
|
+
if (before == null) delete form.dataset.wpSent
|
|
245
|
+
else form.dataset.wpSent = before
|
|
246
|
+
showStatus(form)
|
|
247
|
+
console.error(err)
|
|
248
|
+
} finally {
|
|
249
|
+
if (inFlight.get(form) === sent) inFlight.delete(form)
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
// ---- where each form stands --------------------------------------------------------------------
|
|
254
|
+
|
|
255
|
+
// What a sent answer came to, said beside the form's last send button, where the eye is when it is
|
|
256
|
+
// pressed (a line over the form was out of view below a long list of options): `.wp-form-status`,
|
|
257
|
+
// "waiting for an agent to receive it", or `data-kind="bad"` "couldn't send it". Never what the
|
|
258
|
+
// button says already (sendState): nothing while sending, no "sent".
|
|
259
|
+
const sendButtons = (form: HTMLFormElement) =>
|
|
260
|
+
[...form.querySelectorAll<HTMLButtonElement | HTMLInputElement>('button, input[type=submit]')].filter(
|
|
261
|
+
b => (b instanceof HTMLInputElement || (b.type !== 'button' && b.type !== 'reset')) && b.form === form,
|
|
262
|
+
)
|
|
263
|
+
|
|
264
|
+
function showStatus(form: HTMLFormElement) {
|
|
265
|
+
const text =
|
|
266
|
+
form.dataset.wpState === 'failed'
|
|
267
|
+
? (["couldn't send it", 'bad'] as const)
|
|
268
|
+
: form.dataset.wpState === 'sending'
|
|
269
|
+
? null
|
|
270
|
+
: form.hasAttribute('data-wp-pending')
|
|
271
|
+
? (['waiting for an agent to receive it', null] as const)
|
|
272
|
+
: form.hasAttribute('data-wp-received')
|
|
273
|
+
? (['the agent has it', null] as const)
|
|
274
|
+
: null
|
|
275
|
+
let el = form.querySelector<HTMLElement>('.wp-form-status')
|
|
276
|
+
const last = sendButtons(form).at(-1)
|
|
277
|
+
if (!text || !last) return void el?.remove()
|
|
278
|
+
if (!el) el = Object.assign(document.createElement('span'), { className: 'wp-form-status' })
|
|
279
|
+
el.setAttribute('role', 'status')
|
|
280
|
+
if (el.previousElementSibling !== last) last.after(el)
|
|
281
|
+
el.textContent = text[0]
|
|
282
|
+
if (text[1]) el.dataset.kind = text[1]
|
|
283
|
+
else delete el.dataset.kind
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
const ATTR: Record<FormState, string> = {
|
|
287
|
+
open: 'data-wp-open',
|
|
288
|
+
pending: 'data-wp-pending',
|
|
289
|
+
received: 'data-wp-received',
|
|
290
|
+
handled: 'data-wp-handled',
|
|
291
|
+
held: 'data-wp-held',
|
|
292
|
+
settled: 'data-wp-settled',
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/**
|
|
296
|
+
* A held form says why at its top, under its title: "⏸ on hold: waits for !2145". The line is the
|
|
297
|
+
* page's, put back after each update; it goes once the form is released.
|
|
298
|
+
*/
|
|
299
|
+
function showHold(form: HTMLFormElement, reason: string | null) {
|
|
300
|
+
let el = form.querySelector<HTMLElement>(':scope > .wp-form-held')
|
|
301
|
+
if (reason == null) return void el?.remove()
|
|
302
|
+
if (!el) {
|
|
303
|
+
el = Object.assign(document.createElement('p'), { className: 'wp-form-held' })
|
|
304
|
+
el.setAttribute('role', 'note')
|
|
305
|
+
const title = form.querySelector(':scope > .wp-form-title')
|
|
306
|
+
if (title) title.after(el)
|
|
307
|
+
else form.prepend(el)
|
|
308
|
+
}
|
|
309
|
+
el.textContent = reason ? `⏸ on hold: ${reason}` : '⏸ on hold'
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/** One line quoting an answer: what was chosen, then what was written. */
|
|
313
|
+
/**
|
|
314
|
+
* An answer, told apart: the button it was sent with (none for a plain Send), what was chosen
|
|
315
|
+
* (options, short values), and what was written.
|
|
316
|
+
*/
|
|
317
|
+
export function answerParts(
|
|
318
|
+
data: Data,
|
|
319
|
+
action: string | null,
|
|
320
|
+
): { action: string | null; chosen: string[]; written: string[] } {
|
|
321
|
+
const chosen: string[] = [],
|
|
322
|
+
written: string[] = []
|
|
323
|
+
// a key with a colon is no field's: it says where the answer came from (a chat's message), not what
|
|
324
|
+
for (const [k, v] of Object.entries(data)) {
|
|
325
|
+
if (k.includes(':') || v == null || v === '' || v === false) continue
|
|
326
|
+
if (Array.isArray(v)) {
|
|
327
|
+
if (v.length) chosen.push(v.join(', '))
|
|
328
|
+
} else if (v === true) continue
|
|
329
|
+
else if (String(v).length > 60 || String(v).includes('\n')) written.push(String(v))
|
|
330
|
+
else chosen.push(String(v))
|
|
331
|
+
}
|
|
332
|
+
return { action: action && !['Send', 'Submit'].includes(action) ? action : null, chosen, written }
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/** One line quoting an answer: what was chosen, then what was written. */
|
|
336
|
+
function outcome(data: Data, action: string | null) {
|
|
337
|
+
const { action: button, chosen, written } = answerParts(data, action)
|
|
338
|
+
return [
|
|
339
|
+
[button, ...chosen].filter(Boolean).join(' · ') || 'sent',
|
|
340
|
+
...written.map(w => `“${w.length > 240 ? w.slice(0, 240) + '…' : w}”`),
|
|
341
|
+
].join('\n')
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
let current: FormStatus[] = []
|
|
345
|
+
const justSent = new WeakMap<HTMLFormElement, ReturnType<typeof setTimeout>>()
|
|
346
|
+
|
|
347
|
+
/** Mark every form from the log and the listeners, then tell whoever follows. */
|
|
348
|
+
function mark() {
|
|
349
|
+
const listening = api.listeners()
|
|
350
|
+
const found = forms().map(form => {
|
|
351
|
+
const name = form.getAttribute('name')!
|
|
352
|
+
return { form, name, ...questionState(name, api.events(), listening, api.marks) }
|
|
353
|
+
})
|
|
354
|
+
// a form in a message under a decided form asks nothing any more (settleNested, as the server says)
|
|
355
|
+
const holds = new Map(found.map(f => [f.form, f.hold]))
|
|
356
|
+
current = settleNested(found).map(({ form, name, state, last }) => {
|
|
357
|
+
for (const st of STATES) form.toggleAttribute(ATTR[st], st === state)
|
|
358
|
+
const hold = state === 'held' ? (holds.get(form) ?? null) : null
|
|
359
|
+
// held: the attribute says why
|
|
360
|
+
if (hold) form.setAttribute(ATTR.held, hold.reason)
|
|
361
|
+
showHold(form, hold ? hold.reason : null)
|
|
362
|
+
if (state === 'received' || state === 'handled') form.dataset.wpOutcome = outcome(last!.data, last!.action)
|
|
363
|
+
else delete form.dataset.wpOutcome
|
|
364
|
+
showStatus(form)
|
|
365
|
+
return { form, name, state, last, hold }
|
|
366
|
+
})
|
|
367
|
+
forms_.notify()
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/** After the page re-rendered: answers, drafts and marks back on its forms. */
|
|
371
|
+
function refresh() {
|
|
372
|
+
restoreLast(false)
|
|
373
|
+
restoreDrafts()
|
|
374
|
+
mark()
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/** Look after the page's named forms; called once the page has mounted. */
|
|
378
|
+
export function trackForms(el: HTMLElement, pageId: string, core: Api) {
|
|
379
|
+
root = el
|
|
380
|
+
page = pageId
|
|
381
|
+
api = core
|
|
382
|
+
// before the draft is saved: what was typed picks its option
|
|
383
|
+
document.addEventListener('input', onOtherInput)
|
|
384
|
+
document.addEventListener('input', saveDraft)
|
|
385
|
+
document.addEventListener('change', saveDraft)
|
|
386
|
+
// as it goes down, not up: a submit from a form inside another (one in an agent's message, in
|
|
387
|
+
// the chat under a form) bubbles no further than that form, so the document never hears it
|
|
388
|
+
document.addEventListener('submit', onSubmit, { capture: true })
|
|
389
|
+
api.onRendered(refresh)
|
|
390
|
+
api.listeners.on(mark)
|
|
391
|
+
api.events.on(() => {
|
|
392
|
+
restoreLast(false)
|
|
393
|
+
mark()
|
|
394
|
+
})
|
|
395
|
+
restoreLast(true)
|
|
396
|
+
restoreDrafts()
|
|
397
|
+
mark()
|
|
398
|
+
// a form drawn after the page (in an agent's chat message, Api.message): its answer, draft and
|
|
399
|
+
// marks too, once it is in
|
|
400
|
+
let known = new Set(forms())
|
|
401
|
+
new MutationObserver(() => {
|
|
402
|
+
const now = forms()
|
|
403
|
+
const fresh = now.filter(f => !known.has(f))
|
|
404
|
+
known = new Set(now)
|
|
405
|
+
if (!fresh.length) return
|
|
406
|
+
// only the new ones: a form being filled in elsewhere keeps what is in it
|
|
407
|
+
for (const form of fresh) {
|
|
408
|
+
const last = api.last(form.getAttribute('name')!)
|
|
409
|
+
if (!last) continue
|
|
410
|
+
form.dataset.wpSent = last.action ?? ''
|
|
411
|
+
if (!keepsOwnFields(form)) writeForm(form, last.data)
|
|
412
|
+
}
|
|
413
|
+
restoreDrafts()
|
|
414
|
+
mark()
|
|
415
|
+
}).observe(root, { childList: true, subtree: true })
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
/** For the api: every named form and where it stands, as it changes. */
|
|
419
|
+
const forms_ = reactive((): FormStatus[] => current)
|
|
420
|
+
export const formsApi = { forms: forms_ }
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
// Messages written in markdown (comments, chat messages), as HTML: rendered on the server like a
|
|
2
|
+
// page (code fences highlighted, `#12` linked), without raw HTML or directives (api.markdown). The
|
|
3
|
+
// texts asked for at once go in one request; each text is rendered once, then cached. A
|
|
4
|
+
// stylesheet a message needs (the code block's) is linked once it is first used.
|
|
5
|
+
import { url } from './base.ts'
|
|
6
|
+
|
|
7
|
+
const cache = new Map<string, Promise<string>>()
|
|
8
|
+
let queue: { text: string; resolve: (html: string) => void; reject: (err: unknown) => void }[] = []
|
|
9
|
+
|
|
10
|
+
async function flush() {
|
|
11
|
+
const batch = queue
|
|
12
|
+
queue = []
|
|
13
|
+
try {
|
|
14
|
+
const res = await fetch(url('/api/markdown'), {
|
|
15
|
+
method: 'POST',
|
|
16
|
+
headers: { 'content-type': 'application/json' },
|
|
17
|
+
body: JSON.stringify({ texts: batch.map(b => b.text) }),
|
|
18
|
+
})
|
|
19
|
+
if (!res.ok) throw new Error(await res.text())
|
|
20
|
+
const { html, styles } = (await res.json()) as { html: string[]; styles: string[] }
|
|
21
|
+
linkStyles(styles)
|
|
22
|
+
batch.forEach((b, i) => b.resolve(html[i] ?? ''))
|
|
23
|
+
} catch (err) {
|
|
24
|
+
for (const b of batch) {
|
|
25
|
+
cache.delete(b.text)
|
|
26
|
+
b.reject(err)
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function markdown(text: string): Promise<string> {
|
|
32
|
+
let got = cache.get(text)
|
|
33
|
+
if (!got) {
|
|
34
|
+
got = new Promise((resolve, reject) => {
|
|
35
|
+
if (!queue.length) queueMicrotask(flush)
|
|
36
|
+
queue.push({ text, resolve, reject })
|
|
37
|
+
})
|
|
38
|
+
cache.set(text, got)
|
|
39
|
+
}
|
|
40
|
+
return got
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// ---- the agent's chat messages, as small pages ------------------------------------------------------
|
|
44
|
+
// Rendered by the server by their id (Api.message): every block, as on the page. Cached by id and
|
|
45
|
+
// text, so an edited message renders again. Their islands go to the page module to mount
|
|
46
|
+
// (`wp-islands`), the same way the page's own do.
|
|
47
|
+
|
|
48
|
+
const messages = new Map<string, Promise<string>>()
|
|
49
|
+
let pending: { id: string; resolve: (html: string) => void; reject: (err: unknown) => void; key: string }[] = []
|
|
50
|
+
|
|
51
|
+
function linkStyles(styles: string[]) {
|
|
52
|
+
for (const href of styles) {
|
|
53
|
+
if (
|
|
54
|
+
![...document.querySelectorAll<HTMLLinkElement>('link[rel=stylesheet]')].some(
|
|
55
|
+
l => new URL(l.href).pathname === new URL(href, location.href).pathname,
|
|
56
|
+
)
|
|
57
|
+
)
|
|
58
|
+
document.head.insertAdjacentHTML('beforeend', `<link rel="stylesheet" href="${href.replace(/"/g, '"')}">`)
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
async function flushMessages() {
|
|
63
|
+
const batch = pending
|
|
64
|
+
pending = []
|
|
65
|
+
try {
|
|
66
|
+
const res = await fetch(url('/api/messages'), {
|
|
67
|
+
method: 'POST',
|
|
68
|
+
headers: { 'content-type': 'application/json' },
|
|
69
|
+
body: JSON.stringify({ ids: batch.map(b => b.id) }),
|
|
70
|
+
})
|
|
71
|
+
if (!res.ok) throw new Error(await res.text())
|
|
72
|
+
const { html, islands, styles } = (await res.json()) as {
|
|
73
|
+
html: string[]
|
|
74
|
+
islands: Record<string, unknown>
|
|
75
|
+
styles: string[]
|
|
76
|
+
}
|
|
77
|
+
linkStyles(styles)
|
|
78
|
+
document.dispatchEvent(new CustomEvent('wp-islands', { detail: islands }))
|
|
79
|
+
batch.forEach((b, i) => b.resolve(html[i] ?? ''))
|
|
80
|
+
} catch (err) {
|
|
81
|
+
for (const b of batch) {
|
|
82
|
+
messages.delete(b.key)
|
|
83
|
+
b.reject(err)
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** An agent's chat message as HTML, rendered by the server as a small page (Api.message). */
|
|
89
|
+
export function message(event: { id: string; data: Record<string, unknown> }): Promise<string> {
|
|
90
|
+
const key = `${event.id}\0${String(event.data.text ?? '')}`
|
|
91
|
+
let got = messages.get(key)
|
|
92
|
+
if (!got) {
|
|
93
|
+
got = new Promise((resolve, reject) => {
|
|
94
|
+
if (!pending.length) queueMicrotask(flushMessages)
|
|
95
|
+
pending.push({ id: event.id, resolve, reject, key })
|
|
96
|
+
})
|
|
97
|
+
messages.set(key, got)
|
|
98
|
+
}
|
|
99
|
+
return got
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// ---- markdown a plugin's client puts in what it draws ----------------------------------------------
|
|
103
|
+
// Rendered by the server with every block, as on the page (Api.blocks): a chat in a plugin's own
|
|
104
|
+
// thread, say. Cached by text. Their islands go to the page module to mount (`wp-islands`), as a
|
|
105
|
+
// message's do, once the HTML is in the page.
|
|
106
|
+
|
|
107
|
+
const rendered = new Map<string, Promise<string>>()
|
|
108
|
+
let asked: { text: string; resolve: (html: string) => void; reject: (err: unknown) => void }[] = []
|
|
109
|
+
|
|
110
|
+
async function flushBlocks(page: string) {
|
|
111
|
+
const batch = asked
|
|
112
|
+
asked = []
|
|
113
|
+
try {
|
|
114
|
+
const res = await fetch(url('/api/blocks'), {
|
|
115
|
+
method: 'POST',
|
|
116
|
+
headers: { 'content-type': 'application/json' },
|
|
117
|
+
body: JSON.stringify({ page, texts: batch.map(b => b.text) }),
|
|
118
|
+
})
|
|
119
|
+
if (!res.ok) throw new Error(await res.text())
|
|
120
|
+
const { html, islands, styles } = (await res.json()) as {
|
|
121
|
+
html: string[]
|
|
122
|
+
islands: Record<string, unknown>
|
|
123
|
+
styles: string[]
|
|
124
|
+
}
|
|
125
|
+
linkStyles(styles)
|
|
126
|
+
document.dispatchEvent(new CustomEvent('wp-islands', { detail: islands }))
|
|
127
|
+
batch.forEach((b, i) => b.resolve(html[i] ?? ''))
|
|
128
|
+
} catch (err) {
|
|
129
|
+
for (const b of batch) {
|
|
130
|
+
rendered.delete(b.text)
|
|
131
|
+
b.reject(err)
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** Markdown with every block, as on page `page`, as HTML (Api.blocks). */
|
|
137
|
+
export function blocks(page: string, text: string): Promise<string> {
|
|
138
|
+
let got = rendered.get(text)
|
|
139
|
+
if (!got) {
|
|
140
|
+
got = new Promise((resolve, reject) => {
|
|
141
|
+
if (!asked.length) queueMicrotask(() => flushBlocks(page))
|
|
142
|
+
asked.push({ text, resolve, reject })
|
|
143
|
+
})
|
|
144
|
+
rendered.set(text, got)
|
|
145
|
+
}
|
|
146
|
+
return got
|
|
147
|
+
}
|