@bigmistqke/whiteboard 0.3.1 → 0.5.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 (174) hide show
  1. package/README.md +119 -18
  2. package/bin/whiteboard.ts +300 -71
  3. package/dist/bin/whiteboard.js +21 -0
  4. package/dist/client/runtime.js +132 -54
  5. package/dist/define.js +21 -2
  6. package/dist/plugins/callout/index.js +3 -1
  7. package/dist/plugins/callout/public/style.css +30 -0
  8. package/dist/plugins/chat/index.js +7 -4
  9. package/dist/plugins/chat/{client.js → public/client.js} +1 -1
  10. package/dist/plugins/chat/public/style.css +98 -0
  11. package/dist/plugins/code/index.js +3 -1
  12. package/dist/plugins/code/public/style.css +68 -0
  13. package/dist/plugins/comments/index.js +4 -5
  14. package/dist/plugins/comments/public/client.js +19 -0
  15. package/dist/plugins/comments/public/style.css +185 -0
  16. package/dist/plugins/details/index.js +7 -2
  17. package/dist/plugins/details/public/style.css +7 -0
  18. package/dist/plugins/draft/README.md +14 -0
  19. package/dist/plugins/draft/index.js +21 -0
  20. package/dist/plugins/draft/public/style.css +21 -0
  21. package/dist/plugins/form/index.js +37 -8
  22. package/dist/plugins/form/public/style.css +126 -0
  23. package/dist/plugins/gallery/index.js +4 -3
  24. package/dist/plugins/gallery/public/client.js +1 -0
  25. package/dist/plugins/gallery/public/style.css +90 -0
  26. package/dist/plugins/grid/index.js +9 -3
  27. package/dist/plugins/grid/public/style.css +71 -0
  28. package/dist/plugins/iframe/index.js +13 -14
  29. package/dist/plugins/iframe/public/style.css +13 -0
  30. package/dist/plugins/index.js +7 -1
  31. package/dist/plugins/mermaid/index.js +3 -1
  32. package/dist/plugins/mermaid/{style.css → public/style.css} +7 -2
  33. package/dist/plugins/steps/README.md +42 -0
  34. package/dist/plugins/steps/index.js +99 -0
  35. package/dist/plugins/steps/public/client.js +1 -0
  36. package/dist/plugins/steps/public/style.css +77 -0
  37. package/dist/plugins/terminal/host.js +9 -3
  38. package/dist/plugins/terminal/index.js +10 -9
  39. package/dist/plugins/terminal/{style.css → public/style.css} +199 -45
  40. package/dist/plugins/terminal/sizes.js +2 -1
  41. package/dist/plugins/toc/README.md +21 -3
  42. package/dist/plugins/toc/index.js +12 -5
  43. package/dist/plugins/toc/public/client.js +1 -0
  44. package/dist/plugins/toc/public/style.css +99 -0
  45. package/dist/plugins/window/README.md +29 -0
  46. package/dist/plugins/window/index.js +64 -0
  47. package/dist/solid/index.js +14 -11
  48. package/dist/src/auth.js +2 -1
  49. package/dist/src/client/page/base.css +1078 -199
  50. package/dist/src/client/page/main.js +188 -39
  51. package/dist/src/loader.js +14 -3
  52. package/dist/src/package.js +3 -6
  53. package/dist/src/pages/blocks.js +8 -13
  54. package/dist/src/pages/markdown.js +1 -1
  55. package/dist/src/pages/render.js +106 -20
  56. package/dist/src/pages/window.js +31 -0
  57. package/dist/src/public.js +24 -0
  58. package/dist/src/server.js +251 -23
  59. package/package.json +5 -2
  60. package/plugins/callout/index.ts +3 -1
  61. package/plugins/callout/public/style.css +30 -0
  62. package/plugins/chat/autosize.ts +43 -9
  63. package/plugins/chat/client.tsx +22 -5
  64. package/plugins/chat/index.ts +22 -8
  65. package/plugins/chat/public/style.css +98 -0
  66. package/plugins/claude-code/index.ts +49 -14
  67. package/plugins/code/diff.ts +28 -8
  68. package/plugins/code/index.ts +33 -21
  69. package/plugins/code/public/style.css +68 -0
  70. package/plugins/comments/client.ts +139 -71
  71. package/plugins/comments/index.ts +9 -7
  72. package/plugins/comments/public/style.css +185 -0
  73. package/plugins/details/index.ts +7 -2
  74. package/plugins/details/public/style.css +7 -0
  75. package/plugins/draft/README.md +14 -0
  76. package/plugins/draft/index.ts +23 -0
  77. package/plugins/draft/public/style.css +21 -0
  78. package/plugins/forge/index.ts +16 -3
  79. package/plugins/form/index.ts +75 -27
  80. package/plugins/form/public/style.css +126 -0
  81. package/plugins/gallery/client.tsx +9 -3
  82. package/plugins/gallery/index.ts +31 -9
  83. package/plugins/gallery/public/style.css +90 -0
  84. package/plugins/grid/index.ts +19 -5
  85. package/plugins/grid/public/style.css +71 -0
  86. package/plugins/iframe/index.ts +20 -23
  87. package/plugins/iframe/public/style.css +13 -0
  88. package/plugins/index.ts +20 -1
  89. package/plugins/mermaid/index.ts +7 -3
  90. package/plugins/mermaid/{style.css → public/style.css} +7 -2
  91. package/plugins/steps/README.md +42 -0
  92. package/plugins/steps/client.ts +66 -0
  93. package/plugins/steps/index.ts +127 -0
  94. package/plugins/steps/public/style.css +77 -0
  95. package/plugins/terminal/client.ts +105 -48
  96. package/plugins/terminal/host.ts +143 -35
  97. package/plugins/terminal/index.ts +84 -25
  98. package/plugins/terminal/public/style.css +225 -0
  99. package/plugins/terminal/server.ts +64 -13
  100. package/plugins/terminal/sizes.ts +16 -4
  101. package/plugins/toc/README.md +21 -3
  102. package/plugins/toc/client.ts +90 -30
  103. package/plugins/toc/index.ts +26 -10
  104. package/plugins/toc/public/style.css +99 -0
  105. package/plugins/window/README.md +29 -0
  106. package/plugins/window/index.ts +85 -0
  107. package/skills/whiteboard/SKILL.md +3 -1
  108. package/solid/index.tsx +24 -9
  109. package/src/auth.ts +28 -9
  110. package/src/client/forms.ts +74 -28
  111. package/src/client/markdown.ts +15 -4
  112. package/src/client/page/base.css +1078 -199
  113. package/src/client/page/elsewhere.ts +32 -15
  114. package/src/client/page/fresh.ts +91 -23
  115. package/src/client/page/hold.ts +11 -2
  116. package/src/client/page/live.ts +10 -6
  117. package/src/client/page/main.ts +124 -42
  118. package/src/client/page/orphans.ts +25 -10
  119. package/src/client/page/sort.ts +14 -4
  120. package/src/client/page/sticky.ts +11 -3
  121. package/src/client/page/theme.ts +11 -7
  122. package/src/client/page/waiting.ts +141 -34
  123. package/src/client/page/window.ts +40 -0
  124. package/src/client/reactive.ts +19 -0
  125. package/src/client/read.ts +17 -10
  126. package/src/client/runtime.ts +170 -40
  127. package/src/client/scroll.ts +14 -4
  128. package/src/client/toast.ts +19 -5
  129. package/src/config.ts +20 -5
  130. package/src/define.ts +119 -31
  131. package/src/events.ts +111 -24
  132. package/src/html.ts +6 -2
  133. package/src/icons.ts +4 -2
  134. package/src/load.ts +10 -2
  135. package/src/loader.ts +81 -12
  136. package/src/package.ts +9 -8
  137. package/src/pages/blocks.ts +20 -14
  138. package/src/pages/index.ts +2 -2
  139. package/src/pages/markdown.ts +113 -34
  140. package/src/pages/render.ts +233 -41
  141. package/src/pages/window.ts +78 -0
  142. package/src/plugins.ts +90 -24
  143. package/src/public.ts +39 -0
  144. package/src/running.ts +8 -2
  145. package/src/serve.ts +29 -7
  146. package/src/server.ts +591 -110
  147. package/src/status.ts +15 -9
  148. package/dist/plugins/callout/style.css +0 -12
  149. package/dist/plugins/chat/style.css +0 -24
  150. package/dist/plugins/code/style.css +0 -29
  151. package/dist/plugins/comments/client.js +0 -10
  152. package/dist/plugins/comments/style.css +0 -40
  153. package/dist/plugins/details/style.css +0 -3
  154. package/dist/plugins/form/style.css +0 -44
  155. package/dist/plugins/gallery/client.js +0 -1
  156. package/dist/plugins/gallery/style.css +0 -27
  157. package/dist/plugins/grid/style.css +0 -25
  158. package/dist/plugins/iframe/client.js +0 -1
  159. package/dist/plugins/iframe/style.css +0 -29
  160. package/dist/plugins/toc/client.js +0 -1
  161. package/dist/plugins/toc/style.css +0 -19
  162. package/plugins/callout/style.css +0 -12
  163. package/plugins/chat/style.css +0 -24
  164. package/plugins/code/style.css +0 -29
  165. package/plugins/comments/style.css +0 -40
  166. package/plugins/details/style.css +0 -3
  167. package/plugins/form/style.css +0 -44
  168. package/plugins/gallery/style.css +0 -27
  169. package/plugins/grid/style.css +0 -25
  170. package/plugins/iframe/client.ts +0 -46
  171. package/plugins/iframe/style.css +0 -29
  172. package/plugins/terminal/style.css +0 -71
  173. package/plugins/toc/style.css +0 -19
  174. /package/dist/plugins/terminal/{client.js → public/client.js} +0 -0
@@ -14,16 +14,41 @@ import type { ResolvedBlock, ResolvedBlocks } from './blocks.ts'
14
14
 
15
15
  type PagesPage = Extract<StoredPage, { kind: 'pages' }>
16
16
  type FolderPage = Extract<StoredPage, { kind: 'folder' }>
17
- interface Content { html: string | Html; title?: string | null; islands: Record<string, Island>; styles: string[] }
17
+ interface Content {
18
+ html: string | Html
19
+ title?: string | null
20
+ islands: Record<string, Island>
21
+ styles: string[]
22
+ }
18
23
 
19
24
  const BASE_CSS = new URL('../client/page/base.css', import.meta.url)
20
25
 
21
26
  // before the stylesheets, so the page never flashes the wrong theme. A plain string, not part of an
22
27
  // `html` template: the bundler writes `</script` in strings as `<\/script`, which in a tagged
23
28
  // template would change the raw text the tag gets, so it rewrites the template into a helper call
24
- const THEME_SCRIPT = raw(`<script>try{const t=localStorage.getItem('wb-theme');if(t==='light'||t==='dark')document.documentElement.dataset.theme=t}catch{}</script>`)
29
+ const THEME_SCRIPT = raw(
30
+ `<script>try{const t=localStorage.getItem('wb-theme');if(t==='light'||t==='dark')document.documentElement.dataset.theme=t}catch{}</script>`,
31
+ )
25
32
 
26
- const CODE_LANG: Record<string, string> = { js: 'javascript', mjs: 'javascript', cjs: 'javascript', ts: 'typescript', tsx: 'tsx', jsx: 'jsx', json: 'json', css: 'css', html: 'html', sh: 'bash', zsh: 'bash', py: 'python', rs: 'rust', go: 'go', toml: 'toml', yml: 'yaml', yaml: 'yaml' }
33
+ const CODE_LANG: Record<string, string> = {
34
+ js: 'javascript',
35
+ mjs: 'javascript',
36
+ cjs: 'javascript',
37
+ ts: 'typescript',
38
+ tsx: 'tsx',
39
+ jsx: 'jsx',
40
+ json: 'json',
41
+ css: 'css',
42
+ html: 'html',
43
+ sh: 'bash',
44
+ zsh: 'bash',
45
+ py: 'python',
46
+ rs: 'rust',
47
+ go: 'go',
48
+ toml: 'toml',
49
+ yml: 'yaml',
50
+ yaml: 'yaml',
51
+ }
27
52
 
28
53
  /** Frontmatter is the core's; the page starts after it. */
29
54
  const body = (source: string) => source.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n/, '')
@@ -33,20 +58,41 @@ export function titleOf(file: string, fallback: string) {
33
58
  try {
34
59
  const h1 = /^#\s+(.+)$/m.exec(body(fs.readFileSync(file, 'utf8')))
35
60
  return h1 ? h1[1].replace(/[*_`]/g, '') : fallback
36
- } catch { return fallback }
61
+ } catch {
62
+ return fallback
63
+ }
37
64
  }
38
65
 
39
66
  function crumbs(id: string, name: string) {
40
67
  const parts = id ? id.split('/') : []
41
- return html`<a href="/">${name}</a>${parts.map((p, i) => html` / <a href="/${parts.slice(0, i + 1).join('/')}">${p}</a>`)}`
68
+ return html`<a href="/">${name}</a
69
+ >${parts.map((p, i) => html` / <a href="/${parts.slice(0, i + 1).join('/')}">${p}</a>`)}`
42
70
  }
43
71
 
44
72
  const time = (ts: number) => html`<time data-ts="${ts}"></time>`
45
73
 
46
74
  function pageList(pages: PagesPage['pages']) {
47
- return html`<ul class="wb-index">${pages.map(p => html`<li><a href="/${p.id}">${titleOf(p.file, path.basename(p.id))}</a>${
48
- p.awaiting > 0 && html` <a class="wb-awaiting" href="/${p.id}#wb-waiting" title="${awaitingLabel(p.awaiting)}" aria-label="${awaitingLabel(p.awaiting)}">${raw(INBOX_ICON)}${p.awaiting}</a>`} <span class="wb-meta"><code>${p.id}</code> · edited ${time(p.mtime)}${
49
- p.lastEvent && html` · last submit ${time(Date.parse(p.lastEvent))}`}</span></li>`)}</ul>`
75
+ return html`<ul class="wb-index">
76
+ ${pages.map(
77
+ p =>
78
+ html`<li>
79
+ <a href="/${p.id}">${titleOf(p.file, path.basename(p.id))}</a>${
80
+ p.awaiting > 0 &&
81
+ html` <a
82
+ class="wb-awaiting"
83
+ href="/${p.id}#wb-waiting"
84
+ title="${awaitingLabel(p.awaiting)}"
85
+ aria-label="${awaitingLabel(p.awaiting)}"
86
+ >${raw(INBOX_ICON)}${p.awaiting}</a
87
+ >`
88
+ }
89
+ <span class="wb-meta"
90
+ ><code>${p.id}</code> · edited
91
+ ${time(p.mtime)}${p.lastEvent && html` · last submit ${time(Date.parse(p.lastEvent))}`}</span
92
+ >
93
+ </li>`,
94
+ )}
95
+ </ul>`
50
96
  }
51
97
 
52
98
  /** The folder's README, when it has one. */
@@ -78,22 +124,32 @@ const MARKDOWN = /\.(md|markdown)$/i
78
124
  function documentsIn(dir: string) {
79
125
  let files: string[]
80
126
  try {
81
- files = execFileSync('git', ['ls-files', '--cached', '--others', '--exclude-standard', '--', ':(icase)*.md', ':(icase)*.markdown'], { cwd: dir, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] })
82
- .split('\n').filter(f => f && !f.startsWith('.whiteboard/') && fs.existsSync(path.join(dir, f)))
127
+ files = execFileSync(
128
+ 'git',
129
+ ['ls-files', '--cached', '--others', '--exclude-standard', '--', ':(icase)*.md', ':(icase)*.markdown'],
130
+ { cwd: dir, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] },
131
+ )
132
+ .split('\n')
133
+ .filter(f => f && !f.startsWith('.whiteboard/') && fs.existsSync(path.join(dir, f)))
83
134
  } catch {
84
135
  files = []
85
136
  const walk = (rel: string) => {
86
137
  let entries: fs.Dirent[] = []
87
- try { entries = fs.readdirSync(path.join(dir, rel), { withFileTypes: true }) } catch { return }
138
+ try {
139
+ entries = fs.readdirSync(path.join(dir, rel), { withFileTypes: true })
140
+ } catch {
141
+ return
142
+ }
88
143
  for (const e of entries) {
89
- if (e.isDirectory()) { if (!SKIP.has(e.name) && !e.name.startsWith('.')) walk(path.posix.join(rel, e.name)) }
90
- else if (MARKDOWN.test(e.name)) files.push(path.posix.join(rel, e.name))
144
+ if (e.isDirectory()) {
145
+ if (!SKIP.has(e.name) && !e.name.startsWith('.')) walk(path.posix.join(rel, e.name))
146
+ } else if (MARKDOWN.test(e.name)) files.push(path.posix.join(rel, e.name))
91
147
  }
92
148
  }
93
149
  walk('')
94
150
  }
95
151
  const depth = (f: string) => f.split('/').length
96
- return [...new Set(files)].sort((a, b) => depth(a) - depth(b) || a.localeCompare(b))
152
+ return [...new Set(files)].toSorted((a, b) => depth(a) - depth(b) || a.localeCompare(b))
97
153
  }
98
154
 
99
155
  /**
@@ -111,11 +167,35 @@ function documentList(ctx: RenderContext) {
111
167
  const title = titleOf(abs, name)
112
168
  const where = title === name ? path.posix.dirname(f) : f
113
169
  let mtime = 0
114
- try { mtime = fs.statSync(abs).mtimeMs } catch { /* gone meanwhile */ }
115
- return html`<li data-order="${i}" data-updated="${mtime}" data-title="${title.toLowerCase()}"><a href="${ctx.urlFor(abs) ?? `/-/${f}`}">${title}</a> <span class="wb-meta">${where !== '.' && html`<code>${where === f ? f : `${where}/`}</code> · `}edited ${time(mtime)}</span></li>`
170
+ try {
171
+ mtime = fs.statSync(abs).mtimeMs
172
+ } catch {
173
+ /* gone meanwhile */
174
+ }
175
+ return html`<li data-order="${i}" data-updated="${mtime}" data-title="${title.toLowerCase()}">
176
+ <a href="${ctx.urlFor(abs) ?? `/-/${f}`}">${title}</a>
177
+ <span class="wb-meta"
178
+ >${where !== '.' && html`<code>${where === f ? f : `${where}/`}</code> · `}edited ${time(mtime)}</span
179
+ >
180
+ </li>`
116
181
  })
117
182
  // in a section, so the heading isn't numbered like the page's own sections
118
- return html`<section class="wb-documents"><div class="wb-list-head"><h2>Documents</h2><label class="wb-sort">sort <select data-wb-sort="documents" aria-label="Sort the documents"><option value="order">by folder</option><option value="updated">last updated</option><option value="title">by title</option></select></label></div><ul class="wb-index">${rows}</ul></section>`
183
+ return html`<section class="wb-documents">
184
+ <div class="wb-list-head">
185
+ <h2>Documents</h2>
186
+ <label class="wb-sort"
187
+ >sort
188
+ <select data-wb-sort="documents" aria-label="Sort the documents">
189
+ <option value="order">by folder</option>
190
+ <option value="updated">last updated</option>
191
+ <option value="title">by title</option>
192
+ </select></label
193
+ >
194
+ </div>
195
+ <ul class="wb-index">
196
+ ${rows}
197
+ </ul>
198
+ </section>`
119
199
  }
120
200
 
121
201
  /** The plugins' text links for a project folder, asked once per folder. */
@@ -124,7 +204,14 @@ function textLinksOf(links: ((ctx: { dir: string }) => TextLink[])[]) {
124
204
  return (dir: string) => {
125
205
  let got = linksFor.get(dir)
126
206
  if (!got) {
127
- got = links.flatMap(fn => { try { return fn({ dir }) } catch (err) { console.error('links:', err); return [] } })
207
+ got = links.flatMap(fn => {
208
+ try {
209
+ return fn({ dir })
210
+ } catch (err) {
211
+ console.error('links:', err)
212
+ return []
213
+ }
214
+ })
128
215
  linksFor.set(dir, got)
129
216
  }
130
217
  return got
@@ -135,21 +222,62 @@ function textLinksOf(links: ((ctx: { dir: string }) => TextLink[])[]) {
135
222
  * A message (a comment, a chat message) as HTML: markdown as on a page, but its raw HTML as text and
136
223
  * its directives as written. Code fences go to the code block, so `styles` are what it needs linked.
137
224
  */
138
- export function createMessageRender(blocks: () => ResolvedBlocks, links: ((ctx: { dir: string }) => TextLink[])[] = []) {
225
+ export function createMessageRender(
226
+ blocks: () => ResolvedBlocks,
227
+ links: ((ctx: { dir: string }) => TextLink[])[] = [],
228
+ ) {
139
229
  const textLinks = textLinksOf(links)
140
230
  return async (text: string, ctx: RenderContext) => {
141
- const out = await renderMarkdown(String(text ?? ''), { page: '', file: '', resolve: () => null, code: blocks().code, textLinks: textLinks(ctx.project.dir), message: true })
231
+ const out = await renderMarkdown(String(text ?? ''), {
232
+ page: '',
233
+ file: '',
234
+ resolve: () => null,
235
+ code: blocks().code,
236
+ textLinks: textLinks(ctx.project.dir),
237
+ message: true,
238
+ })
142
239
  return { html: out.html, styles: out.styles.map(s => ctx.asset(s)) }
143
240
  }
144
241
  }
145
242
 
146
- export function createRender(blocks: () => ResolvedBlocks, style?: URL | string, pluginStyles: (URL | string)[] = [], links: ((ctx: { dir: string }) => TextLink[])[] = []) {
243
+ /** What a block left out of a build (RenderContext.skip) is: nothing, for its directives and fences alike. */
244
+ const skipped = (name: string): ResolvedBlock => ({
245
+ name,
246
+ code: false,
247
+ fences: true,
248
+ props: null,
249
+ html: () => '',
250
+ client: null,
251
+ style: null,
252
+ source: 'build',
253
+ })
254
+
255
+ export function createRender(
256
+ blocks: () => ResolvedBlocks,
257
+ style?: URL | string,
258
+ pluginStyles: { plugin: string; file: URL | string }[] = [],
259
+ links: ((ctx: { dir: string }) => TextLink[])[] = [],
260
+ ) {
147
261
  const textLinks = textLinksOf(links)
148
262
  const STYLE = stylePath(style)
149
- const PLUGIN_STYLES = pluginStyles.map(stylePath).filter((f): f is string => !!f)
263
+ const PLUGIN_STYLES = pluginStyles
264
+ .map(s => ({ plugin: s.plugin, file: stylePath(s.file) }))
265
+ .filter((s): s is { plugin: string; file: string } => !!s.file)
150
266
  async function markdown(source: string, page: string, file: string, ctx: RenderContext) {
151
267
  const { blocks: set, code } = blocks()
152
- return renderMarkdown(body(source), { page, file, resolve: name => set.get(name) ?? null, code, linkFor: ctx.urlFor, textLinks: textLinks(ctx.project.dir) })
268
+ const skip = ctx.skip
269
+ return renderMarkdown(body(source), {
270
+ page,
271
+ file,
272
+ resolve: name => {
273
+ const block = set.get(name) ?? null
274
+ if (skip && (skip.has(name) || (block && skip.has(block.source)))) return skipped(name)
275
+ return block
276
+ },
277
+ code,
278
+ linkFor: ctx.urlFor,
279
+ textLinks: textLinks(ctx.project.dir),
280
+ })
153
281
  }
154
282
 
155
283
  async function content(page: StoredPage, ctx: RenderContext): Promise<Content> {
@@ -160,27 +288,58 @@ export function createRender(blocks: () => ResolvedBlocks, style?: URL | string,
160
288
  case 'pages': {
161
289
  const list = page.pages.length ? pageList(page.pages) : html`<p class="wb-meta">No pages yet.</p>`
162
290
  const view = page.id
163
- ? html`<h1>${page.id}</h1>${list}<p class="wb-meta">${page.file}</p>`
164
- : html`<h1>${project.name}</h1>${list}${project.files && documentList(ctx)}<p class="wb-meta"><code>${project.dir}</code>${project.files && html` · <a href="/-/">files</a>`} · <a href="/_/docs">how to write pages</a></p>`
291
+ ? html`<h1>${page.id}</h1>
292
+ ${list}
293
+ <p class="wb-meta">${page.file}</p>`
294
+ : html`<h1>${project.name}</h1>
295
+ ${list}${project.files && documentList(ctx)}
296
+ <p class="wb-meta">
297
+ <code>${project.dir}</code>${project.files && html` · <a href="/-/">files</a>`} ·
298
+ <a href="/_/docs">how to write pages</a>
299
+ </p>`
165
300
  return { html: view, title: page.id || project.name, islands: {}, styles: [] }
166
301
  }
167
302
  case 'folder': {
168
303
  const rel = page.id.slice(2)
169
- const rows = page.entries.map(e => html`<li><a href="${encodeURIComponent(e.name) + (e.dir ? '/' : '')}">${e.name + (e.dir ? '/' : '')}</a></li>`)
170
- const listing = html`<h1>${rel || project.name}</h1><ul class="wb-files">${rel && html`<li><a href="../">../</a></li>`}${rows}</ul><p class="wb-meta">${page.file} · <code>${page.id}</code></p>`
304
+ const rows = page.entries.map(
305
+ e =>
306
+ html`<li>
307
+ <a href="${encodeURIComponent(e.name) + (e.dir ? '/' : '')}">${e.name + (e.dir ? '/' : '')}</a>
308
+ </li>`,
309
+ )
310
+ const listing = html`<h1>${rel || project.name}</h1>
311
+ <ul class="wb-files">
312
+ ${rel && html`<li><a href="../">../</a></li>`}${rows}
313
+ </ul>
314
+ <p class="wb-meta">${page.file} · <code>${page.id}</code></p>`
171
315
  const readme = readmeOf(page)
172
316
  if (!readme) return { html: listing, title: rel || project.name, islands: {}, styles: [] }
173
317
  // markdown's output is HTML already
174
318
  const r = await markdown(readme.source, page.id, readme.file, ctx)
175
- return { ...r, html: html`${raw(r.html)}<hr>${listing}` }
319
+ return {
320
+ ...r,
321
+ html: html`${raw(r.html)}
322
+ <hr />
323
+ ${listing}`,
324
+ }
176
325
  }
177
326
  case 'file': {
178
327
  // the file as one code block, rendered by the code block (or as plain code)
179
328
  const { code } = blocks()
180
329
  const ext = path.extname(page.file).slice(1).toLowerCase()
181
- const tree: MdNode = { type: 'root', children: [{ type: 'code', lang: CODE_LANG[ext] ?? (ext || null), meta: null, value: page.source }] }
182
- const out = await renderMarkdown(tree, { page: page.id, file: page.file, resolve: () => null, code, linkFor: ctx.urlFor })
183
- const view = html`<h1 class="wb-code-title wb-wide">${page.id.slice(2)}</h1><div class="wb-code wb-wide">${raw(out.html)}</div>`
330
+ const tree: MdNode = {
331
+ type: 'root',
332
+ children: [{ type: 'code', lang: CODE_LANG[ext] ?? (ext || null), meta: null, value: page.source }],
333
+ }
334
+ const out = await renderMarkdown(tree, {
335
+ page: page.id,
336
+ file: page.file,
337
+ resolve: () => null,
338
+ code,
339
+ linkFor: ctx.urlFor,
340
+ })
341
+ const view = html`<h1 class="wb-code-title wb-wide">${page.id.slice(2)}</h1>
342
+ <div class="wb-code wb-wide">${raw(out.html)}</div>`
184
343
  return { html: view, title: path.basename(page.file), islands: out.islands, styles: out.styles }
185
344
  }
186
345
  }
@@ -194,20 +353,48 @@ export function createRender(blocks: () => ResolvedBlocks, style?: URL | string,
194
353
  // blocks that do not resolve (a bad block in a plugin)
195
354
  out = { html: html`<pre class="wb-error">${(err as Error).message}</pre>`, islands: {}, styles: [] }
196
355
  }
197
- const islands = Object.fromEntries(Object.entries(out.islands).map(([id, island]) => [id, { ...island, client: ctx.asset(island.client) }]))
356
+ const islands = Object.fromEntries(
357
+ Object.entries(out.islands).map(([id, island]) => [id, { ...island, client: ctx.asset(island.client) }]),
358
+ )
198
359
  const styles = out.styles.map(s => ctx.asset(s))
199
- const nav = html`<nav class="wb-nav"><span>${crumbs(page.id, ctx.project.name)}</span>${page.mtime != null && html`<span class="wb-meta">updated <time id="wb-updated" data-ts="${page.mtime}"></time></span>`}<button type="button" class="wb-theme" title="Theme: follow the system, light or dark" aria-label="Theme"></button><span class="wb-live" role="img" title="Connecting…" aria-label="Connecting…"></span></nav>`
360
+ // a built page: the project's name and the theme; nothing of the server's (crumbs into its
361
+ // folders, when it was updated, whether it is live)
362
+ const nav =
363
+ ctx.live === false
364
+ ? html`<nav class="wb-nav">
365
+ <span>${ctx.project.name}</span
366
+ ><button
367
+ type="button"
368
+ class="wb-theme"
369
+ title="Theme: follow the system, light or dark"
370
+ aria-label="Theme"
371
+ ></button>
372
+ </nav>`
373
+ : html`<nav class="wb-nav">
374
+ <span>${crumbs(page.id, ctx.project.name)}</span
375
+ >${page.mtime != null && html`<span class="wb-meta">updated <time id="wb-updated" data-ts="${page.mtime}"></time></span>`}<button
376
+ type="button"
377
+ class="wb-theme"
378
+ title="Theme: follow the system, light or dark"
379
+ aria-label="Theme"
380
+ ></button
381
+ ><span class="wb-live" role="img" title="Connecting…" aria-label="Connecting…"></span>
382
+ </nav>`
200
383
  // the page's own, the plugins' (every page), the blocks' on this page, then the project's
201
- const links = [ctx.asset(BASE_CSS), ...PLUGIN_STYLES.map(f => ctx.asset(f)), ...styles, ...(STYLE ? [ctx.asset(STYLE)] : [])]
384
+ const links = [
385
+ ctx.asset(BASE_CSS),
386
+ ...PLUGIN_STYLES.filter(s => !ctx.skip?.has(s.plugin)).map(s => ctx.asset(s.file)),
387
+ ...styles,
388
+ ...(STYLE ? [ctx.asset(STYLE)] : []),
389
+ ]
202
390
  return {
203
391
  title: out.title || page.id || ctx.project.name,
204
- head: html`${THEME_SCRIPT}
205
- ${links.map(href => html`<link rel="stylesheet" href="${href}">`)}`,
392
+ head: html`${THEME_SCRIPT} ${links.map(href => html`<link rel="stylesheet" href="${href}" />`)}`,
206
393
  // the page's content is HTML already: markdown's output, or what was built above
207
- html: html`${nav}<main id="wb-main">${raw(out.html)}</main>`,
394
+ html: html`${nav}
395
+ <main id="wb-main">${raw(out.html)}</main>`,
208
396
  // the client mounts `islands` and links `styles`
209
- // its frontmatter too, for the plugins in the browser (handle.data.frontmatter)
210
- data: { islands, styles, mtime: page.mtime, frontmatter: page.kind === 'page' ? page.frontmatter : {} },
397
+ data: { islands, styles, mtime: page.mtime },
211
398
  }
212
399
  }
213
400
  }
@@ -219,8 +406,13 @@ ${links.map(href => html`<link rel="stylesheet" href="${href}">`)}`,
219
406
  export function createDocs(blocks: () => ResolvedBlocks) {
220
407
  return function docs(_ctx: RenderContext) {
221
408
  const byPlugin = new Map<string, string[]>()
222
- for (const t of blocks().blocks.values()) byPlugin.set(t.source, [...(byPlugin.get(t.source) ?? []), t.code ? `${t.name} (every other code fence)` : t.name])
223
- const list = [...byPlugin].sort(([a], [b]) => a.localeCompare(b))
409
+ for (const t of blocks().blocks.values())
410
+ byPlugin.set(t.source, [
411
+ ...(byPlugin.get(t.source) ?? []),
412
+ t.code ? `${t.name} (every other code fence)` : t.name,
413
+ ])
414
+ const list = [...byPlugin]
415
+ .toSorted(([a], [b]) => a.localeCompare(b))
224
416
  .map(([plugin, blocks]) => `- **${plugin}**: ${blocks.map(b => `\`${b}\``).join(', ')}`)
225
417
  return `# Pages
226
418
 
@@ -0,0 +1,78 @@
1
+ // A window around a block: a header with its label (or an address), a button that opens what it
2
+ // shows on its own (an address, an image), and one that fills the browser window with it (the page
3
+ // does that: src/client/page/window.ts; the same button, or Esc, puts it back). The iframe block
4
+ // is one around a page, `:::window` one around any markdown; any block can draw one.
5
+ import { html, raw, type Html } from '../html.ts'
6
+
7
+ // the header's buttons, as icons
8
+ const svg = (d: string) =>
9
+ raw(
10
+ `<svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round">${d}</svg>`,
11
+ )
12
+ const OPEN = svg(
13
+ '<path d="M9 2.5h4.5V7M13.5 2.5 7.5 8.5M11.5 9.5v3a1 1 0 0 1-1 1h-7a1 1 0 0 1-1-1v-7a1 1 0 0 1 1-1h3"/>',
14
+ )
15
+ const MAXIMIZE = svg('<path d="M2.5 6V2.5H6M10 2.5h3.5V6M13.5 10v3.5H10M6 13.5H2.5V10"/>')
16
+ const RESTORE = svg('<path d="M6 2.5V6H2.5M13.5 6H10V2.5M10 13.5V10h3.5M2.5 10H6v3.5"/>')
17
+
18
+ export interface WindowOptions {
19
+ /** what the window shows, as HTML */
20
+ body: Html | string
21
+ /** its label, as HTML (a block's label); without one, the header shows `address` */
22
+ label?: Html | string | null
23
+ /** what it shows on its own: an address, an image's; the ↗ button opens it, and hovering the label shows it */
24
+ open?: string | null
25
+ /** wider than the text column */
26
+ wide?: boolean
27
+ /** no header: the window alone, without its buttons */
28
+ bare?: boolean
29
+ /** a class for its body, and a height for it (a CSS length), for what has none of its own (an iframe) */
30
+ bodyClass?: string
31
+ height?: string
32
+ /** a class for the window itself, for a block's styles and browser code to find it by */
33
+ className?: string
34
+ /** more in the header, after the label: a block's own controls (the steps' ‹ › ) */
35
+ controls?: Html | string
36
+ }
37
+
38
+ /** A window around a block's HTML: see the top of this file. */
39
+ export function windowFrame({
40
+ body,
41
+ label = null,
42
+ open = null,
43
+ wide = false,
44
+ bare = false,
45
+ bodyClass = '',
46
+ height,
47
+ className = '',
48
+ controls = '',
49
+ }: WindowOptions): Html {
50
+ const name =
51
+ label != null && String(label) !== ''
52
+ ? html`<span class="wb-window-title">${raw(String(label))}</span>`
53
+ : open
54
+ ? html`<span class="wb-window-address">${open}</span>`
55
+ : html``
56
+ const header =
57
+ !bare &&
58
+ html`<div class="wb-window-bar">
59
+ <span class="wb-window-name" ${open ? html` title="${open}"` : ''}>${name}</span>
60
+ ${raw(String(controls))}
61
+ ${open && html`<a class="wb-window-button" href="${open}" target="_blank" rel="noopener" title="Open on its own" aria-label="Open on its own">${OPEN}</a>`}
62
+ <button
63
+ type="button"
64
+ class="wb-window-button"
65
+ data-wb-maximize
66
+ title="Fill the window"
67
+ aria-label="Fill the window"
68
+ >
69
+ <span class="wb-window-max">${MAXIMIZE}</span><span class="wb-window-restore">${RESTORE}</span>
70
+ </button>
71
+ </div>`
72
+ return html`<div class="wb-window${wide && raw(' wb-wide')}${className && raw(' ' + className)}">
73
+ ${header}
74
+ <div class="wb-window-body${bodyClass && raw(' ' + bodyClass)}" ${height ? html` style="height: ${height}"` : ''}>
75
+ ${raw(String(body))}
76
+ </div>
77
+ </div>`
78
+ }
package/src/plugins.ts CHANGED
@@ -42,7 +42,8 @@ const TYPES: Record<BaseType, (v: unknown) => boolean> = {
42
42
  function parseType(spec: FieldType | string, where: string): { type: BaseType; optional: boolean } {
43
43
  const optional = spec.endsWith('?')
44
44
  const type = optional ? spec.slice(0, -1) : spec
45
- if (!(type in TYPES)) throw new Error(`${where}: unknown type "${spec}" (one of ${Object.keys(TYPES).join(', ')}, with ? when optional)`)
45
+ if (!(type in TYPES))
46
+ throw new Error(`${where}: unknown type "${spec}" (one of ${Object.keys(TYPES).join(', ')}, with ? when optional)`)
46
47
  return { type: type as BaseType, optional }
47
48
  }
48
49
 
@@ -52,7 +53,10 @@ function checkFields(spec: Record<string, FieldType> = {}, input: unknown = {},
52
53
  const value = input as Record<string, unknown>
53
54
  for (const [name, s] of Object.entries(spec)) {
54
55
  const { type, optional } = parseType(s, where)
55
- if (value[name] === undefined) { if (!optional) return `${where}: ${name} is missing`; continue }
56
+ if (value[name] === undefined) {
57
+ if (!optional) return `${where}: ${name} is missing`
58
+ continue
59
+ }
56
60
  if (!TYPES[type](value[name])) return `${where}: ${name} must be ${type}`
57
61
  }
58
62
  for (const name of Object.keys(value)) if (!(name in spec)) return `${where}: unknown field ${name}`
@@ -81,10 +85,12 @@ export function mountRoutes(name: string, routes: Record<string, Route> = {}): M
81
85
  const m = ROUTE.exec(key)
82
86
  if (!m) throw new Error(`plugin ${name}: route "${key}" must look like "GET /path"`)
83
87
  if (typeof route?.run !== 'function') throw new Error(`plugin ${name}: route "${key}" has no run function`)
84
- for (const [field, spec] of Object.entries({ ...route.body, ...route.query })) parseType(spec, `plugin ${name}, route "${key}", ${field}`)
88
+ for (const [field, spec] of Object.entries({ ...route.body, ...route.query }))
89
+ parseType(spec, `plugin ${name}, route "${key}", ${field}`)
85
90
  const [, method, at] = m as unknown as [string, string, string]
86
91
  const path = `/api/${name}${at === '/' ? '' : at.replace(/\/$/, '')}`
87
- if (table.some(r => r.method === method && r.path === path)) throw new Error(`plugin ${name}: route "${key}" is declared twice`)
92
+ if (table.some(r => r.method === method && r.path === path))
93
+ throw new Error(`plugin ${name}: route "${key}" is declared twice`)
88
94
  table.push({ method, path, route, plugin: name })
89
95
  }
90
96
  return table
@@ -93,8 +99,20 @@ export function mountRoutes(name: string, routes: Record<string, Route> = {}): M
93
99
  function readJson(req: IncomingMessage): Promise<unknown> {
94
100
  return new Promise((resolve, reject) => {
95
101
  let body = ''
96
- req.on('data', (c: Buffer) => { body += c; if (body.length > 1e6) { reject(new Error('body too large')); req.destroy() } })
97
- req.on('end', () => { try { resolve(body ? JSON.parse(body) : {}) } catch { reject(new Error('the body is not JSON')) } })
102
+ req.on('data', (c: Buffer) => {
103
+ body += c
104
+ if (body.length > 1e6) {
105
+ reject(new Error('body too large'))
106
+ req.destroy()
107
+ }
108
+ })
109
+ req.on('end', () => {
110
+ try {
111
+ resolve(body ? JSON.parse(body) : {})
112
+ } catch {
113
+ reject(new Error('the body is not JSON'))
114
+ }
115
+ })
98
116
  req.on('error', reject)
99
117
  })
100
118
  }
@@ -110,29 +128,56 @@ const json = (res: ServerResponse, status: number, data: unknown) => {
110
128
  * JSON; a stream route (`stream: true`) writes to `res` itself. An error it throws is sent with its
111
129
  * `status` (default 500).
112
130
  */
113
- export async function dispatch(table: MountedRoute[], req: IncomingMessage, res: ServerResponse, url: URL, authorized: (req: IncomingMessage) => boolean): Promise<boolean> {
131
+ export async function dispatch(
132
+ table: MountedRoute[],
133
+ req: IncomingMessage,
134
+ res: ServerResponse,
135
+ url: URL,
136
+ authorized: (req: IncomingMessage) => boolean,
137
+ ): Promise<boolean> {
114
138
  const forPath = table.filter(r => r.path === url.pathname)
115
139
  if (!forPath.length) return false
116
140
  const hit = forPath.find(r => r.method === req.method)
117
- if (!hit) { res.setHeader('allow', forPath.map(r => r.method).join(', ')); json(res, 405, { error: `use ${forPath.map(r => r.method).join(' or ')}` }); return true }
141
+ if (!hit) {
142
+ res.setHeader('allow', forPath.map(r => r.method).join(', '))
143
+ json(res, 405, { error: `use ${forPath.map(r => r.method).join(' or ')}` })
144
+ return true
145
+ }
118
146
  const { route } = hit
119
- if (route.auth && !authorized(req)) { json(res, 403, { error: 'this needs the project\'s token: open a link from the command line, or send x-whiteboard-token' }); return true }
147
+ if (route.auth && !authorized(req)) {
148
+ json(res, 403, {
149
+ error: "this needs the project's token: open a link from the command line, or send x-whiteboard-token",
150
+ })
151
+ return true
152
+ }
120
153
  try {
121
154
  const query = fromQuery(route.query, url.searchParams)
122
155
  const queryError = route.query ? checkFields(route.query, query, 'query') : null
123
- if (queryError) { json(res, 400, { error: queryError }); return true }
156
+ if (queryError) {
157
+ json(res, 400, { error: queryError })
158
+ return true
159
+ }
124
160
  let body: Record<string, unknown> = {}
125
161
  if (hit.method !== 'GET' && hit.method !== 'DELETE') {
126
162
  const input = await readJson(req)
127
163
  const bodyError = checkFields(route.body, input, 'body')
128
- if (bodyError) { json(res, 400, { error: bodyError }); return true }
164
+ if (bodyError) {
165
+ json(res, 400, { error: bodyError })
166
+ return true
167
+ }
129
168
  body = input as Record<string, unknown>
130
169
  }
131
- if (route.stream) { await route.run({ body, query, req, res }); return true }
170
+ if (route.stream) {
171
+ await route.run({ body, query, req, res })
172
+ return true
173
+ }
132
174
  const out = await route.run({ body, query, req })
133
175
  json(res, 200, out ?? { ok: true })
134
176
  } catch (err) {
135
- if (res.headersSent) { res.end(); return true }
177
+ if (res.headersSent) {
178
+ res.end()
179
+ return true
180
+ }
136
181
  const e = err as { status?: number; message?: string } | null
137
182
  json(res, e?.status ?? 500, { error: e?.message ?? String(err) })
138
183
  }
@@ -140,10 +185,16 @@ export async function dispatch(table: MountedRoute[], req: IncomingMessage, res:
140
185
  }
141
186
 
142
187
  /** The routes for the docs: method, path, what it does, what it takes. */
143
- export const describeRoutes = (table: MountedRoute[]) => table.map(({ method, path, route }) => ({
144
- method, path, description: route.description ?? '', auth: !!route.auth, stream: !!route.stream,
145
- body: route.body ?? null, query: route.query ?? null,
146
- }))
188
+ export const describeRoutes = (table: MountedRoute[]) =>
189
+ table.map(({ method, path, route }) => ({
190
+ method,
191
+ path,
192
+ description: route.description ?? '',
193
+ auth: !!route.auth,
194
+ stream: !!route.stream,
195
+ body: route.body ?? null,
196
+ query: route.query ?? null,
197
+ }))
147
198
 
148
199
  // ---- commands ----------------------------------------------------------------------------------
149
200
 
@@ -175,19 +226,34 @@ export function parseCommandArgs(command: Command, all: string[], name: string)
175
226
  const cut = all.indexOf('--')
176
227
  const args = cut < 0 ? all : all.slice(0, cut)
177
228
  const rest = cut < 0 ? [] : all.slice(cut + 1)
178
- if (rest.length && !command.rest) throw new Error(`whiteboard ${name} takes nothing after --\nusage: whiteboard ${name} ${usage(command)}`)
179
- const options: ParseArgsOptionsConfig = Object.fromEntries(Object.entries(command.options ?? {}).map(([key, o]) => {
180
- const { type } = parseType(o.type, key)
181
- return [key, { type: type === 'boolean' ? 'boolean' as const : 'string' as const, ...(o.short ? { short: o.short } : {}) }]
182
- }))
229
+ if (rest.length && !command.rest)
230
+ throw new Error(`whiteboard ${name} takes nothing after --\nusage: whiteboard ${name} ${usage(command)}`)
231
+ const options: ParseArgsOptionsConfig = Object.fromEntries(
232
+ Object.entries(command.options ?? {}).map(([key, o]) => {
233
+ const { type } = parseType(o.type, key)
234
+ return [
235
+ key,
236
+ {
237
+ type: type === 'boolean' ? ('boolean' as const) : ('string' as const),
238
+ ...(o.short ? { short: o.short } : {}),
239
+ },
240
+ ]
241
+ }),
242
+ )
183
243
  let parsed
184
- try { parsed = parseArgs({ args, options, allowPositionals: true, strict: true }) } catch (err) {
244
+ try {
245
+ parsed = parseArgs({ args, options, allowPositionals: true, strict: true })
246
+ } catch (err) {
185
247
  throw new Error(`${(err as Error).message}\nusage: whiteboard ${name} ${usage(command)}`)
186
248
  }
187
249
  const values: Record<string, unknown> = { ...parsed.values }
188
250
  for (const [key, o] of Object.entries(command.options ?? {})) {
189
251
  const { type, optional } = parseType(o.type, key)
190
- if (values[key] === undefined) { if (!optional && type !== 'boolean') throw new Error(`--${key} is missing\nusage: whiteboard ${name} ${usage(command)}`); continue }
252
+ if (values[key] === undefined) {
253
+ if (!optional && type !== 'boolean')
254
+ throw new Error(`--${key} is missing\nusage: whiteboard ${name} ${usage(command)}`)
255
+ continue
256
+ }
191
257
  if (type === 'number') {
192
258
  values[key] = Number(values[key])
193
259
  if (!Number.isFinite(values[key])) throw new Error(`--${key} must be a number`)