@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,499 @@
|
|
|
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, SlotName, StoredPage, WpEvent } from '../define'
|
|
5
|
+
import { html } from '../html.ts'
|
|
6
|
+
import { formsApi, trackForms } from './forms'
|
|
7
|
+
import { createToast } from './toast'
|
|
8
|
+
import { markRead, messagesChanged, readsArrived, trackReading, unread as unreadNow } from './read'
|
|
9
|
+
import { READ, SCROLL, fromReader } from '../status.ts'
|
|
10
|
+
import { blocks, markdown, message } from './markdown'
|
|
11
|
+
import { scrollToAnchor, scrollToTarget } from './scroll'
|
|
12
|
+
import { reactive } from './reactive'
|
|
13
|
+
import { url } from './base.ts'
|
|
14
|
+
|
|
15
|
+
interface Handoff {
|
|
16
|
+
id: string
|
|
17
|
+
kind: StoredPage['kind']
|
|
18
|
+
data: unknown
|
|
19
|
+
/** the page module; null for raw text */
|
|
20
|
+
client: string | null
|
|
21
|
+
/** the plugins' browser modules */
|
|
22
|
+
plugins: { name: string; client: string }[]
|
|
23
|
+
/** the event types that, from the agent, are messages for the reader */
|
|
24
|
+
messages: string[]
|
|
25
|
+
/** the page's frontmatter (PageHandle.frontmatter) */
|
|
26
|
+
frontmatter: Record<string, unknown>
|
|
27
|
+
/** false on a built page (`workpad build`): a file, no server behind it */
|
|
28
|
+
live?: boolean
|
|
29
|
+
/** what the browser runs and how it looks, as the server served them (see /api/stamps) */
|
|
30
|
+
stamps?: { code: string; style: string }
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const handoff: Handoff = JSON.parse(document.getElementById('wp-page')!.textContent!)
|
|
34
|
+
const root = document.getElementById('wp-root')!
|
|
35
|
+
const page = handoff.id
|
|
36
|
+
const isDir = handoff.kind === 'pages' || handoff.kind === 'folder'
|
|
37
|
+
// a built page has no server: no events, no listeners, no live channel, nothing to record
|
|
38
|
+
const live = handoff.live !== false
|
|
39
|
+
// a module's path as the page names it: a built page's are relative to the page, which an import()
|
|
40
|
+
// here would take as relative to this module
|
|
41
|
+
const moduleUrl = (path: string) => new URL(path, document.baseURI).href
|
|
42
|
+
|
|
43
|
+
// ---- events ------------------------------------------------------------------------------------
|
|
44
|
+
|
|
45
|
+
let events: WpEvent[] = []
|
|
46
|
+
const eventsValue = reactive(() => events)
|
|
47
|
+
// what is unread changes with the events, and with a message read here before the log has it
|
|
48
|
+
const unread = reactive(unreadNow)
|
|
49
|
+
function setEvents(next: WpEvent[]) {
|
|
50
|
+
events = next
|
|
51
|
+
readsArrived(events)
|
|
52
|
+
eventsValue.notify()
|
|
53
|
+
unread.notify()
|
|
54
|
+
messagesChanged()
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
async function loadEvents() {
|
|
58
|
+
if (!live) return
|
|
59
|
+
const res = await fetch(url(`/api/events?page=${encodeURIComponent(page)}`))
|
|
60
|
+
const all: WpEvent[] = (await res.json()).filter((e: WpEvent) => e.page === page)
|
|
61
|
+
// what is still on its way stays: the log doesn't have it yet
|
|
62
|
+
const known = new Set(all.map(e => e.id))
|
|
63
|
+
for (const [id, e] of sending) if (known.has(id)) sending.delete(id)
|
|
64
|
+
setEvents([...all, ...[...sending.values()]])
|
|
65
|
+
scrollFromLog()
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// `workpad scroll` is an event in the log (SCROLL), so a scroll sent while this page wasn't
|
|
69
|
+
// connected still happens once it is. The latest one counts; the first load only notes which that
|
|
70
|
+
// is, so a page loaded later doesn't jump to a place shown before it.
|
|
71
|
+
let scrolledTo: string | null | undefined
|
|
72
|
+
function scrollFromLog() {
|
|
73
|
+
const last = events.findLast(e => e.type === SCROLL && !fromReader(e))
|
|
74
|
+
if (scrolledTo === undefined) return void (scrolledTo = last?.id ?? null)
|
|
75
|
+
if (!last || last.id === scrolledTo) return
|
|
76
|
+
scrolledTo = last.id
|
|
77
|
+
const to = String(last.data?.to ?? '')
|
|
78
|
+
if (!scrollToTarget(root, to)) console.warn(`workpad scroll: nothing on the page matches ${JSON.stringify(to)}`)
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// Appending is optimistic: the event is in the page's events at once, marked `sending`, so the page
|
|
82
|
+
// shows it without waiting; the server's copy replaces it once it is in the log. Its id is made
|
|
83
|
+
// here and the server keeps it, so a send that heard nothing back can be sent again without
|
|
84
|
+
// appending it twice: it is retried, and only when none goes through is it taken out again and the
|
|
85
|
+
// append fails.
|
|
86
|
+
|
|
87
|
+
/** How long one send may take before it is tried again, in ms; and how many tries in all. */
|
|
88
|
+
const SEND_TIMEOUT = 8_000
|
|
89
|
+
const TRIES = 4
|
|
90
|
+
|
|
91
|
+
/** Events appended here that the server hasn't confirmed: kept in the events when they are loaded. */
|
|
92
|
+
const sending = new Map<string, WpEvent>()
|
|
93
|
+
|
|
94
|
+
/** An id as the server makes them (isEventId): the time in base 36, a dash, random hex. */
|
|
95
|
+
const newId = () =>
|
|
96
|
+
`${Date.now().toString(36)}-${[...crypto.getRandomValues(new Uint8Array(6))].map(b => b.toString(16).padStart(2, '0')).join('')}`
|
|
97
|
+
|
|
98
|
+
async function append(
|
|
99
|
+
type: string,
|
|
100
|
+
data: Record<string, unknown> = {},
|
|
101
|
+
action: string | null = null,
|
|
102
|
+
): Promise<WpEvent> {
|
|
103
|
+
if (!live) throw new Error('a built page is a file: there is no log to append to')
|
|
104
|
+
const id = newId()
|
|
105
|
+
const shown: WpEvent = { id, ts: new Date().toISOString(), page, type, action, data, sending: true }
|
|
106
|
+
sending.set(id, shown)
|
|
107
|
+
setEvents([...events, shown])
|
|
108
|
+
const body = JSON.stringify({ id, page, type, action, data })
|
|
109
|
+
let failure: unknown
|
|
110
|
+
for (let attempt = 0; attempt < TRIES; attempt++) {
|
|
111
|
+
if (attempt) await new Promise(r => setTimeout(r, 500 * 2 ** attempt))
|
|
112
|
+
try {
|
|
113
|
+
const res = await fetch(url('/api/events'), {
|
|
114
|
+
method: 'POST',
|
|
115
|
+
headers: { 'content-type': 'application/json' },
|
|
116
|
+
body,
|
|
117
|
+
// never left hanging: a browser holds a request while it has no connection to send it on
|
|
118
|
+
signal: AbortSignal.timeout(SEND_TIMEOUT),
|
|
119
|
+
})
|
|
120
|
+
// refused: sending it again changes nothing
|
|
121
|
+
if (res.status >= 400 && res.status < 500) {
|
|
122
|
+
failure = new Error(await res.text())
|
|
123
|
+
break
|
|
124
|
+
}
|
|
125
|
+
if (!res.ok) throw new Error(await res.text())
|
|
126
|
+
const saved: WpEvent = await res.json()
|
|
127
|
+
sending.delete(id)
|
|
128
|
+
// the server's copy in its place (a load may have brought it already)
|
|
129
|
+
setEvents([...events.filter(e => e.id !== id && e.id !== saved.id), saved].toSorted(byTime))
|
|
130
|
+
return saved
|
|
131
|
+
} catch (err) {
|
|
132
|
+
failure = err
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
// the log has it already (a load brought it), though no answer to a send came back
|
|
136
|
+
const arrived = !sending.has(id) && events.find(e => e.id === id && !e.sending)
|
|
137
|
+
if (arrived) return arrived
|
|
138
|
+
sending.delete(id)
|
|
139
|
+
setEvents(events.filter(e => e.id !== id))
|
|
140
|
+
throw failure
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const byTime = (a: WpEvent, b: WpEvent) => (a.ts < b.ts ? -1 : a.ts > b.ts ? 1 : 0)
|
|
144
|
+
|
|
145
|
+
let listeners: Listener[] = []
|
|
146
|
+
const listenersValue = reactive(() => listeners)
|
|
147
|
+
|
|
148
|
+
async function loadListeners() {
|
|
149
|
+
if (!live) return
|
|
150
|
+
listeners = await (await fetch(url(`/api/listeners?page=${encodeURIComponent(page)}`))).json()
|
|
151
|
+
listenersValue.notify()
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const renderedListeners = new Set<() => void>()
|
|
155
|
+
|
|
156
|
+
// ---- the corner and the title ------------------------------------------------------------------
|
|
157
|
+
|
|
158
|
+
// the server puts it in the page; a page from a server older than this runtime has none
|
|
159
|
+
const corner =
|
|
160
|
+
document.getElementById('wp-dock') ??
|
|
161
|
+
document.body.appendChild(Object.assign(document.createElement('div'), { id: 'wp-dock' }))
|
|
162
|
+
let baseTitle = document.title
|
|
163
|
+
const badges = new Map<string, { text: string; order: number; since: number }>()
|
|
164
|
+
let badgeCount = 0
|
|
165
|
+
function writeTitle() {
|
|
166
|
+
const list = [...badges.values()].toSorted((a, b) => a.order - b.order || a.since - b.since)
|
|
167
|
+
document.title = `${list.map(b => `(${b.text}) `).join('')}${baseTitle}`
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// ---- slots -------------------------------------------------------------------------------------
|
|
171
|
+
|
|
172
|
+
/** The plugins in their order, which is the order of their elements in a slot. */
|
|
173
|
+
const pluginOrder = (handoff.plugins ?? []).map(p => p.name)
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Mount `owner`'s element in a slot (Api.slot): the one the server rendered with its markup, or a
|
|
177
|
+
* new one, put among the others in plugin order. What `mount` returns runs when it is taken away.
|
|
178
|
+
*/
|
|
179
|
+
function slotFor(owner: string, name: SlotName, mount: (el: HTMLElement) => void | (() => void)): () => void {
|
|
180
|
+
const holder =
|
|
181
|
+
name === 'corner'
|
|
182
|
+
? corner
|
|
183
|
+
: name === 'header'
|
|
184
|
+
? root.querySelector<HTMLElement>('[data-wp-slot=header]')
|
|
185
|
+
: document.querySelector<HTMLElement>(`body > [data-wp-slot=${name}]`)
|
|
186
|
+
if (!holder) return () => {}
|
|
187
|
+
let el = [...holder.children].find((c): c is HTMLElement => c instanceof HTMLElement && c.dataset.plugin === owner)
|
|
188
|
+
if (!el) {
|
|
189
|
+
el = document.createElement('div')
|
|
190
|
+
el.dataset.plugin = owner
|
|
191
|
+
const at = pluginOrder.indexOf(owner)
|
|
192
|
+
const next = [...holder.children].find(
|
|
193
|
+
c => c instanceof HTMLElement && c.dataset.plugin != null && pluginOrder.indexOf(c.dataset.plugin) > at,
|
|
194
|
+
)
|
|
195
|
+
holder.insertBefore(el, next ?? null)
|
|
196
|
+
}
|
|
197
|
+
const unmount = mount(el)
|
|
198
|
+
let gone = false
|
|
199
|
+
return () => {
|
|
200
|
+
if (gone) return
|
|
201
|
+
gone = true
|
|
202
|
+
unmount?.()
|
|
203
|
+
el.remove()
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** The page's own element in the corner (its toasts), made the first time it is asked for. */
|
|
208
|
+
let pageCorner: HTMLElement | null = null
|
|
209
|
+
const cornerOfPage = (): HTMLElement => {
|
|
210
|
+
if (!pageCorner) slotFor('', 'corner', el => void (pageCorner = el))
|
|
211
|
+
return pageCorner ?? corner
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
const api: Api = {
|
|
215
|
+
page,
|
|
216
|
+
url,
|
|
217
|
+
events: eventsValue,
|
|
218
|
+
last: type => events.findLast(e => e.type === type),
|
|
219
|
+
marks: {
|
|
220
|
+
received: id => !!events.find(e => e.id === id)?.received,
|
|
221
|
+
handled: id => !!events.find(e => e.id === id)?.handled,
|
|
222
|
+
},
|
|
223
|
+
unread,
|
|
224
|
+
markRead: ids => {
|
|
225
|
+
markRead(ids)
|
|
226
|
+
unread.notify()
|
|
227
|
+
},
|
|
228
|
+
markdown,
|
|
229
|
+
message,
|
|
230
|
+
blocks: text => blocks(page, text),
|
|
231
|
+
append,
|
|
232
|
+
listeners: listenersValue,
|
|
233
|
+
rendered() {
|
|
234
|
+
// the new page is in place: what came with its render is the page's now, before anyone hears
|
|
235
|
+
// of the update, so a listener reads the new values
|
|
236
|
+
const frontmatterChanged = JSON.stringify(nextFrontmatter) !== JSON.stringify(frontmatter)
|
|
237
|
+
data = nextData
|
|
238
|
+
frontmatter = nextFrontmatter
|
|
239
|
+
// a chat taken off the page or put back changes what is unread
|
|
240
|
+
unread.notify()
|
|
241
|
+
for (const fn of renderedListeners) fn()
|
|
242
|
+
dataValue.notify()
|
|
243
|
+
if (frontmatterChanged) frontmatterValue.notify()
|
|
244
|
+
},
|
|
245
|
+
onRendered(fn) {
|
|
246
|
+
renderedListeners.add(fn)
|
|
247
|
+
return () => renderedListeners.delete(fn)
|
|
248
|
+
},
|
|
249
|
+
// the page's own (not a plugin's): before the plugins' in a slot
|
|
250
|
+
slot: (name, mount) => slotFor('', name, mount),
|
|
251
|
+
badge(key, text, order = 0) {
|
|
252
|
+
if (text == null) badges.delete(key)
|
|
253
|
+
else badges.set(key, { text, order, since: badges.get(key)?.since ?? badgeCount++ })
|
|
254
|
+
writeTitle()
|
|
255
|
+
},
|
|
256
|
+
title(title) {
|
|
257
|
+
baseTitle = title
|
|
258
|
+
writeTitle()
|
|
259
|
+
},
|
|
260
|
+
toast: createToast(cornerOfPage),
|
|
261
|
+
...formsApi,
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
// ---- the page ----------------------------------------------------------------------------------
|
|
265
|
+
|
|
266
|
+
const changeListeners = new Set<() => void>()
|
|
267
|
+
|
|
268
|
+
async function getJson<T>(url: string): Promise<T> {
|
|
269
|
+
const res = await fetch(url)
|
|
270
|
+
if (!res.ok) throw new Error(`${url}: ${res.status}`)
|
|
271
|
+
return res.json()
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
// what came with the page, and what came with its last render: the page's once the new page is in
|
|
275
|
+
// place (api.rendered), so a listener never sees new values over the old page
|
|
276
|
+
let data: unknown = handoff.data
|
|
277
|
+
let nextData: unknown = data
|
|
278
|
+
let frontmatter: Record<string, unknown> = handoff.frontmatter ?? {}
|
|
279
|
+
let nextFrontmatter = frontmatter
|
|
280
|
+
const dataValue = reactive(() => data)
|
|
281
|
+
const frontmatterValue = reactive(() => frontmatter)
|
|
282
|
+
const nothing = reactive((): unknown => undefined)
|
|
283
|
+
const handle: PageHandle = {
|
|
284
|
+
settings: nothing,
|
|
285
|
+
id: page,
|
|
286
|
+
kind: handoff.kind,
|
|
287
|
+
live,
|
|
288
|
+
data: dataValue,
|
|
289
|
+
frontmatter: frontmatterValue,
|
|
290
|
+
onChange(fn) {
|
|
291
|
+
changeListeners.add(fn)
|
|
292
|
+
return () => changeListeners.delete(fn)
|
|
293
|
+
},
|
|
294
|
+
render: async () => {
|
|
295
|
+
const next = await getJson<RenderedPage>(url(`/api/render?page=${encodeURIComponent(page)}`))
|
|
296
|
+
nextData = next.data ?? null
|
|
297
|
+
nextFrontmatter = next.frontmatter ?? {}
|
|
298
|
+
return next
|
|
299
|
+
},
|
|
300
|
+
stored: () => getJson<StoredPage>(url(`/api/page?page=${encodeURIComponent(page)}`)),
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/** Did the page change since it was rendered here (its file's time, or it came to be)? Then say so. */
|
|
304
|
+
async function caughtUp() {
|
|
305
|
+
let now: number | null
|
|
306
|
+
try {
|
|
307
|
+
now =
|
|
308
|
+
(await getJson<RenderedPage & { mtime: number | null }>(url(`/api/render?page=${encodeURIComponent(page)}`)))
|
|
309
|
+
.mtime ?? null
|
|
310
|
+
} catch {
|
|
311
|
+
now = null
|
|
312
|
+
}
|
|
313
|
+
const shown = (data as { mtime?: number | null } | null)?.mtime ?? null
|
|
314
|
+
if (now !== shown) for (const fn of changeListeners) fn()
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
// raw text: the server's HTML is the page, replaced when the page changes
|
|
318
|
+
if (!handoff.client)
|
|
319
|
+
handle.onChange(async () => {
|
|
320
|
+
root.innerHTML = (await handle.render()).html
|
|
321
|
+
api.rendered()
|
|
322
|
+
})
|
|
323
|
+
|
|
324
|
+
// ---- live channel ------------------------------------------------------------------------------
|
|
325
|
+
|
|
326
|
+
// A WebSocket, not server-sent events: a browser keeps six HTTP/1.1 connections to an origin, and
|
|
327
|
+
// every workpad tab is on the same one; one stream per tab left none for a form's answer (see
|
|
328
|
+
// src/ws.ts). A WebSocket doesn't reconnect by itself: this does, sooner at first, then every few
|
|
329
|
+
// seconds, and at once when the tab is shown or the network comes back.
|
|
330
|
+
const reloadWhenUp = async () => {
|
|
331
|
+
try {
|
|
332
|
+
if ((await fetch(url('/api/health'), { cache: 'no-store' })).ok) return location.reload()
|
|
333
|
+
} catch {
|
|
334
|
+
/* not up yet */
|
|
335
|
+
}
|
|
336
|
+
setTimeout(reloadWhenUp, 500)
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/** What the server says on the live channel, by its name. */
|
|
340
|
+
const onLive: Record<string, (data: unknown) => void> = {
|
|
341
|
+
change: () => {
|
|
342
|
+
for (const fn of changeListeners) fn()
|
|
343
|
+
},
|
|
344
|
+
events: () => loadEvents(),
|
|
345
|
+
listeners: () => loadListeners(),
|
|
346
|
+
// under a shared server: what waits in another project changed (the page's menu of it listens)
|
|
347
|
+
elsewhere: () => document.dispatchEvent(new Event('wp-elsewhere')),
|
|
348
|
+
// browser code changed; the page keeps what matters across a reload itself. Reload only once
|
|
349
|
+
// the server answers: reloading while it restarts would leave the browser's error page, which
|
|
350
|
+
// has nothing left in it to recover with.
|
|
351
|
+
reload: () => reloadWhenUp(),
|
|
352
|
+
style: () => {
|
|
353
|
+
stamps = null
|
|
354
|
+
for (const link of document.querySelectorAll<HTMLLinkElement>('link[rel=stylesheet]')) {
|
|
355
|
+
const url = new URL(link.href)
|
|
356
|
+
if (url.origin !== location.origin) continue
|
|
357
|
+
url.searchParams.set('t', String(Date.now()))
|
|
358
|
+
link.href = url.pathname + url.search
|
|
359
|
+
}
|
|
360
|
+
},
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
// What the browser runs and how it looks, as this page has them; null once a style message refreshed
|
|
364
|
+
// the stylesheets without a stamp to go with it (the next comparison takes the server's then).
|
|
365
|
+
let stamps: { code: string; style: string } | null = handoff.stamps ?? null
|
|
366
|
+
|
|
367
|
+
/**
|
|
368
|
+
* Back on the live channel: what changed while this page wasn't on it, it never heard of. Browser
|
|
369
|
+
* code that changed reloads the page; stylesheets that changed are refreshed in place.
|
|
370
|
+
*/
|
|
371
|
+
async function compareStamps() {
|
|
372
|
+
let now: { code: string; style: string }
|
|
373
|
+
try {
|
|
374
|
+
now = await (await fetch(url('/api/stamps'), { cache: 'no-store' })).json()
|
|
375
|
+
} catch {
|
|
376
|
+
return
|
|
377
|
+
}
|
|
378
|
+
if (stamps && now.code !== stamps.code) return reloadWhenUp()
|
|
379
|
+
if (stamps && now.style !== stamps.style) onLive.style!(null)
|
|
380
|
+
stamps = now
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
let socket: WebSocket | null = null
|
|
384
|
+
let retries = 0
|
|
385
|
+
let retryTimer: ReturnType<typeof setTimeout> | undefined
|
|
386
|
+
|
|
387
|
+
function connect() {
|
|
388
|
+
clearTimeout(retryTimer)
|
|
389
|
+
if (socket && socket.readyState <= WebSocket.OPEN) return
|
|
390
|
+
const at = new URL(url(`/api/live?page=${encodeURIComponent(page)}${isDir ? '&dir' : ''}`), location.href)
|
|
391
|
+
at.protocol = location.protocol === 'https:' ? 'wss:' : 'ws:'
|
|
392
|
+
const ws = (socket = new WebSocket(at))
|
|
393
|
+
ws.onopen = () => {
|
|
394
|
+
retries = 0
|
|
395
|
+
document.documentElement.dataset.wpLive = ''
|
|
396
|
+
// after a server restart: who is listening now, and what was answered meanwhile, here and
|
|
397
|
+
// elsewhere
|
|
398
|
+
loadListeners()
|
|
399
|
+
loadEvents()
|
|
400
|
+
void compareStamps()
|
|
401
|
+
document.dispatchEvent(new Event('wp-elsewhere'))
|
|
402
|
+
// and the page, if it changed while the channel wasn't open yet (just after loading, or while
|
|
403
|
+
// the server restarted): that change was never announced. Only then: an update that changes
|
|
404
|
+
// nothing still redraws, sorts and scrolls, under the reader's hands
|
|
405
|
+
caughtUp()
|
|
406
|
+
}
|
|
407
|
+
ws.onmessage = e => {
|
|
408
|
+
let message: { event?: string; data?: unknown }
|
|
409
|
+
try {
|
|
410
|
+
message = JSON.parse(String(e.data))
|
|
411
|
+
} catch {
|
|
412
|
+
return
|
|
413
|
+
}
|
|
414
|
+
if (message.event) onLive[message.event]?.(message.data)
|
|
415
|
+
}
|
|
416
|
+
ws.onclose = () => {
|
|
417
|
+
if (socket !== ws) return
|
|
418
|
+
socket = null
|
|
419
|
+
delete document.documentElement.dataset.wpLive
|
|
420
|
+
retryTimer = setTimeout(connect, Math.min(250 * 2 ** retries++, 5000))
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
// back at once: a tab shown again (a browser may have let its connection go), the network back
|
|
424
|
+
document.addEventListener('visibilitychange', () => {
|
|
425
|
+
if (document.visibilityState === 'visible' && !socket) connect()
|
|
426
|
+
})
|
|
427
|
+
addEventListener('online', () => {
|
|
428
|
+
if (!socket) connect()
|
|
429
|
+
})
|
|
430
|
+
|
|
431
|
+
await Promise.all([loadEvents(), loadListeners()])
|
|
432
|
+
if (handoff.client) {
|
|
433
|
+
try {
|
|
434
|
+
const mount: PluginMount = (await import(moduleUrl(handoff.client))).default
|
|
435
|
+
await mount(root, handle, api)
|
|
436
|
+
} catch (err) {
|
|
437
|
+
console.error('page:', err)
|
|
438
|
+
root.insertAdjacentHTML(
|
|
439
|
+
'afterbegin',
|
|
440
|
+
String(html`<pre class="wp-error" role="alert">the page failed to start: ${(err as Error).message}</pre>`),
|
|
441
|
+
)
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
// named forms, once the page is on the page, and what the reader read: neither on a built page
|
|
445
|
+
if (live) {
|
|
446
|
+
trackForms(root, page, api)
|
|
447
|
+
trackReading({
|
|
448
|
+
messages: handoff.messages ?? [],
|
|
449
|
+
events: () => events,
|
|
450
|
+
send: ids => {
|
|
451
|
+
append(READ, { ids }).catch(err => console.error('marking read:', err))
|
|
452
|
+
},
|
|
453
|
+
})
|
|
454
|
+
}
|
|
455
|
+
// a link to a place on the page (`<page>#<form name>`): there once the page is in place, and again
|
|
456
|
+
// when the hash changes
|
|
457
|
+
scrollToAnchor(root)
|
|
458
|
+
addEventListener('hashchange', () => scrollToAnchor(root))
|
|
459
|
+
/**
|
|
460
|
+
* A plugin's page handle: the page's, with its own settings, the page's frontmatter under `plugins:`
|
|
461
|
+
* by its name, heard of only when they changed.
|
|
462
|
+
*/
|
|
463
|
+
function handleFor(name: string): PageHandle {
|
|
464
|
+
const own = () => {
|
|
465
|
+
const plugins = frontmatter.plugins
|
|
466
|
+
return plugins && typeof plugins === 'object' ? (plugins as Record<string, unknown>)[name] : undefined
|
|
467
|
+
}
|
|
468
|
+
const settings = reactive(own)
|
|
469
|
+
let last = JSON.stringify(own() ?? null)
|
|
470
|
+
frontmatterValue.on(() => {
|
|
471
|
+
const now = JSON.stringify(own() ?? null)
|
|
472
|
+
if (now === last) return
|
|
473
|
+
last = now
|
|
474
|
+
settings.notify()
|
|
475
|
+
})
|
|
476
|
+
return { ...handle, settings }
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
// the plugins' modules after the page, so that what they work on is there; one failing leaves the others
|
|
480
|
+
await Promise.all(
|
|
481
|
+
(handoff.plugins ?? []).map(async ext => {
|
|
482
|
+
try {
|
|
483
|
+
const mount: PluginMount = (await import(moduleUrl(ext.client))).default
|
|
484
|
+
if (typeof mount !== 'function')
|
|
485
|
+
throw new Error('the client module must export a mount(root, page, api) function as default')
|
|
486
|
+
await mount(root, handleFor(ext.name), { ...api, slot: (name, mount) => slotFor(ext.name, name, mount) })
|
|
487
|
+
} catch (err) {
|
|
488
|
+
console.error(`plugin ${ext.name}:`, err)
|
|
489
|
+
root.insertAdjacentHTML(
|
|
490
|
+
'afterbegin',
|
|
491
|
+
String(
|
|
492
|
+
html`<pre class="wp-error" role="alert">
|
|
493
|
+
plugin "${ext.name}" failed in the browser: ${(err as Error).message}</pre>`,
|
|
494
|
+
),
|
|
495
|
+
)
|
|
496
|
+
}
|
|
497
|
+
}),
|
|
498
|
+
)
|
|
499
|
+
if (live) connect()
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
// An agent shows the reader a place on the page (`workpad scroll <page> <where>`): the live
|
|
2
|
+
// channel says where, and the page goes there. `where` is, in this order: a heading whose text it
|
|
3
|
+
// is (or, failing that, contains), a form of that name, an element with that id, or the first text
|
|
4
|
+
// that contains it. A <details> around it opens; it is scrolled to just below the header and the
|
|
5
|
+
// titles of open details that stick above it, and lit up a moment, so the eye finds it.
|
|
6
|
+
//
|
|
7
|
+
// A link does the same with its hash: `<page>#<id>` opens the page at the element with that id
|
|
8
|
+
// (src/anchors.ts: a heading by its slug, `#form:logger`, `#chat:notes`, `#tab:intro`,
|
|
9
|
+
// `#details:…`, `#message:<id>`), and what hides it shows it (wp-reveal: a step not showing, a
|
|
10
|
+
// closed details). Something drawn after the page (a chat's messages) is waited for a moment. The
|
|
11
|
+
// page's own hashes (`#wp-waiting`) are left to theirs.
|
|
12
|
+
|
|
13
|
+
const norm = (s: string) => s.replace(/\s+/g, ' ').trim().toLowerCase()
|
|
14
|
+
|
|
15
|
+
export function findTarget(root: ParentNode, where: string): HTMLElement | null {
|
|
16
|
+
// an anchor, as a link would name it (`form:logger`)
|
|
17
|
+
const exact = document.getElementById(where.trim())
|
|
18
|
+
if (exact && root.contains(exact)) return exact
|
|
19
|
+
const want = norm(where)
|
|
20
|
+
const headings = [...root.querySelectorAll<HTMLElement>('h1, h2, h3, h4, h5, h6, summary')]
|
|
21
|
+
const heading =
|
|
22
|
+
headings.find(h => norm(h.textContent ?? '') === want) ??
|
|
23
|
+
headings.find(h => norm(h.textContent ?? '').includes(want))
|
|
24
|
+
if (heading) return heading
|
|
25
|
+
const byName = [...root.querySelectorAll<HTMLElement>('form[name]')].find(
|
|
26
|
+
f => f.getAttribute('name') === where.trim(),
|
|
27
|
+
)
|
|
28
|
+
if (byName) return byName
|
|
29
|
+
const walker = document.createTreeWalker(root as Node, NodeFilter.SHOW_TEXT)
|
|
30
|
+
for (let n = walker.nextNode(); n; n = walker.nextNode()) {
|
|
31
|
+
if (norm(n.textContent ?? '').includes(want) && n.parentElement && !n.parentElement.closest('script, style'))
|
|
32
|
+
return n.parentElement
|
|
33
|
+
}
|
|
34
|
+
return null
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** How long a link's target is waited for when the page doesn't have it yet (a chat's messages, drawn after it). */
|
|
38
|
+
const LATE = 3000
|
|
39
|
+
|
|
40
|
+
/** Go to the element the location's hash names (src/anchors.ts), now or once it is drawn. */
|
|
41
|
+
export function scrollToAnchor(root: ParentNode) {
|
|
42
|
+
let id: string
|
|
43
|
+
try {
|
|
44
|
+
id = decodeURIComponent(location.hash.slice(1))
|
|
45
|
+
} catch {
|
|
46
|
+
return
|
|
47
|
+
}
|
|
48
|
+
if (!id.trim() || id.startsWith('wp-')) return
|
|
49
|
+
const find = () => {
|
|
50
|
+
const el = document.getElementById(id)
|
|
51
|
+
return el && root.contains(el) ? el : null
|
|
52
|
+
}
|
|
53
|
+
if (goTo(find())) return
|
|
54
|
+
const seen = new MutationObserver(() => {
|
|
55
|
+
if (goTo(find())) seen.disconnect()
|
|
56
|
+
})
|
|
57
|
+
seen.observe(root as Node, { childList: true, subtree: true })
|
|
58
|
+
setTimeout(() => seen.disconnect(), LATE)
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function scrollToTarget(root: ParentNode, where: string): boolean {
|
|
62
|
+
return goTo(findTarget(root, where))
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function goTo(target: HTMLElement | null): boolean {
|
|
66
|
+
if (!target) return false
|
|
67
|
+
// what hides it shows it (a step not showing): told by an event from it, which bubbles
|
|
68
|
+
target.dispatchEvent(new CustomEvent('wp-reveal', { bubbles: true }))
|
|
69
|
+
// a <details> around it opens (a summary's own details stays as it is)
|
|
70
|
+
for (
|
|
71
|
+
let d = (target.tagName === 'SUMMARY' ? target.parentElement?.parentElement : target)?.closest('details');
|
|
72
|
+
d;
|
|
73
|
+
d = d.parentElement?.closest('details')
|
|
74
|
+
)
|
|
75
|
+
d.open = true
|
|
76
|
+
requestAnimationFrame(() => {
|
|
77
|
+
// below the header, and below the titles of the open details around it, which stick
|
|
78
|
+
let offset = (document.querySelector<HTMLElement>('.wp-nav')?.getBoundingClientRect().height ?? 0) + 12
|
|
79
|
+
for (let d = target.parentElement?.closest('details'); d; d = d.parentElement?.closest('details')) {
|
|
80
|
+
const summary = d.querySelector<HTMLElement>(':scope > summary')
|
|
81
|
+
if (summary && summary !== target) offset += summary.getBoundingClientRect().height
|
|
82
|
+
}
|
|
83
|
+
scrollTo({ top: Math.max(0, scrollY + target.getBoundingClientRect().top - offset), behavior: 'smooth' })
|
|
84
|
+
target.classList.remove('wp-flash')
|
|
85
|
+
void target.offsetWidth
|
|
86
|
+
target.classList.add('wp-flash')
|
|
87
|
+
setTimeout(() => target.classList.remove('wp-flash'), 2000)
|
|
88
|
+
})
|
|
89
|
+
return true
|
|
90
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
// Toasts (api.toast): short labels in the page's corner (its element in the corner slot, above what covers the bottom
|
|
2
|
+
// of the window) that say what is going on and take the reader there: "→ unanswered (2)",
|
|
3
|
+
// "↓ new (3)", "Sent, but no agent is listening". One goes after a few seconds, or on a click; one
|
|
4
|
+
// with `ms: 0` stays until closed, and changes its text, or hides and shows again, through what
|
|
5
|
+
// toast() returns. A click runs `onClick` (and closes a toast that goes by itself); `onDismiss`
|
|
6
|
+
// adds a ✕ that runs it and closes the toast. A toast stays short: what more there is to say goes in
|
|
7
|
+
// `details`, which a ▸ unfolds under it; unfolded, it doesn't go by itself until folded again. Their look is the core's (server.ts), in the page's
|
|
8
|
+
// theme colours.
|
|
9
|
+
import type { Toast, ToastOptions } from '../define.ts'
|
|
10
|
+
|
|
11
|
+
let box: HTMLElement | null = null
|
|
12
|
+
function place(corner: HTMLElement) {
|
|
13
|
+
if (box?.isConnected) return box
|
|
14
|
+
box = document.createElement('div')
|
|
15
|
+
box.className = 'wp-toasts'
|
|
16
|
+
box.setAttribute('role', 'status')
|
|
17
|
+
box.setAttribute('aria-live', 'polite')
|
|
18
|
+
corner.append(box)
|
|
19
|
+
return box
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function createToast(corner: () => HTMLElement) {
|
|
23
|
+
return function toast(
|
|
24
|
+
text: string,
|
|
25
|
+
{ kind = 'info', ms = 7000, onClick, onDismiss, name, order = 0, details }: ToastOptions = {},
|
|
26
|
+
): Toast {
|
|
27
|
+
const el = document.createElement('button')
|
|
28
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
29
|
+
const close = () => {
|
|
30
|
+
clearTimeout(timer)
|
|
31
|
+
el.remove()
|
|
32
|
+
}
|
|
33
|
+
el.type = 'button'
|
|
34
|
+
el.className = 'wp-toast'
|
|
35
|
+
el.dataset.kind = kind
|
|
36
|
+
if (name) el.dataset.toast = name
|
|
37
|
+
el.style.order = String(order)
|
|
38
|
+
const label = document.createElement('span')
|
|
39
|
+
label.className = 'wp-toast-text'
|
|
40
|
+
label.textContent = text
|
|
41
|
+
el.append(label)
|
|
42
|
+
let more: HTMLElement | null = null
|
|
43
|
+
let detail: HTMLElement | null = null
|
|
44
|
+
if (details) {
|
|
45
|
+
more = document.createElement('span')
|
|
46
|
+
more.className = 'wp-toast-more'
|
|
47
|
+
detail = document.createElement('span')
|
|
48
|
+
detail.className = 'wp-toast-details'
|
|
49
|
+
detail.textContent = details
|
|
50
|
+
// read out with the toast, folded or not
|
|
51
|
+
el.setAttribute('aria-description', details)
|
|
52
|
+
el.append(more, detail)
|
|
53
|
+
fold(false)
|
|
54
|
+
}
|
|
55
|
+
function fold(open: boolean) {
|
|
56
|
+
el.toggleAttribute('data-open', open)
|
|
57
|
+
detail!.hidden = !open
|
|
58
|
+
more!.textContent = open ? '▾' : '▸'
|
|
59
|
+
more!.title = open ? 'Less' : 'More'
|
|
60
|
+
// being read: it stays; folded again, it goes as it would have
|
|
61
|
+
clearTimeout(timer)
|
|
62
|
+
if (!open && ms) timer = setTimeout(close, ms)
|
|
63
|
+
}
|
|
64
|
+
if (onDismiss) {
|
|
65
|
+
const x = document.createElement('span')
|
|
66
|
+
x.className = 'wp-toast-dismiss'
|
|
67
|
+
x.textContent = '✕'
|
|
68
|
+
x.title = x.ariaLabel = 'Dismiss'
|
|
69
|
+
el.append(x)
|
|
70
|
+
}
|
|
71
|
+
el.addEventListener('click', e => {
|
|
72
|
+
const target = e.target as HTMLElement
|
|
73
|
+
if (onDismiss && target.closest('.wp-toast-dismiss')) {
|
|
74
|
+
close()
|
|
75
|
+
onDismiss()
|
|
76
|
+
return
|
|
77
|
+
}
|
|
78
|
+
// the ▸, or the details themselves: fold or unfold, nothing else
|
|
79
|
+
if (details && target.closest('.wp-toast-more, .wp-toast-details')) return fold(!el.hasAttribute('data-open'))
|
|
80
|
+
if (ms) close()
|
|
81
|
+
onClick?.()
|
|
82
|
+
})
|
|
83
|
+
if (ms && !details) timer = setTimeout(close, ms)
|
|
84
|
+
place(corner()).append(el)
|
|
85
|
+
return {
|
|
86
|
+
close,
|
|
87
|
+
update: next => {
|
|
88
|
+
label.textContent = next
|
|
89
|
+
},
|
|
90
|
+
hide: () => {
|
|
91
|
+
el.hidden = true
|
|
92
|
+
},
|
|
93
|
+
show: () => {
|
|
94
|
+
if (!el.isConnected) place(corner()).append(el)
|
|
95
|
+
el.hidden = false
|
|
96
|
+
},
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|