@bigmistqke/whiteboard 0.0.0-stage → 0.2.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.
- package/LICENSE +21 -0
- package/README.md +628 -2
- package/bin/whiteboard.ts +488 -0
- package/dist/_virtual/_@oxc-project_runtime@0.156.0/helpers/esm/taggedTemplateLiteral.js +5 -0
- package/dist/bin/whiteboard.js +542 -0
- package/dist/client/runtime.js +544 -0
- package/dist/define.js +7 -0
- package/dist/plugins/callout/README.md +13 -0
- package/dist/plugins/callout/index.js +27 -0
- package/dist/plugins/callout/style.css +12 -0
- package/dist/plugins/chat/README.md +46 -0
- package/dist/plugins/chat/client.js +3 -0
- package/dist/plugins/chat/index.js +47 -0
- package/dist/plugins/chat/style.css +24 -0
- package/dist/plugins/claude-code/index.js +120 -0
- package/dist/plugins/code/README.md +42 -0
- package/dist/plugins/code/diff.js +65 -0
- package/dist/plugins/code/index.js +77 -0
- package/dist/plugins/code/style.css +29 -0
- package/dist/plugins/comments/client.js +10 -0
- package/dist/plugins/comments/index.js +54 -0
- package/dist/plugins/comments/style.css +40 -0
- package/dist/plugins/details/README.md +17 -0
- package/dist/plugins/details/index.js +17 -0
- package/dist/plugins/details/style.css +3 -0
- package/dist/plugins/forge/README.md +12 -0
- package/dist/plugins/forge/index.js +83 -0
- package/dist/plugins/form/README.md +111 -0
- package/dist/plugins/form/index.js +102 -0
- package/dist/plugins/form/style.css +41 -0
- package/dist/plugins/gallery/README.md +30 -0
- package/dist/plugins/gallery/client.js +1 -0
- package/dist/plugins/gallery/index.js +74 -0
- package/dist/plugins/gallery/style.css +27 -0
- package/dist/plugins/grid/README.md +33 -0
- package/dist/plugins/grid/index.js +33 -0
- package/dist/plugins/grid/style.css +25 -0
- package/dist/plugins/iframe/README.md +18 -0
- package/dist/plugins/iframe/client.js +1 -0
- package/dist/plugins/iframe/index.js +40 -0
- package/dist/plugins/iframe/style.css +29 -0
- package/dist/plugins/index.js +30 -0
- package/dist/plugins/mermaid/README.md +21 -0
- package/dist/plugins/mermaid/index.js +35 -0
- package/dist/plugins/mermaid/style.css +16 -0
- package/dist/plugins/quiet/README.md +26 -0
- package/dist/plugins/quiet/index.js +17 -0
- package/dist/plugins/terminal/client.js +41 -0
- package/dist/plugins/terminal/host.js +332 -0
- package/dist/plugins/terminal/index.js +171 -0
- package/dist/plugins/terminal/modes.js +32 -0
- package/dist/plugins/terminal/server.js +256 -0
- package/dist/plugins/terminal/sizes.js +57 -0
- package/dist/plugins/terminal/style.css +357 -0
- package/dist/solid/index.js +36 -0
- package/dist/src/auth.js +54 -0
- package/dist/src/client/page/base.css +295 -0
- package/dist/src/client/page/main.js +1228 -0
- package/dist/src/config.js +76 -0
- package/dist/src/events.js +183 -0
- package/dist/src/html.js +34 -0
- package/dist/src/icons.js +6 -0
- package/dist/src/load.js +77 -0
- package/dist/src/loader.js +126 -0
- package/dist/src/package.js +33 -0
- package/dist/src/pages/blocks.js +50 -0
- package/dist/src/pages/index.js +15 -0
- package/dist/src/pages/markdown.js +410 -0
- package/dist/src/pages/render.js +311 -0
- package/dist/src/plugins.js +238 -0
- package/dist/src/running.js +24 -0
- package/dist/src/serve.js +71 -0
- package/dist/src/server.js +725 -0
- package/dist/src/status.js +71 -0
- package/package.json +131 -4
- package/plugins/callout/README.md +13 -0
- package/plugins/callout/index.ts +25 -0
- package/plugins/callout/style.css +12 -0
- package/plugins/chat/README.md +46 -0
- package/plugins/chat/autosize.ts +101 -0
- package/plugins/chat/client.tsx +93 -0
- package/plugins/chat/index.ts +61 -0
- package/plugins/chat/style.css +24 -0
- package/plugins/claude-code/index.ts +136 -0
- package/plugins/code/README.md +42 -0
- package/plugins/code/diff.ts +64 -0
- package/plugins/code/index.ts +94 -0
- package/plugins/code/style.css +29 -0
- package/plugins/comments/client.ts +492 -0
- package/plugins/comments/index.ts +54 -0
- package/plugins/comments/style.css +40 -0
- package/plugins/details/README.md +17 -0
- package/plugins/details/index.ts +21 -0
- package/plugins/details/style.css +3 -0
- package/plugins/forge/README.md +12 -0
- package/plugins/forge/index.ts +71 -0
- package/plugins/form/README.md +111 -0
- package/plugins/form/index.ts +104 -0
- package/plugins/form/style.css +41 -0
- package/plugins/gallery/README.md +30 -0
- package/plugins/gallery/client.tsx +64 -0
- package/plugins/gallery/index.ts +67 -0
- package/plugins/gallery/style.css +27 -0
- package/plugins/grid/README.md +33 -0
- package/plugins/grid/index.ts +36 -0
- package/plugins/grid/style.css +25 -0
- package/plugins/iframe/README.md +18 -0
- package/plugins/iframe/client.ts +46 -0
- package/plugins/iframe/index.ts +54 -0
- package/plugins/iframe/style.css +29 -0
- package/plugins/index.ts +21 -0
- package/plugins/mermaid/README.md +21 -0
- package/plugins/mermaid/index.ts +40 -0
- package/plugins/mermaid/style.css +16 -0
- package/plugins/quiet/README.md +26 -0
- package/plugins/quiet/index.ts +27 -0
- package/plugins/terminal/client.ts +317 -0
- package/plugins/terminal/host.ts +326 -0
- package/plugins/terminal/index.ts +138 -0
- package/plugins/terminal/modes.ts +30 -0
- package/plugins/terminal/server.ts +215 -0
- package/plugins/terminal/sizes.ts +60 -0
- package/plugins/terminal/style.css +71 -0
- package/skills/whiteboard/SKILL.md +302 -0
- package/solid/index.tsx +59 -0
- package/src/auth.ts +66 -0
- package/src/client/forms.ts +185 -0
- package/src/client/markdown.ts +36 -0
- package/src/client/page/base.css +295 -0
- package/src/client/page/elsewhere.ts +70 -0
- package/src/client/page/fresh.ts +205 -0
- package/src/client/page/live.ts +30 -0
- package/src/client/page/main.ts +272 -0
- package/src/client/page/orphans.ts +46 -0
- package/src/client/page/sort.ts +38 -0
- package/src/client/page/theme.ts +32 -0
- package/src/client/page/view.ts +9 -0
- package/src/client/page/waiting.ts +182 -0
- package/src/client/read.ts +73 -0
- package/src/client/runtime.ts +183 -0
- package/src/client/toast.ts +25 -0
- package/src/config.ts +96 -0
- package/src/define.ts +612 -0
- package/src/events.ts +218 -0
- package/src/html.ts +40 -0
- package/src/icons.ts +8 -0
- package/src/load.ts +89 -0
- package/src/loader.ts +112 -0
- package/src/package.ts +39 -0
- package/src/pages/blocks.ts +70 -0
- package/src/pages/index.ts +42 -0
- package/src/pages/markdown.ts +364 -0
- package/src/pages/render.ts +233 -0
- package/src/plugins.ts +197 -0
- package/src/running.ts +22 -0
- package/src/serve.ts +52 -0
- package/src/server.ts +667 -0
- package/src/status.ts +113 -0
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
// The page's light and dark theme: the reader's choice (kept in localStorage), else the system's.
|
|
2
|
+
import type { Theme } from '../../define.ts'
|
|
3
|
+
|
|
4
|
+
export type ThemePreference = Theme | 'auto'
|
|
5
|
+
|
|
6
|
+
const media = matchMedia('(prefers-color-scheme: dark)')
|
|
7
|
+
const listeners = new Set<(theme: Theme) => void>()
|
|
8
|
+
const resolve = (): Theme => (document.documentElement.dataset.theme as Theme | undefined) ?? (media.matches ? 'dark' : 'light')
|
|
9
|
+
let theme = resolve()
|
|
10
|
+
|
|
11
|
+
function update() {
|
|
12
|
+
const next = resolve()
|
|
13
|
+
if (next === theme) return
|
|
14
|
+
theme = next
|
|
15
|
+
for (const fn of listeners) fn(theme)
|
|
16
|
+
}
|
|
17
|
+
media.addEventListener('change', update)
|
|
18
|
+
|
|
19
|
+
export const currentTheme = () => theme
|
|
20
|
+
export function onTheme(fn: (theme: Theme) => void) { listeners.add(fn); return () => listeners.delete(fn) }
|
|
21
|
+
|
|
22
|
+
export const themePreference = (): ThemePreference => (document.documentElement.dataset.theme as Theme | undefined) ?? 'auto'
|
|
23
|
+
|
|
24
|
+
export function setThemePreference(pref: ThemePreference) {
|
|
25
|
+
if (pref === 'auto') delete document.documentElement.dataset.theme
|
|
26
|
+
else document.documentElement.dataset.theme = pref
|
|
27
|
+
try {
|
|
28
|
+
if (pref === 'auto') localStorage.removeItem('wb-theme')
|
|
29
|
+
else localStorage.setItem('wb-theme', pref)
|
|
30
|
+
} catch { /* the choice still applies to this visit */ }
|
|
31
|
+
update()
|
|
32
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// The part of the window the page is seen in. The core may put something at the bottom of the
|
|
2
|
+
// window (the terminal drawer) and says how tall it is in `--wb-inset-bottom`; what is behind it is
|
|
3
|
+
// not in view, so measurements of what the reader sees stop above it.
|
|
4
|
+
|
|
5
|
+
/** The bottom of the visible part of the page, in window coordinates. */
|
|
6
|
+
export function viewBottom(): number {
|
|
7
|
+
const inset = parseFloat(getComputedStyle(document.documentElement).getPropertyValue('--wb-inset-bottom')) || 0
|
|
8
|
+
return Math.max(0, innerHeight - inset)
|
|
9
|
+
}
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
// How the page shows what waits for the reader: its open questions and the agent's messages they
|
|
2
|
+
// haven't read (status.ts). The core marks each named form with where it stands (open, pending,
|
|
3
|
+
// decided; see `api.onForms`); the page styles those marks (base.css), folds a decided form into
|
|
4
|
+
// one line quoting its answer, sums them up in a line above the page, puts a button in the page's
|
|
5
|
+
// corner that goes from one thing waiting for the reader to the next, and counts them in the tab
|
|
6
|
+
// title. Unread messages also get a toast that stays while there are any. A message is found on the
|
|
7
|
+
// page by its element (`data-wb-message`), or, when it isn't shown, by the element that holds it
|
|
8
|
+
// (`data-wb-holds`: a comment's badge), which is sent `wb-reveal` to show it. Arriving by a link that
|
|
9
|
+
// ends in `#wb-waiting` (the header's menu, the overview), the page goes to the first. An answer no
|
|
10
|
+
// agent is listening for says so once it is sent, in a toast: the form's own mark may be out of view.
|
|
11
|
+
import type { Api, FormState, FormStatus, Toast } from '../../define.ts'
|
|
12
|
+
import { viewBottom } from './view'
|
|
13
|
+
import { STATES } from '../../status.ts'
|
|
14
|
+
import { WAITING_HASH } from './elsewhere'
|
|
15
|
+
|
|
16
|
+
const ORDER = STATES
|
|
17
|
+
const LABEL: Record<FormState, (n: number) => string> = {
|
|
18
|
+
open: n => `${n} waiting for you`,
|
|
19
|
+
pending: n => `${n} waiting for the agent`,
|
|
20
|
+
decided: n => `${n} decided`,
|
|
21
|
+
}
|
|
22
|
+
const messagesLabel = (n: number) => `${n} unread message${n === 1 ? '' : 's'} from the agent`
|
|
23
|
+
|
|
24
|
+
let main: HTMLElement
|
|
25
|
+
let api: Api
|
|
26
|
+
let forms: FormStatus[] = []
|
|
27
|
+
|
|
28
|
+
const button = document.createElement('button')
|
|
29
|
+
button.type = 'button'
|
|
30
|
+
button.className = 'wb-waiting-next'
|
|
31
|
+
button.hidden = true
|
|
32
|
+
|
|
33
|
+
// above the page's content, not in it: #wb-main is compared block by block on every update
|
|
34
|
+
const summary = document.createElement('div')
|
|
35
|
+
summary.className = 'wb-summary'
|
|
36
|
+
summary.hidden = true
|
|
37
|
+
|
|
38
|
+
// forms the reader opened again to change their answer, by name, with the answer they opened:
|
|
39
|
+
// they stay open until a newer answer is decided
|
|
40
|
+
const reopened = new Map<string, string>()
|
|
41
|
+
|
|
42
|
+
const inState = (state: FormState) => forms.filter(f => f.state === state && f.form.isConnected).map(f => f.form)
|
|
43
|
+
|
|
44
|
+
/** Where an unread message is on the page: its own element, else the one holding it. */
|
|
45
|
+
function messageTarget(id: string): HTMLElement | null {
|
|
46
|
+
const own = document.querySelector<HTMLElement>(`[data-wb-message="${CSS.escape(id)}"]`)
|
|
47
|
+
if (own && own.getClientRects().length) return own
|
|
48
|
+
return [...document.querySelectorAll<HTMLElement>('[data-wb-holds]')].find(el => el.dataset.wbHolds!.split(' ').includes(id)) ?? null
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** What waits for the reader, top to bottom: open forms and unread messages. */
|
|
52
|
+
function targets(kind: 'all' | 'messages' = 'all'): HTMLElement[] {
|
|
53
|
+
const list = [...new Set([
|
|
54
|
+
...(kind === 'all' ? inState('open') : []),
|
|
55
|
+
...api.unread().map(e => messageTarget(e.id)).filter((el): el is HTMLElement => !!el),
|
|
56
|
+
])]
|
|
57
|
+
const top = (el: HTMLElement) => el.getBoundingClientRect().top
|
|
58
|
+
return list.sort((a, b) => top(a) - top(b))
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
let messagesToast: Toast | null = null
|
|
62
|
+
let toastTimer = 0
|
|
63
|
+
|
|
64
|
+
function show(list: FormStatus[] = forms) {
|
|
65
|
+
forms = list
|
|
66
|
+
for (const { form, name, state, last } of forms) {
|
|
67
|
+
if (last && reopened.has(name) && reopened.get(name) !== last.id && state === 'decided') reopened.delete(name)
|
|
68
|
+
form.toggleAttribute('data-wb-folded', state === 'decided' && !reopened.has(name))
|
|
69
|
+
}
|
|
70
|
+
const unread = api.unread().length
|
|
71
|
+
const parts: [string, string][] = ORDER.map(state => [state, inState(state).length] as const).filter(([, count]) => count).map(([state, count]) => [state, LABEL[state](count)])
|
|
72
|
+
if (unread) parts.splice(inState('open').length ? 1 : 0, 0, ['messages', messagesLabel(unread)])
|
|
73
|
+
summary.hidden = !parts.length
|
|
74
|
+
summary.replaceChildren(...parts.flatMap(([state, text], i) => {
|
|
75
|
+
const link = document.createElement('button')
|
|
76
|
+
link.type = 'button'
|
|
77
|
+
link.dataset.state = state
|
|
78
|
+
link.textContent = text
|
|
79
|
+
return i ? [document.createTextNode(' · '), link] : [link]
|
|
80
|
+
}))
|
|
81
|
+
const n = inState('open').length + unread
|
|
82
|
+
button.hidden = n === 0
|
|
83
|
+
button.textContent = `→ waiting for you (${n})`
|
|
84
|
+
api.badge('waiting', n ? `!${n}` : null, -1)
|
|
85
|
+
// the agent's messages, wherever the reader is scrolled: a toast while there are any. It comes a
|
|
86
|
+
// moment late: a message that arrives in view (an open thread) is read before it would show.
|
|
87
|
+
if (!unread) { messagesToast?.close(); messagesToast = null; clearTimeout(toastTimer) }
|
|
88
|
+
else if (messagesToast) messagesToast.update(messagesLabel(unread))
|
|
89
|
+
else {
|
|
90
|
+
clearTimeout(toastTimer)
|
|
91
|
+
toastTimer = window.setTimeout(() => {
|
|
92
|
+
const left = api.unread().length
|
|
93
|
+
if (left && !messagesToast) messagesToast = api.toast(messagesLabel(left), { ms: 0, onClick: () => jump('messages') })
|
|
94
|
+
}, 1000)
|
|
95
|
+
}
|
|
96
|
+
// arrived to answer: the first thing waiting, once the page knows (the log loads after the page)
|
|
97
|
+
if (arriving && n) {
|
|
98
|
+
arriving = false
|
|
99
|
+
history.replaceState(history.state, '', location.pathname + location.search)
|
|
100
|
+
requestAnimationFrame(() => { const first = targets()[0]; if (first) jumpTo(first) })
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
let arriving = location.hash === WAITING_HASH
|
|
105
|
+
// a page whose questions were answered meanwhile has none left to go to
|
|
106
|
+
setTimeout(() => { arriving = false }, 5000)
|
|
107
|
+
|
|
108
|
+
// What a jump went to last, and where the page was scrolled then: jumping again goes to the one
|
|
109
|
+
// after it, round to the first. Once the reader scrolled themselves, the next one is the first
|
|
110
|
+
// below where they are.
|
|
111
|
+
let current: HTMLElement | null = null
|
|
112
|
+
let scrolledTo = 0
|
|
113
|
+
|
|
114
|
+
function next(list: HTMLElement[]) {
|
|
115
|
+
const i = current ? list.indexOf(current) : -1
|
|
116
|
+
if (i >= 0 && Math.abs(scrollY - scrolledTo) < 40) return list[(i + 1) % list.length]
|
|
117
|
+
return list.find(f => f.getBoundingClientRect().top > viewBottom() / 2) ?? list[0]
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function jump(what: FormState | 'messages' | 'all') {
|
|
121
|
+
const list = what === 'all' ? targets() : what === 'messages' ? targets('messages') : inState(what)
|
|
122
|
+
const target = next(list)
|
|
123
|
+
if (target) jumpTo(target)
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function jumpTo(target: HTMLElement) {
|
|
127
|
+
current = target
|
|
128
|
+
// centred in the part of the window the page is seen in (above the terminal drawer), as far as
|
|
129
|
+
// the page allows
|
|
130
|
+
const r = target.getBoundingClientRect()
|
|
131
|
+
scrolledTo = Math.max(0, Math.min(scrollY + r.top + r.height / 2 - viewBottom() / 2, document.documentElement.scrollHeight - innerHeight))
|
|
132
|
+
scrollTo({ top: scrolledTo, behavior: 'smooth' })
|
|
133
|
+
if (target instanceof HTMLFormElement) {
|
|
134
|
+
if (target.hasAttribute('data-wb-open')) target.querySelector<HTMLElement>('input:not([type=hidden]), textarea, select, button')?.focus({ preventScroll: true })
|
|
135
|
+
} else target.dispatchEvent(new CustomEvent('wb-reveal', { bubbles: true }))
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export function trackWaiting(root: HTMLElement, core: Api) {
|
|
139
|
+
main = root
|
|
140
|
+
api = core
|
|
141
|
+
api.corner().prepend(button)
|
|
142
|
+
button.addEventListener('click', () => jump('all'))
|
|
143
|
+
main.before(summary)
|
|
144
|
+
summary.addEventListener('click', e => {
|
|
145
|
+
const state = (e.target as HTMLElement).closest<HTMLElement>('button[data-state]')?.dataset.state as FormState | 'messages' | undefined
|
|
146
|
+
if (state) jump(state)
|
|
147
|
+
})
|
|
148
|
+
// a folded form opens again on a click, to change the answer; not on one in its thread, which
|
|
149
|
+
// stays open under it
|
|
150
|
+
main.addEventListener('click', e => {
|
|
151
|
+
const target = e.target as HTMLElement
|
|
152
|
+
const form = target.closest<HTMLFormElement>('form[data-wb-folded]')
|
|
153
|
+
if (!form || target.closest('[data-block=chat-thread]')) return
|
|
154
|
+
e.preventDefault()
|
|
155
|
+
const name = form.getAttribute('name')!
|
|
156
|
+
const last = api.last(name)
|
|
157
|
+
if (last) reopened.set(name, last.id)
|
|
158
|
+
show(forms)
|
|
159
|
+
form.querySelector<HTMLElement>('input:not([type=hidden]), textarea, select')?.focus({ preventScroll: true })
|
|
160
|
+
})
|
|
161
|
+
api.onForms(show)
|
|
162
|
+
// a message read, or a new one
|
|
163
|
+
api.onEvents(() => show())
|
|
164
|
+
show(api.forms())
|
|
165
|
+
document.addEventListener('submit', e => {
|
|
166
|
+
const form = e.target as HTMLFormElement
|
|
167
|
+
const name = form.getAttribute('name')
|
|
168
|
+
if (!name || !main.contains(form) || !forms.some(f => f.form === form)) return
|
|
169
|
+
// who listens as it is sent: an agent that takes it ends its wait right after
|
|
170
|
+
const takes = (fallback: boolean) => api.listeners().some(l => !!l.fallback === fallback && (l.type === name || l.type === null))
|
|
171
|
+
if (takes(false)) return
|
|
172
|
+
const fallback = takes(true)
|
|
173
|
+
const sent = new MutationObserver(() => {
|
|
174
|
+
if (form.dataset.wbState === 'sending') return
|
|
175
|
+
sent.disconnect()
|
|
176
|
+
if (form.dataset.wbState !== 'sent') return
|
|
177
|
+
if (fallback) api.toast('Sent. No agent waits on this page; the fallback agent picks it up.')
|
|
178
|
+
else api.toast('Sent, but no agent is listening right now. Your answer stays in the log until one checks this page.', { kind: 'warn' })
|
|
179
|
+
})
|
|
180
|
+
sent.observe(form, { attributes: true, attributeFilter: ['data-wb-state'] })
|
|
181
|
+
})
|
|
182
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
// The agent's messages the reader hasn't read (status.ts: unreadMessages), and reading them: an
|
|
2
|
+
// element marked `data-wb-message="<event id>"` (a reply in an open thread, a chat bubble) reads
|
|
3
|
+
// its message once it has been mostly in view while the tab is visible. Reads are sent together, a
|
|
4
|
+
// moment later, as one `whiteboard:read` event.
|
|
5
|
+
import type { WbEvent } from '../define.ts'
|
|
6
|
+
import { READ, unreadMessages } from '../status.ts'
|
|
7
|
+
|
|
8
|
+
let isMessage: (type: string) => boolean = () => false
|
|
9
|
+
let getEvents: () => WbEvent[] = () => []
|
|
10
|
+
let send: (ids: string[]) => void = () => {}
|
|
11
|
+
// read here but not in the log yet: they don't count as unread meanwhile
|
|
12
|
+
const sending = new Set<string>()
|
|
13
|
+
|
|
14
|
+
export const unread = (): WbEvent[] => unreadMessages(getEvents(), isMessage).filter(e => !sending.has(e.id))
|
|
15
|
+
|
|
16
|
+
// read, to send in the next batch
|
|
17
|
+
const queued = new Set<string>()
|
|
18
|
+
let timer = 0
|
|
19
|
+
export function markRead(ids: string[]) {
|
|
20
|
+
const open = new Set(unread().map(e => e.id))
|
|
21
|
+
const fresh = ids.filter(id => open.has(id))
|
|
22
|
+
if (!fresh.length) return
|
|
23
|
+
for (const id of fresh) { sending.add(id); queued.add(id) }
|
|
24
|
+
clearTimeout(timer)
|
|
25
|
+
timer = window.setTimeout(() => {
|
|
26
|
+
const batch = [...queued]
|
|
27
|
+
queued.clear()
|
|
28
|
+
if (batch.length) send(batch)
|
|
29
|
+
}, 300)
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Once the log has the reads, they need no holding. */
|
|
33
|
+
export function readsArrived(events: WbEvent[]) {
|
|
34
|
+
for (const e of events) if (e.type === READ) for (const id of (e.data?.ids as unknown[] | undefined) ?? []) sending.delete(String(id))
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// what is in view now, read once the tab is visible too
|
|
38
|
+
const inView = new Set<string>()
|
|
39
|
+
const seen = new IntersectionObserver(entries => {
|
|
40
|
+
for (const entry of entries) {
|
|
41
|
+
const id = (entry.target as HTMLElement).dataset.wbMessage!
|
|
42
|
+
if (entry.isIntersecting) inView.add(id)
|
|
43
|
+
else inView.delete(id)
|
|
44
|
+
}
|
|
45
|
+
readVisible()
|
|
46
|
+
}, { threshold: 0.6 })
|
|
47
|
+
|
|
48
|
+
function readVisible() {
|
|
49
|
+
if (document.visibilityState === 'visible' && inView.size) markRead([...inView])
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const observed = new WeakSet<Element>()
|
|
53
|
+
function observeMessages() {
|
|
54
|
+
const open = new Set(unread().map(e => e.id))
|
|
55
|
+
for (const el of document.querySelectorAll<HTMLElement>('[data-wb-message]')) {
|
|
56
|
+
if (observed.has(el) || !open.has(el.dataset.wbMessage!)) continue
|
|
57
|
+
observed.add(el)
|
|
58
|
+
seen.observe(el)
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function trackReading(options: { messages: string[]; events: () => WbEvent[]; send: (ids: string[]) => void }) {
|
|
63
|
+
const types = new Set(options.messages)
|
|
64
|
+
isMessage = type => types.has(type)
|
|
65
|
+
getEvents = options.events
|
|
66
|
+
send = options.send
|
|
67
|
+
new MutationObserver(observeMessages).observe(document.body, { childList: true, subtree: true })
|
|
68
|
+
document.addEventListener('visibilitychange', readVisible)
|
|
69
|
+
observeMessages()
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** After the events changed: messages that came since may already be on screen. */
|
|
73
|
+
export const messagesChanged = () => observeMessages()
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
// The core in the browser: the page's events, the live channel, and handing the page to the page
|
|
2
|
+
// module (./page: markdown live, the blocks' islands) and the plugins' modules. When the config failed
|
|
3
|
+
// to load, the page is its raw text: the server's HTML, replaced when it changes.
|
|
4
|
+
import type { Api, PluginMount, Listener, PageHandle, RenderedPage, StoredPage, WbEvent } from '../define'
|
|
5
|
+
import { html } from '../html.ts'
|
|
6
|
+
import { formsApi, trackForms } from './forms'
|
|
7
|
+
import { toast } from './toast'
|
|
8
|
+
import { markRead, messagesChanged, readsArrived, trackReading, unread } from './read'
|
|
9
|
+
import { READ } from '../status.ts'
|
|
10
|
+
import { markdown } from './markdown'
|
|
11
|
+
|
|
12
|
+
interface Handoff {
|
|
13
|
+
id: string; kind: StoredPage['kind']; data: unknown
|
|
14
|
+
/** the page module; null for raw text */
|
|
15
|
+
client: string | null
|
|
16
|
+
/** the plugins' browser modules */
|
|
17
|
+
plugins: { name: string; client: string }[]
|
|
18
|
+
/** the event types that, from the agent, are messages for the reader */
|
|
19
|
+
messages: string[]
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const handoff: Handoff = JSON.parse(document.getElementById('wb-page')!.textContent!)
|
|
23
|
+
const root = document.getElementById('wb-root')!
|
|
24
|
+
const page = handoff.id
|
|
25
|
+
const isDir = handoff.kind === 'pages' || handoff.kind === 'folder'
|
|
26
|
+
|
|
27
|
+
// ---- events ------------------------------------------------------------------------------------
|
|
28
|
+
|
|
29
|
+
let events: WbEvent[] = []
|
|
30
|
+
const eventListeners = new Set<(events: WbEvent[]) => void>()
|
|
31
|
+
function setEvents(next: WbEvent[]) {
|
|
32
|
+
events = next
|
|
33
|
+
readsArrived(events)
|
|
34
|
+
for (const fn of eventListeners) fn(events)
|
|
35
|
+
messagesChanged()
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async function loadEvents() {
|
|
39
|
+
const res = await fetch(`/api/events?page=${encodeURIComponent(page)}`)
|
|
40
|
+
const all: WbEvent[] = await res.json()
|
|
41
|
+
setEvents(all.filter(e => e.page === page))
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
async function append(type: string, data: Record<string, unknown> = {}, action: string | null = null): Promise<WbEvent> {
|
|
45
|
+
const res = await fetch('/api/events', {
|
|
46
|
+
method: 'POST',
|
|
47
|
+
headers: { 'content-type': 'application/json' },
|
|
48
|
+
body: JSON.stringify({ page, type, action, data }),
|
|
49
|
+
})
|
|
50
|
+
if (!res.ok) throw new Error(await res.text())
|
|
51
|
+
const saved: WbEvent = await res.json()
|
|
52
|
+
if (!events.some(e => e.id === saved.id)) setEvents([...events, saved])
|
|
53
|
+
return saved
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
let listeners: Listener[] = []
|
|
57
|
+
const listenerListeners = new Set<(listeners: Listener[]) => void>()
|
|
58
|
+
|
|
59
|
+
async function loadListeners() {
|
|
60
|
+
listeners = await (await fetch(`/api/listeners?page=${encodeURIComponent(page)}`)).json()
|
|
61
|
+
for (const fn of listenerListeners) fn(listeners)
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const renderedListeners = new Set<() => void>()
|
|
65
|
+
|
|
66
|
+
// ---- the corner and the title ------------------------------------------------------------------
|
|
67
|
+
|
|
68
|
+
// the server puts it in the page; a page from a server older than this runtime has none
|
|
69
|
+
const corner = document.getElementById('wb-dock') ?? document.body.appendChild(Object.assign(document.createElement('div'), { id: 'wb-dock' }))
|
|
70
|
+
let baseTitle = document.title
|
|
71
|
+
const badges = new Map<string, { text: string; order: number; since: number }>()
|
|
72
|
+
let badgeCount = 0
|
|
73
|
+
function writeTitle() {
|
|
74
|
+
const list = [...badges.values()].sort((a, b) => a.order - b.order || a.since - b.since)
|
|
75
|
+
document.title = `${list.map(b => `(${b.text}) `).join('')}${baseTitle}`
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const api: Api = {
|
|
79
|
+
page,
|
|
80
|
+
events: () => events,
|
|
81
|
+
onEvents(fn) { eventListeners.add(fn); return () => eventListeners.delete(fn) },
|
|
82
|
+
last: type => events.findLast(e => e.type === type),
|
|
83
|
+
pickedUp: id => !!events.find(e => e.id === id)?.pickedUp,
|
|
84
|
+
unread,
|
|
85
|
+
markRead,
|
|
86
|
+
markdown,
|
|
87
|
+
append,
|
|
88
|
+
listeners: () => listeners,
|
|
89
|
+
onListeners(fn) { listenerListeners.add(fn); return () => listenerListeners.delete(fn) },
|
|
90
|
+
rendered() { for (const fn of renderedListeners) fn() },
|
|
91
|
+
onRendered(fn) { renderedListeners.add(fn); return () => renderedListeners.delete(fn) },
|
|
92
|
+
corner: () => corner,
|
|
93
|
+
badge(key, text, order = 0) {
|
|
94
|
+
if (text == null) badges.delete(key)
|
|
95
|
+
else badges.set(key, { text, order, since: badges.get(key)?.since ?? badgeCount++ })
|
|
96
|
+
writeTitle()
|
|
97
|
+
},
|
|
98
|
+
title(title) { baseTitle = title; writeTitle() },
|
|
99
|
+
toast,
|
|
100
|
+
...formsApi,
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// ---- the page ----------------------------------------------------------------------------------
|
|
104
|
+
|
|
105
|
+
const changeListeners = new Set<() => void>()
|
|
106
|
+
|
|
107
|
+
async function getJson<T>(url: string): Promise<T> {
|
|
108
|
+
const res = await fetch(url)
|
|
109
|
+
if (!res.ok) throw new Error(`${url}: ${res.status}`)
|
|
110
|
+
return res.json()
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const handle: PageHandle = {
|
|
114
|
+
id: page,
|
|
115
|
+
kind: handoff.kind,
|
|
116
|
+
data: handoff.data,
|
|
117
|
+
onChange(fn) { changeListeners.add(fn); return () => changeListeners.delete(fn) },
|
|
118
|
+
render: () => getJson<RenderedPage>(`/api/render?page=${encodeURIComponent(page)}`),
|
|
119
|
+
stored: () => getJson<StoredPage>(`/api/page?page=${encodeURIComponent(page)}`),
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// raw text: the server's HTML is the page, replaced when the page changes
|
|
123
|
+
if (!handoff.client) handle.onChange(async () => { root.innerHTML = (await handle.render()).html; api.rendered() })
|
|
124
|
+
|
|
125
|
+
// ---- live channel ------------------------------------------------------------------------------
|
|
126
|
+
|
|
127
|
+
function connect() {
|
|
128
|
+
const es = new EventSource(`/api/watch?page=${encodeURIComponent(page)}${isDir ? '&dir' : ''}`)
|
|
129
|
+
es.onopen = () => {
|
|
130
|
+
document.documentElement.dataset.wbLive = ''
|
|
131
|
+
// after a server restart: who is listening now, and what was answered meanwhile
|
|
132
|
+
loadListeners()
|
|
133
|
+
loadEvents()
|
|
134
|
+
}
|
|
135
|
+
es.onerror = () => { delete document.documentElement.dataset.wbLive }
|
|
136
|
+
es.addEventListener('change', () => { for (const fn of changeListeners) fn() })
|
|
137
|
+
es.addEventListener('events', () => loadEvents())
|
|
138
|
+
es.addEventListener('listeners', () => loadListeners())
|
|
139
|
+
// browser code changed; the page keeps what matters across a reload itself. Reload only once
|
|
140
|
+
// the server answers: reloading while it restarts would leave the browser's error page, which
|
|
141
|
+
// has nothing left in it to recover with.
|
|
142
|
+
es.addEventListener('reload', () => {
|
|
143
|
+
const go = async () => {
|
|
144
|
+
try { if ((await fetch('/api/health', { cache: 'no-store' })).ok) return location.reload() } catch { /* not up yet */ }
|
|
145
|
+
setTimeout(go, 500)
|
|
146
|
+
}
|
|
147
|
+
go()
|
|
148
|
+
})
|
|
149
|
+
es.addEventListener('style', () => {
|
|
150
|
+
for (const link of document.querySelectorAll<HTMLLinkElement>('link[rel=stylesheet]')) {
|
|
151
|
+
const url = new URL(link.href)
|
|
152
|
+
if (url.origin !== location.origin) continue
|
|
153
|
+
url.searchParams.set('t', String(Date.now()))
|
|
154
|
+
link.href = url.pathname + url.search
|
|
155
|
+
}
|
|
156
|
+
})
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
await Promise.all([loadEvents(), loadListeners()])
|
|
160
|
+
if (handoff.client) {
|
|
161
|
+
try {
|
|
162
|
+
const mount: PluginMount = (await import(handoff.client)).default
|
|
163
|
+
await mount(root, handle, api)
|
|
164
|
+
} catch (err) {
|
|
165
|
+
console.error('page:', err)
|
|
166
|
+
root.insertAdjacentHTML('afterbegin', String(html`<pre class="wb-error" role="alert">the page failed to start: ${(err as Error).message}</pre>`))
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
// named forms, once the page is on the page
|
|
170
|
+
trackForms(root, page, api)
|
|
171
|
+
trackReading({ messages: handoff.messages ?? [], events: () => events, send: ids => { append(READ, { ids }).catch(err => console.error('marking read:', err)) } })
|
|
172
|
+
// the plugins' modules after the page, so that what they work on is there; one failing leaves the others
|
|
173
|
+
await Promise.all((handoff.plugins ?? []).map(async ext => {
|
|
174
|
+
try {
|
|
175
|
+
const mount: PluginMount = (await import(ext.client)).default
|
|
176
|
+
if (typeof mount !== 'function') throw new Error('the client module must export a mount(root, page, api) function as default')
|
|
177
|
+
await mount(root, handle, api)
|
|
178
|
+
} catch (err) {
|
|
179
|
+
console.error(`plugin ${ext.name}:`, err)
|
|
180
|
+
root.insertAdjacentHTML('afterbegin', String(html`<pre class="wb-error" role="alert">plugin "${ext.name}" failed in the browser: ${(err as Error).message}</pre>`))
|
|
181
|
+
}
|
|
182
|
+
}))
|
|
183
|
+
connect()
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// Toasts (api.toast): a short message at the bottom of the window, above what covers its bottom
|
|
2
|
+
// (--wb-inset-bottom), for what the reader should know when it happens, wherever they are scrolled.
|
|
3
|
+
// One goes after a few seconds, or on a click (a click runs `onClick` first). One with `ms: 0`
|
|
4
|
+
// stays: a click only runs `onClick`, and whoever made it closes it, or changes its text, through
|
|
5
|
+
// what toast() returns. Its look is the core's (server.ts), with the page's theme colours.
|
|
6
|
+
import type { Toast, ToastOptions } from '../define.ts'
|
|
7
|
+
|
|
8
|
+
const box = document.createElement('div')
|
|
9
|
+
box.id = 'wb-toasts'
|
|
10
|
+
box.setAttribute('role', 'status')
|
|
11
|
+
box.setAttribute('aria-live', 'polite')
|
|
12
|
+
|
|
13
|
+
export function toast(text: string, { kind = 'info', ms = 7000, onClick }: ToastOptions = {}): Toast {
|
|
14
|
+
if (!box.isConnected) document.body.append(box)
|
|
15
|
+
const el = document.createElement('div')
|
|
16
|
+
el.className = 'wb-toast'
|
|
17
|
+
el.dataset.kind = kind
|
|
18
|
+
if (onClick) el.dataset.action = ''
|
|
19
|
+
el.textContent = text
|
|
20
|
+
const close = () => el.remove()
|
|
21
|
+
el.addEventListener('click', () => { if (ms) close(); onClick?.() })
|
|
22
|
+
if (ms) setTimeout(close, ms)
|
|
23
|
+
box.append(el)
|
|
24
|
+
return { close, update: next => { el.textContent = next } }
|
|
25
|
+
}
|
package/src/config.ts
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
// The project, its files, and page ids.
|
|
2
|
+
//
|
|
3
|
+
// A project is a folder (usually a repository root) with a `.whiteboard/` folder in it.
|
|
4
|
+
// Everything whiteboard keeps lives in that folder:
|
|
5
|
+
// config.ts what the project changes from the defaults (optional)
|
|
6
|
+
// pages/ the pages, served at /<page>
|
|
7
|
+
// events.ndjson the events: form submits, chat messages, comments, and what agents picked up
|
|
8
|
+
// token the secret for what runs code (the terminal), made on first use
|
|
9
|
+
// server.json the port and process of this project's running server
|
|
10
|
+
// server.log that server's output
|
|
11
|
+
// Each project runs its own server; nothing is shared between projects.
|
|
12
|
+
import path from 'node:path'
|
|
13
|
+
import fs from 'node:fs'
|
|
14
|
+
|
|
15
|
+
/** A project: its folders and files. */
|
|
16
|
+
export interface Project {
|
|
17
|
+
/** the project folder */
|
|
18
|
+
dir: string
|
|
19
|
+
/** its .whiteboard folder */
|
|
20
|
+
wb: string
|
|
21
|
+
readonly configFile: string | null
|
|
22
|
+
pagesDir: string
|
|
23
|
+
eventsFile: string
|
|
24
|
+
serverFile: string
|
|
25
|
+
logFile: string
|
|
26
|
+
readonly name: string
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export const CONFIG_NAMES = ['config.ts', 'config.mts', 'config.js', 'config.mjs']
|
|
30
|
+
/** the port a project's server tries first; it takes the next free one when that is taken */
|
|
31
|
+
export const DEFAULT_PORT = Number(process.env.WHITEBOARD_PORT || 4777)
|
|
32
|
+
|
|
33
|
+
/** The config file in a `.whiteboard` folder, or null. */
|
|
34
|
+
export function configFileIn(whiteboardDir: string): string | null {
|
|
35
|
+
for (const name of CONFIG_NAMES) {
|
|
36
|
+
const f = path.join(whiteboardDir, name)
|
|
37
|
+
if (fs.existsSync(f)) return f
|
|
38
|
+
}
|
|
39
|
+
return null
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const isDir = (p: string) => { try { return fs.statSync(p).isDirectory() } catch { return false } }
|
|
43
|
+
|
|
44
|
+
/** The project folder a path is in: the nearest folder upward with a `.whiteboard/` folder. */
|
|
45
|
+
export function findProjectDir(from: string = process.cwd()): string | null {
|
|
46
|
+
let dir = path.resolve(from)
|
|
47
|
+
for (;;) {
|
|
48
|
+
if (isDir(path.join(dir, '.whiteboard'))) return dir
|
|
49
|
+
const up = path.dirname(dir)
|
|
50
|
+
if (up === dir) return null
|
|
51
|
+
dir = up
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Everything about the project in `dir`, or null when `dir` is not one. */
|
|
56
|
+
export function project(dir: string | null | undefined): Project | null {
|
|
57
|
+
if (!dir) return null
|
|
58
|
+
const wb = path.join(dir, '.whiteboard')
|
|
59
|
+
if (!isDir(wb)) return null
|
|
60
|
+
return {
|
|
61
|
+
dir,
|
|
62
|
+
wb,
|
|
63
|
+
/** the config file, or null: looked up each time, since one can be added or removed while a server runs */
|
|
64
|
+
get configFile() { return configFileIn(wb) },
|
|
65
|
+
pagesDir: path.join(wb, 'pages'),
|
|
66
|
+
eventsFile: path.join(wb, 'events.ndjson'),
|
|
67
|
+
serverFile: path.join(wb, 'server.json'),
|
|
68
|
+
logFile: path.join(wb, 'server.log'),
|
|
69
|
+
/** shown in titles and the overview: `name` in the config if it is a plain literal, else the folder name */
|
|
70
|
+
get name() {
|
|
71
|
+
const file = configFileIn(wb)
|
|
72
|
+
return (file && (/\bname\s*:\s*['"]([^'"]+)['"]/.exec(fs.readFileSync(file, 'utf8')) ?? [])[1]) || path.basename(dir)
|
|
73
|
+
},
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// ---- page ids ----------------------------------------------------------------------------------
|
|
78
|
+
|
|
79
|
+
const strip = (p: string) => p.replace(/\\/g, '/').replace(/\.md$/, '').replace(/^\/+|\/+$/g, '')
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* A file path or page name → the page id used in URLs and events.
|
|
83
|
+
* - a file inside the pages folder → "<path>" without .md
|
|
84
|
+
* - any other file inside the project folder → "-/<path>" (shown from the repository)
|
|
85
|
+
* - anything else → the name as given, without .md
|
|
86
|
+
*/
|
|
87
|
+
export function pageId(proj: Project | null, input: unknown, cwd: string = process.cwd()): string {
|
|
88
|
+
if (!input) return ''
|
|
89
|
+
const s = String(input)
|
|
90
|
+
const looksLikeFile = path.isAbsolute(s) || s.startsWith('.') || /\.\w+$/.test(s)
|
|
91
|
+
if (!looksLikeFile || !proj) return strip(s)
|
|
92
|
+
const abs = path.resolve(cwd, s)
|
|
93
|
+
if (abs.startsWith(proj.pagesDir + path.sep)) return strip(path.relative(proj.pagesDir, abs))
|
|
94
|
+
if (abs === proj.dir || abs.startsWith(proj.dir + path.sep)) return `-/${path.relative(proj.dir, abs).replace(/\\/g, '/')}`.replace(/\/$/, '')
|
|
95
|
+
return strip(s)
|
|
96
|
+
}
|