@bigmistqke/whiteboard 0.1.0 → 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.
Files changed (73) hide show
  1. package/README.md +31 -12
  2. package/bin/whiteboard.ts +74 -17
  3. package/dist/bin/whiteboard.js +93 -22
  4. package/dist/client/runtime.js +164 -11
  5. package/dist/plugins/chat/README.md +2 -1
  6. package/dist/plugins/chat/client.js +2 -2
  7. package/dist/plugins/chat/index.js +1 -0
  8. package/dist/plugins/chat/style.css +7 -0
  9. package/dist/plugins/code/diff.js +1 -0
  10. package/dist/plugins/comments/client.js +6 -6
  11. package/dist/plugins/comments/index.js +4 -1
  12. package/dist/plugins/comments/style.css +8 -0
  13. package/dist/plugins/forge/README.md +12 -0
  14. package/dist/plugins/forge/index.js +83 -0
  15. package/dist/plugins/gallery/client.js +1 -1
  16. package/dist/plugins/iframe/README.md +18 -0
  17. package/dist/plugins/iframe/client.js +1 -0
  18. package/dist/plugins/iframe/index.js +40 -0
  19. package/dist/plugins/iframe/style.css +29 -0
  20. package/dist/plugins/index.js +4 -0
  21. package/dist/plugins/mermaid/index.js +1 -0
  22. package/dist/solid/index.js +2 -1
  23. package/dist/src/client/page/base.css +33 -12
  24. package/dist/src/client/page/main.js +246 -22
  25. package/dist/src/events.js +24 -3
  26. package/dist/src/icons.js +6 -0
  27. package/dist/src/loader.js +12 -6
  28. package/dist/src/pages/blocks.js +1 -0
  29. package/dist/src/pages/index.js +3 -2
  30. package/dist/src/pages/markdown.js +107 -4
  31. package/dist/src/pages/render.js +63 -9
  32. package/dist/src/server.js +37 -12
  33. package/dist/src/status.js +38 -10
  34. package/package.json +1 -1
  35. package/plugins/chat/README.md +2 -1
  36. package/plugins/chat/client.tsx +15 -3
  37. package/plugins/chat/index.ts +1 -1
  38. package/plugins/chat/style.css +7 -0
  39. package/plugins/code/diff.ts +7 -1
  40. package/plugins/comments/client.ts +50 -6
  41. package/plugins/comments/index.ts +4 -2
  42. package/plugins/comments/style.css +8 -0
  43. package/plugins/forge/README.md +12 -0
  44. package/plugins/forge/index.ts +71 -0
  45. package/plugins/iframe/README.md +18 -0
  46. package/plugins/iframe/client.ts +46 -0
  47. package/plugins/iframe/index.ts +54 -0
  48. package/plugins/iframe/style.css +29 -0
  49. package/plugins/index.ts +3 -1
  50. package/plugins/mermaid/index.ts +1 -0
  51. package/skills/whiteboard/SKILL.md +17 -7
  52. package/solid/index.tsx +3 -0
  53. package/src/client/forms.ts +5 -6
  54. package/src/client/markdown.ts +36 -0
  55. package/src/client/page/base.css +33 -12
  56. package/src/client/page/elsewhere.ts +70 -0
  57. package/src/client/page/live.ts +30 -0
  58. package/src/client/page/main.ts +25 -2
  59. package/src/client/page/sort.ts +38 -0
  60. package/src/client/page/waiting.ts +102 -29
  61. package/src/client/read.ts +73 -0
  62. package/src/client/runtime.ts +13 -0
  63. package/src/client/toast.ts +25 -0
  64. package/src/define.ts +79 -13
  65. package/src/events.ts +27 -3
  66. package/src/icons.ts +8 -0
  67. package/src/loader.ts +7 -4
  68. package/src/pages/blocks.ts +3 -0
  69. package/src/pages/index.ts +8 -2
  70. package/src/pages/markdown.ts +92 -4
  71. package/src/pages/render.ts +49 -12
  72. package/src/server.ts +35 -12
  73. package/src/status.ts +64 -20
@@ -0,0 +1,38 @@
1
+ // A list the reader can sort: a `<select data-wb-sort="<name>">` sorts the `ul` after its heading
2
+ // by what each `li` carries (`data-order`, `data-updated`, `data-title`: the overview's documents).
3
+ // The choice is kept per list in this browser, and put back after a live update, which writes the
4
+ // list again in the server's order.
5
+ const KEY = (name: string) => `wb-sort:${name}`
6
+
7
+ function sortList(select: HTMLSelectElement) {
8
+ const list = select.closest('section')?.querySelector('ul')
9
+ if (!list) return
10
+ const by = select.value
11
+ const value = (li: HTMLElement) => by === 'title' ? li.dataset.title ?? '' : Number(by === 'updated' ? li.dataset.updated : li.dataset.order)
12
+ const rows = [...list.children] as HTMLElement[]
13
+ rows.sort((a, b) => {
14
+ const x = value(a), y = value(b)
15
+ if (by === 'updated') return (y as number) - (x as number)
16
+ return typeof x === 'string' ? x.localeCompare(y as string) : (x as number) - (y as number)
17
+ })
18
+ list.append(...rows)
19
+ }
20
+
21
+ export function applySorts() {
22
+ for (const select of document.querySelectorAll<HTMLSelectElement>('select[data-wb-sort]')) {
23
+ let kept: string | null = null
24
+ try { kept = localStorage.getItem(KEY(select.dataset.wbSort!)) } catch { /* private window */ }
25
+ if (kept && [...select.options].some(o => o.value === kept)) select.value = kept
26
+ sortList(select)
27
+ }
28
+ }
29
+
30
+ export function trackSorts() {
31
+ document.addEventListener('change', e => {
32
+ const select = e.target as HTMLSelectElement
33
+ if (!select.matches?.('select[data-wb-sort]')) return
34
+ try { localStorage.setItem(KEY(select.dataset.wbSort!), select.value) } catch { /* private window */ }
35
+ sortList(select)
36
+ })
37
+ applySorts()
38
+ }
@@ -1,19 +1,25 @@
1
- // How the page shows what an agent waits for. The core marks each named form with where it stands
2
- // (waiting, unheard, pending, decided; see `api.onForms`); the page styles those marks (base.css),
3
- // folds a decided form into one line quoting its answer, sums the states up in a line above the
4
- // page, puts a button in the page's corner that jumps from one waiting form to the next, and counts
5
- // the waiting ones in the tab title.
6
- import type { Api, FormState, FormStatus } from '../../define.ts'
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'
7
12
  import { viewBottom } from './view'
8
13
  import { STATES } from '../../status.ts'
14
+ import { WAITING_HASH } from './elsewhere'
9
15
 
10
16
  const ORDER = STATES
11
17
  const LABEL: Record<FormState, (n: number) => string> = {
12
- waiting: n => `${n} waiting for you`,
13
- unheard: n => `${n} nobody listening`,
18
+ open: n => `${n} waiting for you`,
14
19
  pending: n => `${n} waiting for the agent`,
15
20
  decided: n => `${n} decided`,
16
21
  }
22
+ const messagesLabel = (n: number) => `${n} unread message${n === 1 ? '' : 's'} from the agent`
17
23
 
18
24
  let main: HTMLElement
19
25
  let api: Api
@@ -35,60 +41,108 @@ const reopened = new Map<string, string>()
35
41
 
36
42
  const inState = (state: FormState) => forms.filter(f => f.state === state && f.form.isConnected).map(f => f.form)
37
43
 
38
- function show(list: FormStatus[]) {
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) {
39
65
  forms = list
40
66
  for (const { form, name, state, last } of forms) {
41
67
  if (last && reopened.has(name) && reopened.get(name) !== last.id && state === 'decided') reopened.delete(name)
42
68
  form.toggleAttribute('data-wb-folded', state === 'decided' && !reopened.has(name))
43
69
  }
44
- const parts = ORDER.map(state => [state, inState(state).length] as const).filter(([, count]) => count)
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)])
45
73
  summary.hidden = !parts.length
46
- summary.replaceChildren(...parts.flatMap(([state, count], i) => {
74
+ summary.replaceChildren(...parts.flatMap(([state, text], i) => {
47
75
  const link = document.createElement('button')
48
76
  link.type = 'button'
49
77
  link.dataset.state = state
50
- link.textContent = LABEL[state](count)
78
+ link.textContent = text
51
79
  return i ? [document.createTextNode(' · '), link] : [link]
52
80
  }))
53
- const n = inState('waiting').length
81
+ const n = inState('open').length + unread
54
82
  button.hidden = n === 0
55
83
  button.textContent = `→ waiting for you (${n})`
56
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
+ }
57
102
  }
58
103
 
59
- // The form a jump went to last, and where the page was scrolled then: jumping again in the same
60
- // state goes to the one after it, round to the first. Once the reader scrolled themselves, the
61
- // next one is the first below where they are.
62
- let current: HTMLFormElement | null = null
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
63
112
  let scrolledTo = 0
64
113
 
65
- function next(state: FormState) {
66
- const list = inState(state)
114
+ function next(list: HTMLElement[]) {
67
115
  const i = current ? list.indexOf(current) : -1
68
116
  if (i >= 0 && Math.abs(scrollY - scrolledTo) < 40) return list[(i + 1) % list.length]
69
117
  return list.find(f => f.getBoundingClientRect().top > viewBottom() / 2) ?? list[0]
70
118
  }
71
119
 
72
- function jump(state: FormState) {
73
- const form = next(state)
74
- if (!form) return
75
- current = form
76
- // the form centred in the part of the window the page is seen in (above the terminal drawer),
77
- // as far as the page allows
78
- const r = form.getBoundingClientRect()
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()
79
131
  scrolledTo = Math.max(0, Math.min(scrollY + r.top + r.height / 2 - viewBottom() / 2, document.documentElement.scrollHeight - innerHeight))
80
132
  scrollTo({ top: scrolledTo, behavior: 'smooth' })
81
- if (state === 'waiting') form.querySelector<HTMLElement>('input:not([type=hidden]), textarea, select, button')?.focus({ preventScroll: true })
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 }))
82
136
  }
83
137
 
84
138
  export function trackWaiting(root: HTMLElement, core: Api) {
85
139
  main = root
86
140
  api = core
87
141
  api.corner().prepend(button)
88
- button.addEventListener('click', () => jump('waiting'))
142
+ button.addEventListener('click', () => jump('all'))
89
143
  main.before(summary)
90
144
  summary.addEventListener('click', e => {
91
- const state = (e.target as HTMLElement).closest<HTMLElement>('button[data-state]')?.dataset.state as FormState | undefined
145
+ const state = (e.target as HTMLElement).closest<HTMLElement>('button[data-state]')?.dataset.state as FormState | 'messages' | undefined
92
146
  if (state) jump(state)
93
147
  })
94
148
  // a folded form opens again on a click, to change the answer; not on one in its thread, which
@@ -105,5 +159,24 @@ export function trackWaiting(root: HTMLElement, core: Api) {
105
159
  form.querySelector<HTMLElement>('input:not([type=hidden]), textarea, select')?.focus({ preventScroll: true })
106
160
  })
107
161
  api.onForms(show)
162
+ // a message read, or a new one
163
+ api.onEvents(() => show())
108
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
+ })
109
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()
@@ -4,6 +4,10 @@
4
4
  import type { Api, PluginMount, Listener, PageHandle, RenderedPage, StoredPage, WbEvent } from '../define'
5
5
  import { html } from '../html.ts'
6
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'
7
11
 
8
12
  interface Handoff {
9
13
  id: string; kind: StoredPage['kind']; data: unknown
@@ -11,6 +15,8 @@ interface Handoff {
11
15
  client: string | null
12
16
  /** the plugins' browser modules */
13
17
  plugins: { name: string; client: string }[]
18
+ /** the event types that, from the agent, are messages for the reader */
19
+ messages: string[]
14
20
  }
15
21
 
16
22
  const handoff: Handoff = JSON.parse(document.getElementById('wb-page')!.textContent!)
@@ -24,7 +30,9 @@ let events: WbEvent[] = []
24
30
  const eventListeners = new Set<(events: WbEvent[]) => void>()
25
31
  function setEvents(next: WbEvent[]) {
26
32
  events = next
33
+ readsArrived(events)
27
34
  for (const fn of eventListeners) fn(events)
35
+ messagesChanged()
28
36
  }
29
37
 
30
38
  async function loadEvents() {
@@ -73,6 +81,9 @@ const api: Api = {
73
81
  onEvents(fn) { eventListeners.add(fn); return () => eventListeners.delete(fn) },
74
82
  last: type => events.findLast(e => e.type === type),
75
83
  pickedUp: id => !!events.find(e => e.id === id)?.pickedUp,
84
+ unread,
85
+ markRead,
86
+ markdown,
76
87
  append,
77
88
  listeners: () => listeners,
78
89
  onListeners(fn) { listenerListeners.add(fn); return () => listenerListeners.delete(fn) },
@@ -85,6 +96,7 @@ const api: Api = {
85
96
  writeTitle()
86
97
  },
87
98
  title(title) { baseTitle = title; writeTitle() },
99
+ toast,
88
100
  ...formsApi,
89
101
  }
90
102
 
@@ -156,6 +168,7 @@ if (handoff.client) {
156
168
  }
157
169
  // named forms, once the page is on the page
158
170
  trackForms(root, page, api)
171
+ trackReading({ messages: handoff.messages ?? [], events: () => events, send: ids => { append(READ, { ids }).catch(err => console.error('marking read:', err)) } })
159
172
  // the plugins' modules after the page, so that what they work on is there; one failing leaves the others
160
173
  await Promise.all((handoff.plugins ?? []).map(async ext => {
161
174
  try {
@@ -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/define.ts CHANGED
@@ -58,6 +58,12 @@ export interface Plugin {
58
58
  blocks?: Record<string, Block<any>>
59
59
  /** a stylesheet linked on every page (for blocks, their own `style` links it only where they're used) */
60
60
  style?: URL | string
61
+ /**
62
+ * Text that links somewhere, as written in plain text (`#12` → an issue): the core turns each
63
+ * match into a link when it renders a page, but not inside code, links or inline directives.
64
+ * Called once per project folder (`dir`), so it can read the project (its git remote, say).
65
+ */
66
+ links?(ctx: { dir: string }): TextLink[]
61
67
  /**
62
68
  * The event types it writes to the log, named `<plugin name>:<what>`, and who they're for.
63
69
  * `whiteboard docs` lists them. Only those with `handOut: true` reach an agent unasked: a `wait`
@@ -85,12 +91,28 @@ export interface Plugin {
85
91
 
86
92
  export const definePlugin = (plugin: Plugin): Plugin => plugin
87
93
 
94
+ /** A pattern in a page's text that links somewhere (Plugin.links). */
95
+ export interface TextLink {
96
+ /** what to find; matched against each run of plain text */
97
+ pattern: RegExp
98
+ /** where a match links to; null leaves it as text */
99
+ href(match: RegExpExecArray): string | null
100
+ /** what the link says on hover */
101
+ title?(match: RegExpExecArray): string
102
+ }
103
+
88
104
  /** One of a plugin's event types. */
89
105
  export interface EventSpec {
90
106
  /** what it is, and its `data`: for `whiteboard docs` */
91
107
  description?: string
92
108
  /** hand it to an agent unasked, like a form's answer (a message for the agent); default false */
93
109
  handOut?: boolean
110
+ /**
111
+ * one from the agent is a message for the reader (a reply in a thread, a chat message): it waits
112
+ * for them until read, which the page records once its element (marked `data-wb-message` with the
113
+ * event's id) has been in view; default false
114
+ */
115
+ forReader?: boolean
94
116
  }
95
117
 
96
118
  export interface Project {
@@ -214,18 +236,22 @@ export interface CommandContext {
214
236
  /** What is open on one page. */
215
237
  export interface PageStatus {
216
238
  page: string
239
+ /** what the reader knows it by: its first heading, else its name */
240
+ title: string
217
241
  /** the page's file */
218
242
  file: string
219
243
  /** the session that claimed the page with `whiteboard new`, if one did */
220
244
  owner: string | null
221
245
  /** the event types the page waits on the reader for: its named forms */
222
246
  asks: string[]
223
- /** where each of them stands, as the page shows it: waiting, unheard, pending or decided */
247
+ /** where each of them stands, as the page shows it: open, pending or decided */
224
248
  questions: { name: string; state: FormState }[]
225
249
  /** those waiting for the reader: no answer yet, or a running wait asks for a new one */
226
250
  open: string[]
227
- /** the open ones no running wait or watch listens for */
251
+ /** the open ones no running wait or watch (but the fallback) takes */
228
252
  unheard: string[]
253
+ /** the agent's messages on the page the reader hasn't read (see EventSpec.forReader) */
254
+ unread: WbEvent[]
229
255
  /** the reader's events on the page that no wait, watch or hook handed out */
230
256
  unpicked: WbEvent[]
231
257
  /** the running waits and watches that cover the page */
@@ -287,8 +313,8 @@ export interface FolderSource extends StoredBase {
287
313
  /** The overview, or a folder of pages without an index.md. */
288
314
  export interface PagesSource extends StoredBase {
289
315
  kind: 'pages'
290
- /** `listeners`: how many agents are waiting for answers on the page right now */
291
- pages: { id: string; file: string; mtime: number; lastEvent: string | null; listeners: number }[]
316
+ /** `awaiting`: how many things on the page wait for the reader: open questions, unread messages */
317
+ pages: { id: string; file: string; mtime: number; lastEvent: string | null; awaiting: number }[]
292
318
  }
293
319
 
294
320
  /** What the core offers the pages on the server: how files are served and linked. */
@@ -353,6 +379,26 @@ export interface Listener {
353
379
  page: string
354
380
  type: string | null
355
381
  command: 'wait' | 'watch'
382
+ /**
383
+ * a `wait` or `watch` without `--page`: it takes only what no other listener would, and asks no
384
+ * question again. At most one runs per project.
385
+ */
386
+ fallback?: boolean
387
+ }
388
+
389
+ /** How a toast looks and acts: `warn` for something that may need the reader, how long it stays. */
390
+ export interface ToastOptions {
391
+ kind?: 'info' | 'warn'
392
+ /** milliseconds before it goes, 7000 by default; 0: it stays until closed through its `Toast` */
393
+ ms?: number
394
+ /** what a click on it does, besides closing it (a toast that stays, stays) */
395
+ onClick?: () => void
396
+ }
397
+
398
+ /** A toast on the screen: close it, or change what it says (a count that goes down). */
399
+ export interface Toast {
400
+ close(): void
401
+ update(text: string): void
356
402
  }
357
403
 
358
404
  /** What the core gives the page and every plugin in the browser. Framework-free: getters and subscriptions. */
@@ -369,6 +415,18 @@ export interface Api {
369
415
  append(type: string, data?: Record<string, unknown>, action?: string | null): Promise<WbEvent>
370
416
  /** has an agent picked this event up (a `wait` or `watch` handed it out)? */
371
417
  pickedUp(id: string): boolean
418
+ /**
419
+ * The agent's messages on this page the reader hasn't read, oldest first (see
420
+ * EventSpec.forReader). An element marked `data-wb-message="<event id>"` reads its message once
421
+ * it has been in view; `markRead` does so for messages read otherwise (a thread closed).
422
+ */
423
+ unread(): WbEvent[]
424
+ markRead(ids: string[]): void
425
+ /**
426
+ * A message's markdown (a comment, a chat message) as HTML, rendered by the server like a page:
427
+ * code fences highlighted, text links (`#12`), but raw HTML as text and no directives. Cached.
428
+ */
429
+ markdown(text: string): Promise<string>
372
430
  /** the agents waiting for answers on this page right now */
373
431
  listeners(): Listener[]
374
432
  onListeners(fn: (listeners: Listener[]) => void): () => void
@@ -393,10 +451,17 @@ export interface Api {
393
451
  badge(key: string, text: string | null, order?: number): void
394
452
  /** the page's own title, behind the badges */
395
453
  title(title: string): void
454
+ /**
455
+ * A short message at the bottom of the window, for what the reader should know when it happens,
456
+ * wherever they are scrolled: an answer nobody listens for, a reply in a thread. It goes after a
457
+ * few seconds, or on a click, which runs `onClick` first (go to what it is about); with `ms: 0`
458
+ * it stays until closed through what this returns.
459
+ */
460
+ toast(text: string, options?: ToastOptions): Toast
396
461
  /**
397
462
  * The page's named forms and where each stands. The core looks after every `<form name>` without
398
463
  * an `action`: it sends a submit as an event, keeps drafts, puts the last answer back, and marks
399
- * each form with its state (`data-wb-waiting`, `-unheard`, `-pending`, `-decided`). How that
464
+ * each form with its state (`data-wb-open`, `-pending`, `-decided`). How that
400
465
  * looks is the page's styles'; this is for drawing more than the attributes allow (a summary, a count)
401
466
  */
402
467
  forms(): FormStatus[]
@@ -411,7 +476,7 @@ export interface Api {
411
476
  * - pending: answered, but no agent has picked the answer up yet
412
477
  * - decided: an agent picked up its latest answer
413
478
  */
414
- export type FormState = 'waiting' | 'unheard' | 'pending' | 'decided'
479
+ export type FormState = 'open' | 'pending' | 'decided'
415
480
 
416
481
  export interface FormStatus {
417
482
  form: HTMLFormElement
@@ -425,20 +490,21 @@ export interface FormStatus {
425
490
  // ---- blocks ------------------------------------------------------------------------------------
426
491
 
427
492
  /**
428
- * A block handles the directive or fence with its name (its key in a plugin's `blocks`): `:::name`,
429
- * `::name`, `:name` and ```` ```name ````. Server functions run while the page renders; `client`
430
- * runs in the browser.
493
+ * A block handles the directives with its name (its key in a plugin's `blocks`): `:::name`,
494
+ * `::name` and `:name`; and, when it says so (`fence`), the code fences of that language,
495
+ * ```` ```name ````. Server functions run while the page renders; `client` runs in the browser.
431
496
  *
432
497
  * File references are URLs relative to the plugin's module, so they work wherever it is installed:
433
498
  * client: new URL('./client.js', import.meta.url)
434
499
  */
435
500
  export interface Block<Props = unknown> {
436
501
  /**
437
- * `'any'`: also render every fence no block claims by name, and the code view of repository
438
- * files: the block for code in general, such as a syntax highlighter. When several blocks set it,
439
- * the last plugin's wins.
502
+ * Which code fences it renders. `true`: those of its name (```` ```mermaid ````). `'any'`: those
503
+ * too, and every fence no block claims by name, and the code view of repository files: the block
504
+ * for code in general, such as a syntax highlighter (when several set it, the last plugin's wins).
505
+ * Without it, a fence of its name is code like any other: ```` ```text ```` is no text field.
440
506
  */
441
- fence?: 'any'
507
+ fence?: boolean | 'any'
442
508
  /** props for the client; JSON-serialisable. Without it a client gets the defaults (see DirectiveProps / FenceProps). */
443
509
  props?(ctx: ServerContext): Props | Promise<Props>
444
510
  /**
package/src/events.ts CHANGED
@@ -154,6 +154,13 @@ export interface HandOutOptions {
154
154
  interval?: number
155
155
  /** stops following */
156
156
  signal?: AbortSignal
157
+ /**
158
+ * Leave an event for now (the fallback: another listener would take it). A left event is looked
159
+ * at again each time `recheck` calls back, and handed out then if nobody picked it up meanwhile
160
+ * and it is no longer left.
161
+ */
162
+ skip?: (event: WbEvent) => boolean
163
+ recheck?: (again: () => void) => void
157
164
  }
158
165
 
159
166
  /**
@@ -168,7 +175,7 @@ export interface HandOutOptions {
168
175
  * `follow`, or when `signal` aborts.
169
176
  */
170
177
  export function handOut(file: string, filter: EventFilter, onEvent: (event: WbEvent) => void, options: HandOutOptions = {}): Promise<number> {
171
- const { count = Infinity, follow: following = true, interval, signal, forAgent: isForAgent = forAgent() } = options
178
+ const { count = Infinity, follow: following = true, interval, signal, forAgent: isForAgent = forAgent(), skip, recheck } = options
172
179
  return new Promise(resolve => {
173
180
  let got = 0
174
181
  let stop = () => {}
@@ -181,14 +188,31 @@ export function handOut(file: string, filter: EventFilter, onEvent: (event: WbEv
181
188
  pick(file, e)
182
189
  return ++got < count
183
190
  }
191
+ // the events left for now (skip), by id
192
+ const left = new Map<string, WbEvent>()
193
+ // false once enough were handed out; a left event is kept to look at again
194
+ const offer = (e: WbEvent) => {
195
+ if (skip?.(e)) { left.set(e.id, e); return true }
196
+ return hand(e)
197
+ }
184
198
  if (count <= 0 || signal?.aborted) return finish()
185
199
  const { events, end } = read(file)
186
200
  const picked = pickedUp(events)
187
201
  for (const e of events) {
188
- if (wanted(e) && !picked.has(e.id) && !hand(e)) return finish()
202
+ if (wanted(e) && !picked.has(e.id) && !offer(e)) return finish()
189
203
  }
190
204
  if (!following) return finish()
191
205
  signal?.addEventListener('abort', finish)
192
- stop = follow(file, end, e => { if (got < count && wanted(e) && !hand(e)) finish() }, { interval })
206
+ recheck?.(() => {
207
+ if (!left.size || got >= count) return
208
+ const picked = pickedUp(read(file).events)
209
+ for (const [id, e] of left) {
210
+ if (picked.has(id)) { left.delete(id); continue }
211
+ if (skip?.(e)) continue
212
+ left.delete(id)
213
+ if (!hand(e)) return finish()
214
+ }
215
+ })
216
+ stop = follow(file, end, e => { if (got < count && wanted(e) && !offer(e)) finish() }, { interval })
193
217
  })
194
218
  }
package/src/icons.ts ADDED
@@ -0,0 +1,8 @@
1
+ // Icons the page and the server both draw, as SVG markup. No Node in it: the browser runtime
2
+ // imports it too.
3
+
4
+ /** An inbox: what awaits the reader (the header's menu, the overview). */
5
+ export const INBOX_ICON = '<svg viewBox="0 0 16 16" width="13" height="13" aria-hidden="true"><path d="M2 9.5 3.8 3.2A1 1 0 0 1 4.8 2.5h6.4a1 1 0 0 1 1 .7L14 9.5V13a.5.5 0 0 1-.5.5h-11A.5.5 0 0 1 2 13Zm0 0h3.5l1 1.5h3l1-1.5H14" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linejoin="round"/></svg>'
6
+
7
+ /** "Awaiting you: 2 things", and where: what the inbox says to a reader who hovers it. */
8
+ export const awaitingLabel = (n: number, where = '') => `Awaiting you: ${n === 1 ? '1 question or message' : `${n} questions and messages`}${where}`