@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
package/src/loader.ts CHANGED
@@ -8,7 +8,8 @@ import { fileURLToPath } from 'node:url'
8
8
  import { importFresh, importOwn } from './load.ts'
9
9
  import { createPages, type Pages } from './pages/index.ts'
10
10
  import { pluginCommands } from './plugins.ts'
11
- import type { Config, Plugin } from './define.ts'
11
+ import { inPublic, publicDirOf } from './public.ts'
12
+ import type { BuildConfig, Config, Plugin } from './define.ts'
12
13
  import type { Project } from './config.ts'
13
14
 
14
15
  /** A config as loaded: what went wrong is in `errors`. */
@@ -20,13 +21,38 @@ export interface LoadedConfig {
20
21
  handedOut: Set<string>
21
22
  /** the plugins' event types declared `forReader: true`: from the agent, a message for the reader */
22
23
  forReader: Set<string>
24
+ /** each plugin's public folder, by name: the one place its browser files are served from */
25
+ publicDirs: Map<string, string>
23
26
  files: boolean
27
+ /** what `whiteboard build` makes */
28
+ build: BuildConfig
24
29
  errors: unknown[]
25
30
  }
26
31
 
27
32
  const NAME = /^[\w-]+$/
28
33
  /** The command line's own commands: a plugin can't be named like one, since its commands are `whiteboard <name>`. */
29
- export const BUILTIN_COMMANDS = new Set(['serve', 'init', 'root', 'new', 'show', 'url', 'docs', 'events', 'wait', 'watch', 'append', 'pick', 'status', 'scroll', 'close', 'prune', 'edit', 'skill', 'help'])
34
+ export const BUILTIN_COMMANDS = new Set([
35
+ 'serve',
36
+ 'init',
37
+ 'root',
38
+ 'new',
39
+ 'show',
40
+ 'url',
41
+ 'docs',
42
+ 'events',
43
+ 'wait',
44
+ 'watch',
45
+ 'append',
46
+ 'pick',
47
+ 'status',
48
+ 'scroll',
49
+ 'close',
50
+ 'prune',
51
+ 'build',
52
+ 'edit',
53
+ 'skill',
54
+ 'help',
55
+ ])
30
56
  // folders in .whiteboard/ that are the core's or meant for the project's own plugins (a plugin's own
31
57
  // folder holds its data, ignored by git), and the built-in commands
32
58
  const RESERVED = new Set(['pages', 'plugins', ...BUILTIN_COMMANDS])
@@ -54,11 +80,14 @@ async function builtinPlugins(): Promise<Plugin[]> {
54
80
 
55
81
  /** Check a plugin, as the config gives it. */
56
82
  function checkPlugin(e: Plugin, where: string | null) {
57
- if (typeof e !== 'object' || !NAME.test(e?.name ?? '')) throw new Error(`a plugin in ${where} needs a name: letters, digits, - and _`)
58
- if (RESERVED.has(e.name)) throw new Error(`plugin name "${e.name}" in ${where} is taken by the core (a folder in .whiteboard/ or a command)`)
83
+ if (typeof e !== 'object' || !NAME.test(e?.name ?? ''))
84
+ throw new Error(`a plugin in ${where} needs a name: letters, digits, - and _`)
85
+ if (RESERVED.has(e.name))
86
+ throw new Error(`plugin name "${e.name}" in ${where} is taken by the core (a folder in .whiteboard/ or a command)`)
59
87
  pluginCommands(e) // checks them
60
88
  for (const type of Object.keys(e.events ?? {}))
61
- if (!type.startsWith(`${e.name}:`) || type.length <= e.name.length + 1) throw new Error(`plugin ${e.name}: event type "${type}" must be named after it: ${e.name}:<what>`)
89
+ if (!type.startsWith(`${e.name}:`) || type.length <= e.name.length + 1)
90
+ throw new Error(`plugin ${e.name}: event type "${type}" must be named after it: ${e.name}:<what>`)
62
91
  }
63
92
 
64
93
  /**
@@ -92,21 +121,61 @@ export function createConfigLoader(proj: Project, { pages: withPages = true } =
92
121
  if (builtin.has(e.name)) plugins[plugins.findIndex(p => p.name === e.name)] = e
93
122
  else plugins.push(e)
94
123
  }
95
- const blocks = plugins.flatMap(p => Object.entries(p.blocks ?? {}).map(([name, block]) => ({ name, block, plugin: p.name })))
96
- const styles = plugins.map(p => p.style).filter((s): s is URL | string => !!s)
97
- const links = plugins.flatMap(p => p.links ? [p.links.bind(p)] : [])
124
+ // each plugin's browser files are served from its public folder alone: its files are named in it
125
+ const publicDirs = new Map(plugins.map(p => [p.name, publicDirOf(p, proj.wb)]))
126
+ const blocks = plugins.flatMap(p =>
127
+ Object.entries(p.blocks ?? {}).map(([name, block]) => ({
128
+ name,
129
+ block,
130
+ plugin: p.name,
131
+ public: publicDirs.get(p.name)!,
132
+ })),
133
+ )
134
+ const styles = plugins
135
+ .filter(p => p.style)
136
+ .map(p => ({ plugin: p.name, file: inPublic(publicDirs.get(p.name)!, p.style!, `plugin ${p.name}: style`) }))
137
+ const links = plugins.flatMap(p => (p.links ? [p.links.bind(p)] : []))
98
138
  const pages = withPages ? createPages({ blocks, style: config?.style, styles, links }) : null
99
- const declared = (flag: 'handOut' | 'forReader') => new Set(plugins.flatMap(p => Object.entries(p.events ?? {}).filter(([, spec]) => spec?.[flag]).map(([type]) => type)))
100
- return { pages, plugins, handedOut: declared('handOut'), forReader: declared('forReader'), files: config?.files !== false }
139
+ const declared = (flag: 'handOut' | 'forReader') =>
140
+ new Set(
141
+ plugins.flatMap(p =>
142
+ Object.entries(p.events ?? {})
143
+ .filter(([, spec]) => spec?.[flag])
144
+ .map(([type]) => type),
145
+ ),
146
+ )
147
+ return {
148
+ pages,
149
+ plugins,
150
+ handedOut: declared('handOut'),
151
+ forReader: declared('forReader'),
152
+ publicDirs,
153
+ files: config?.files !== false,
154
+ build: config?.build ?? {},
155
+ }
101
156
  }
102
157
 
103
158
  function config(): Promise<LoadedConfig> {
104
159
  cached ??= load().then(
105
160
  value => ({ ...value, errors: [] }),
106
- error => ({ pages: null, plugins: [], handedOut: new Set<string>(), forReader: new Set<string>(), files: false, errors: [error] }),
161
+ error => ({
162
+ pages: null,
163
+ plugins: [],
164
+ handedOut: new Set<string>(),
165
+ forReader: new Set<string>(),
166
+ publicDirs: new Map<string, string>(),
167
+ files: false,
168
+ build: {},
169
+ errors: [error],
170
+ }),
107
171
  )
108
172
  return cached
109
173
  }
110
174
 
111
- return { config, invalidate: () => { cached = null } }
175
+ return {
176
+ config,
177
+ invalidate: () => {
178
+ cached = null
179
+ },
180
+ }
112
181
  }
package/src/package.ts CHANGED
@@ -8,9 +8,13 @@ import { fileURLToPath } from 'node:url'
8
8
  function findRoot(from: string): string {
9
9
  for (let dir = from; ; dir = path.dirname(dir)) {
10
10
  try {
11
- if (JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8')).name === '@bigmistqke/whiteboard') return dir
12
- } catch { /* no package.json here, or not ours */ }
13
- if (path.dirname(dir) === dir) throw new Error(`whiteboard: no package.json of @bigmistqke/whiteboard above ${from}`)
11
+ if (JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8')).name === '@bigmistqke/whiteboard')
12
+ return dir
13
+ } catch {
14
+ /* no package.json here, or not ours */
15
+ }
16
+ if (path.dirname(dir) === dir)
17
+ throw new Error(`whiteboard: no package.json of @bigmistqke/whiteboard above ${from}`)
14
18
  }
15
19
  }
16
20
 
@@ -32,8 +36,5 @@ export const FROM_SOURCE = fileURLToPath(import.meta.url).endsWith('.ts')
32
36
  * dist/. The same whether the module runs from source (plugins/form/index.ts gives
33
37
  * dist/plugins/form/client.js) or from dist/ itself.
34
38
  */
35
- export function builtFile(moduleUrl: string, name: string): string {
36
- const rel = path.relative(PACKAGE_DIR, path.dirname(fileURLToPath(moduleUrl)))
37
- const inDist = rel === 'dist' || rel.startsWith('dist' + path.sep)
38
- return path.join(PACKAGE_DIR, inDist ? '' : 'dist', rel, name)
39
- }
39
+ /** A built-in plugin's public folder: its built browser modules and copied styles (build.ts). */
40
+ export const builtinPublic = (name: string): string => packagePath('dist', 'plugins', name, 'public')
@@ -4,9 +4,16 @@ import path from 'node:path'
4
4
  import { fileURLToPath } from 'node:url'
5
5
  import type { Html } from '../html.ts'
6
6
  import type { Block } from '../define.ts'
7
+ import { inPublic } from '../public.ts'
7
8
 
8
9
  /** A block as the plugins bring it: its name, and the plugin it comes from. */
9
- export interface BlockEntry { name: string; block: Block<any>; plugin: string }
10
+ /** A block of a plugin, with the plugin's public folder, where its files are. */
11
+ export interface BlockEntry {
12
+ name: string
13
+ block: Block<any>
14
+ plugin: string
15
+ public: string
16
+ }
10
17
 
11
18
  const NAME = /^[\w-]+$/
12
19
 
@@ -25,23 +32,22 @@ export interface ResolvedBlock {
25
32
  source: string
26
33
  }
27
34
 
28
- export interface ResolvedBlocks { blocks: Map<string, ResolvedBlock>; code: ResolvedBlock | null }
29
-
30
- /** A block's file reference (URL, file: URL string, or absolute path) → absolute path. */
31
- function toPath(ref: unknown, field: string, block: string): string | null {
32
- if (ref == null) return null
33
- if (ref instanceof URL || (typeof ref === 'string' && ref.startsWith('file:'))) return fileURLToPath(ref)
34
- if (typeof ref === 'string' && path.isAbsolute(ref)) return ref
35
- throw new Error(`block "${block}": ${field} must be a URL, e.g. new URL('./${field}.js', import.meta.url)`)
35
+ export interface ResolvedBlocks {
36
+ blocks: Map<string, ResolvedBlock>
37
+ code: ResolvedBlock | null
36
38
  }
37
39
 
38
- /** Check and resolve one block into what the engine uses. */
39
- function normalize({ name, block: b, plugin }: BlockEntry): ResolvedBlock {
40
+ /** Check and resolve one block into what the engine uses: its files in its plugin's public folder. */
41
+ function normalize({ name, block: b, plugin, public: dir }: BlockEntry): ResolvedBlock {
40
42
  if (typeof b !== 'object' || !b) throw new Error(`plugin ${plugin}: block "${name}" is not an object`)
41
- if (!NAME.test(name)) throw new Error(`plugin ${plugin}: block name ${JSON.stringify(name)}: use letters, digits, - and _`)
42
- const files = { client: toPath(b.client, 'client', name), style: toPath(b.style, 'style', name) }
43
+ if (!NAME.test(name))
44
+ throw new Error(`plugin ${plugin}: block name ${JSON.stringify(name)}: use letters, digits, - and _`)
45
+ const file = (ref: URL | string | undefined, field: string) =>
46
+ ref == null ? null : inPublic(dir, ref, `plugin ${plugin}, block "${name}": ${field}`)
47
+ const files = { client: file(b.client, 'client'), style: file(b.style, 'style') }
43
48
  for (const [field, file] of Object.entries(files))
44
- if (file && !fs.existsSync(file)) throw new Error(`plugin ${plugin}, block "${name}": ${field} file not found: ${file}`)
49
+ if (file && !fs.existsSync(file))
50
+ throw new Error(`plugin ${plugin}, block "${name}": ${field} file not found: ${file}`)
45
51
  return {
46
52
  name,
47
53
  code: b.fence === 'any',
@@ -12,8 +12,8 @@ export interface PagesOptions {
12
12
  blocks: BlockEntry[]
13
13
  /** the project's stylesheet, linked on every page after the others */
14
14
  style?: URL | string
15
- /** the plugins' stylesheets, linked on every page */
16
- styles?: (URL | string)[]
15
+ /** the plugins' stylesheets, linked on every page (but a build's, for a plugin it skips) */
16
+ styles?: { plugin: string; file: URL | string }[]
17
17
  /** the plugins' text links (Plugin.links), each asked once per project folder */
18
18
  links?: ((ctx: { dir: string }) => TextLink[])[]
19
19
  }
@@ -42,25 +42,38 @@ const FENCE = /^(\s*)(`{3,}|~{3,})/
42
42
 
43
43
  function hideColonsInFences(source: string): string {
44
44
  let open: { char: string; length: number } | null = null
45
- return source.split('\n').map(line => {
46
- const fence = FENCE.exec(line)
47
- if (!open) {
48
- if (fence) open = { char: fence[2][0], length: fence[2].length }
49
- return line
50
- }
51
- if (fence && fence[2][0] === open.char && fence[2].length >= open.length && !line.slice(fence[0].length).trim()) { open = null; return line }
52
- return line.replace(/^(\s*)(:+)/, (_, space: string, colons: string) => space + HIDDEN_COLON.repeat(colons.length))
53
- }).join('\n')
45
+ return source
46
+ .split('\n')
47
+ .map(line => {
48
+ const fence = FENCE.exec(line)
49
+ if (!open) {
50
+ if (fence) open = { char: fence[2][0], length: fence[2].length }
51
+ return line
52
+ }
53
+ if (fence && fence[2][0] === open.char && fence[2].length >= open.length && !line.slice(fence[0].length).trim()) {
54
+ open = null
55
+ return line
56
+ }
57
+ return line.replace(
58
+ /^(\s*)(:+)/,
59
+ (_, space: string, colons: string) => space + HIDDEN_COLON.repeat(colons.length),
60
+ )
61
+ })
62
+ .join('\n')
54
63
  }
55
64
 
56
65
  function showColons(node: MdNode) {
57
- if (typeof node.value === 'string' && node.value.includes(HIDDEN_COLON)) node.value = node.value.replaceAll(HIDDEN_COLON, ':')
66
+ if (typeof node.value === 'string' && node.value.includes(HIDDEN_COLON))
67
+ node.value = node.value.replaceAll(HIDDEN_COLON, ':')
58
68
  node.children?.forEach(showColons)
59
69
  }
60
70
 
61
71
  /** A message's raw HTML, as text: it shows as written, and runs nothing. */
62
72
  function asText(node: MdNode) {
63
- if (node.type === 'html') { node.type = 'text'; return }
73
+ if (node.type === 'html') {
74
+ node.type = 'text'
75
+ return
76
+ }
64
77
  node.children?.forEach(asText)
65
78
  }
66
79
 
@@ -70,7 +83,10 @@ function parseMarkdown(source: string): MdNode {
70
83
  showColons(tree)
71
84
  return tree
72
85
  }
73
- const toHast = unified().use(remarkRehype, { allowDangerousHtml: true }).use(rehypeStringify, { allowDangerousHtml: true }).freeze()
86
+ const toHast = unified()
87
+ .use(remarkRehype, { allowDangerousHtml: true })
88
+ .use(rehypeStringify, { allowDangerousHtml: true })
89
+ .freeze()
74
90
 
75
91
  /** `cols=3 open title="a b"` → { cols: '3', open: '', title: 'a b' } (bare words get '' like directive attrs) */
76
92
  export function parseAttrs(s: unknown) {
@@ -81,8 +97,20 @@ export function parseAttrs(s: unknown) {
81
97
  }
82
98
 
83
99
  const DIRECTIVES = new Set(['containerDirective', 'leafDirective', 'textDirective'])
84
- const PHRASING = new Set(['text', 'emphasis', 'strong', 'delete', 'inlineCode', 'break', 'link', 'linkReference',
85
- 'image', 'imageReference', 'footnoteReference', 'textDirective'])
100
+ const PHRASING = new Set([
101
+ 'text',
102
+ 'emphasis',
103
+ 'strong',
104
+ 'delete',
105
+ 'inlineCode',
106
+ 'break',
107
+ 'link',
108
+ 'linkReference',
109
+ 'image',
110
+ 'imageReference',
111
+ 'footnoteReference',
112
+ 'textDirective',
113
+ ])
86
114
 
87
115
  const SCHEME = /^[a-z][a-z0-9+.-]*:/i
88
116
 
@@ -108,11 +136,19 @@ function linkText(tree: MdNode, links: TextLink[]) {
108
136
  const re = new RegExp(link.pattern.source, flags)
109
137
  let at = 0
110
138
  for (let m = re.exec(value); m; m = re.exec(value)) {
111
- if (!m[0]) { re.lastIndex++; continue }
139
+ if (!m[0]) {
140
+ re.lastIndex++
141
+ continue
142
+ }
112
143
  const href = link.href(m)
113
144
  if (!href) continue
114
145
  if (m.index > at) out.push({ type: 'text', value: value.slice(at, m.index) })
115
- out.push({ type: 'link', url: href, title: link.title?.(m) ?? null, children: [{ type: 'text', value: m[0] }] })
146
+ out.push({
147
+ type: 'link',
148
+ url: href,
149
+ title: link.title?.(m) ?? null,
150
+ children: [{ type: 'text', value: m[0] }],
151
+ })
116
152
  at = m.index + m[0].length
117
153
  }
118
154
  if (at < value.length) out.push({ type: 'text', value: value.slice(at) })
@@ -123,7 +159,9 @@ function linkText(tree: MdNode, links: TextLink[]) {
123
159
  }
124
160
  const walk = (node: MdNode) => {
125
161
  if (!node.children || NO_TEXT_LINKS.has(node.type)) return
126
- node.children = node.children.flatMap(child => child.type === 'text' ? split(child.value as string) : (walk(child), [child]))
162
+ node.children = node.children.flatMap(child =>
163
+ child.type === 'text' ? split(child.value as string) : (walk(child), [child]),
164
+ )
127
165
  }
128
166
  walk(tree)
129
167
  }
@@ -131,11 +169,19 @@ function linkText(tree: MdNode, links: TextLink[]) {
131
169
  function rewriteLinks(tree: MdNode, file: string, linkFor?: LinkFor) {
132
170
  if (!linkFor || !file) return
133
171
  const walk = (node: MdNode) => {
134
- if ((node.type === 'link' || node.type === 'image' || node.type === 'definition') && node.url &&
135
- !SCHEME.test(node.url) && !/^[/#]/.test(node.url)) {
172
+ if (
173
+ (node.type === 'link' || node.type === 'image' || node.type === 'definition') &&
174
+ node.url &&
175
+ !SCHEME.test(node.url) &&
176
+ !/^[/#]/.test(node.url)
177
+ ) {
136
178
  const [, target, rest] = /^([^?#]*)(.*)$/s.exec(node.url)!
137
179
  let decoded = target
138
- try { decoded = decodeURIComponent(target) } catch { /* keep as written */ }
180
+ try {
181
+ decoded = decodeURIComponent(target)
182
+ } catch {
183
+ /* keep as written */
184
+ }
139
185
  const url = decoded && linkFor(path.resolve(path.dirname(file), decoded))
140
186
  if (url) node.url = url + rest
141
187
  }
@@ -147,7 +193,8 @@ function rewriteLinks(tree: MdNode, file: string, linkFor?: LinkFor) {
147
193
  /** Separate a directive's `[label]` (remark-directive stores it as a flagged first paragraph). */
148
194
  function splitLabel(node: MdNode): { label: MdNode[] | null; children: MdNode[] } {
149
195
  const [head, ...rest] = node.children ?? []
150
- if (node.type === 'containerDirective' && head?.data?.directiveLabel) return { label: head.children ?? null, children: rest }
196
+ if (node.type === 'containerDirective' && head?.data?.directiveLabel)
197
+ return { label: head.children ?? null, children: rest }
151
198
  if (node.type !== 'containerDirective') return { label: node.children?.length ? node.children : null, children: [] }
152
199
  return { label: null, children: node.children ?? [] }
153
200
  }
@@ -156,7 +203,9 @@ const MARKER: Record<string, string> = { textDirective: ':', leafDirective: '::'
156
203
 
157
204
  function literalDirective(node: MdNode, label: MdNode[] | null) {
158
205
  const marker = MARKER[node.type]
159
- const attrs = Object.entries(node.attributes ?? {}).map(([k, v]) => (v ? `${k}="${v}"` : k)).join(' ')
206
+ const attrs = Object.entries(node.attributes ?? {})
207
+ .map(([k, v]) => (v ? `${k}="${v}"` : k))
208
+ .join(' ')
160
209
  return `${marker}${node.name}${label ? `[${toString({ type: 'root', children: label } as any)}]` : ''}${attrs ? `{${attrs}}` : ''}`
161
210
  }
162
211
 
@@ -203,14 +252,21 @@ export interface RenderOptions {
203
252
  message?: boolean
204
253
  }
205
254
 
206
- export interface Island { block: string; client: string; props: unknown }
255
+ export interface Island {
256
+ block: string
257
+ client: string
258
+ props: unknown
259
+ }
207
260
 
208
261
  /**
209
262
  * Markdown (or an mdast root, rendered as it is) → HTML, with directives and fences handed to
210
263
  * blocks. Returns the page's HTML, its first heading, the islands to mount and the blocks'
211
264
  * stylesheets.
212
265
  */
213
- export async function renderMarkdown(source: string | MdNode, { page, file, resolve, code = null, linkFor, textLinks = [], message = false }: RenderOptions) {
266
+ export async function renderMarkdown(
267
+ source: string | MdNode,
268
+ { page, file, resolve, code = null, linkFor, textLinks = [], message = false }: RenderOptions,
269
+ ) {
214
270
  let nextId = 0
215
271
  const islands: Record<string, Island> = {}
216
272
  const keyCount: Record<string, number> = {}
@@ -220,13 +276,18 @@ export async function renderMarkdown(source: string | MdNode, { page, file, reso
220
276
  // inline content (a label, say) is one line: as children of the root, each node would be a block
221
277
  // of its own, separated by newlines, which show as spaces
222
278
  if (nodes.length && nodes.every(n => PHRASING.has(n.type))) {
223
- const out = toHast.stringify(toHast.runSync({ type: 'root', children: [{ type: 'paragraph', children: nodes }] } as any))
279
+ const out = toHast.stringify(
280
+ toHast.runSync({ type: 'root', children: [{ type: 'paragraph', children: nodes }] } as any),
281
+ )
224
282
  return out.replace(/^<p>([\s\S]*)<\/p>$/, '$1')
225
283
  }
226
284
  return toHast.stringify(toHast.runSync({ type: 'root', children: nodes } as any))
227
285
  }
228
286
  /** Render mdast nodes to HTML. Transforms nested directives first; safe to call twice on the same nodes. */
229
- const toHtml = async (nodes: MdNode[]) => { await transform({ type: 'root', children: nodes }); return stringify(nodes) }
287
+ const toHtml = async (nodes: MdNode[]) => {
288
+ await transform({ type: 'root', children: nodes })
289
+ return stringify(nodes)
290
+ }
230
291
 
231
292
  async function sectionsOf(children: MdNode[]) {
232
293
  await transform({ type: 'root', children })
@@ -250,7 +311,11 @@ export async function renderMarkdown(source: string | MdNode, { page, file, reso
250
311
  }
251
312
  return {
252
313
  intro: stringify(intro),
253
- sections: out.map(s => ({ title: stringify(s.heading.children ?? []), text: toString(s.heading as any), html: stringify(s.body) })),
314
+ sections: out.map(s => ({
315
+ title: stringify(s.heading.children ?? []),
316
+ text: toString(s.heading as any),
317
+ html: stringify(s.body),
318
+ })),
254
319
  }
255
320
  }
256
321
 
@@ -271,7 +336,11 @@ export async function renderMarkdown(source: string | MdNode, { page, file, reso
271
336
  const id = String(++nextId)
272
337
  islands[id] = { block: block.name, client: block.client, props }
273
338
  // stable across re-renders while block + props are unchanged, so the client keeps the mounted island
274
- const hash = crypto.createHash('sha1').update(block.name + '\0' + JSON.stringify(props)).digest('hex').slice(0, 12)
339
+ const hash = crypto
340
+ .createHash('sha1')
341
+ .update(block.name + '\0' + JSON.stringify(props))
342
+ .digest('hex')
343
+ .slice(0, 12)
275
344
  const key = `${hash}-${(keyCount[hash] = (keyCount[hash] ?? 0) + 1)}`
276
345
  return html`<${tag} class="wb-island" data-block="${ctx.name}" data-wb-island="${id}" data-wb-key="${key}">${body}</${tag}>`
277
346
  } catch (err) {
@@ -298,7 +367,9 @@ export async function renderMarkdown(source: string | MdNode, { page, file, reso
298
367
  if (node.type === 'textDirective') return { type: 'text', value: literalDirective(node, label) }
299
368
  // an unknown directive still shows its content: a typo never breaks the page
300
369
  const labelHtml = label && html`<p class="wb-label"><strong>${raw(await toHtml(label))}</strong></p>`
301
- return htmlNode(html`<div class="wb-unknown" data-directive="${node.name}">${labelHtml}${raw(await toHtml(children))}</div>`)
370
+ return htmlNode(
371
+ html`<div class="wb-unknown" data-directive="${node.name}">${labelHtml}${raw(await toHtml(children))}</div>`,
372
+ )
302
373
  }
303
374
  const labelHtml = label ? await toHtml(label) : null
304
375
  let defaults: Promise<Record<string, unknown>> | undefined
@@ -312,10 +383,17 @@ export async function renderMarkdown(source: string | MdNode, { page, file, reso
312
383
  children,
313
384
  node,
314
385
  sections: () => sectionsOf(children),
315
- defaults: () => (defaults ??= (async () => {
316
- const content = await toHtml(children)
317
- return { name: node.name, attrs: { ...node.attributes }, label: labelHtml, html: content, ...(await sectionsOf(children)) }
318
- })()),
386
+ defaults: () =>
387
+ (defaults ??= (async () => {
388
+ const content = await toHtml(children)
389
+ return {
390
+ name: node.name,
391
+ attrs: { ...node.attributes },
392
+ label: labelHtml,
393
+ html: content,
394
+ ...(await sectionsOf(children)),
395
+ }
396
+ })()),
319
397
  }
320
398
  return htmlNode(await run(block, ctx, () => toHtml(children)))
321
399
  }
@@ -359,6 +437,7 @@ export async function renderMarkdown(source: string | MdNode, { page, file, reso
359
437
  const title = h1 ? toString(h1 as any) : null
360
438
  await transform(tree)
361
439
  const out = stringify(tree.children ?? [])
362
- const styles = [...used.values()].map(t => t.style).filter((s): s is string => !!s)
440
+ // blocks of one plugin can share a stylesheet (the form and its fields): linked once
441
+ const styles = [...new Set([...used.values()].map(t => t.style).filter((s): s is string => !!s))]
363
442
  return { html: out, title, islands, styles }
364
443
  }