Code
·
367 lines
·
7911 bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367# MarkdownStreamer
A lightweight, streaming Markdown parser that renders directly into the DOM — character by character, in real time. No dependencies, no build step.
> **Version:** md v4.0.1
> **Author:** Alphons van der Heijden
---
## How it works
`MarkdownStreamer` processes Markdown one character at a time. This makes it ideal for streaming output from an LLM or any character-based text source: the DOM is updated live as characters arrive, with no buffering of the full document required.
---
## Quick start
### Synchronous (instant render)
```html
<div id="output"></div>
<script src="md4.js"></script>
<script>
const el = document.getElementById('output');
const streamer = new MarkdownStreamer(el);
streamer.markdown('# Hello\n\nThis is **MarkdownStreamer**.');
streamer.finalize();
</script>
```
### Animated streaming
```html
<div id="output"></div>
<script src="md4.js"></script>
<script>
async function stream() {
const el = document.getElementById('output');
const streamer = new MarkdownStreamer(el);
streamer.setSpeed(80); // 1–100, higher = faster
await streamer.markdownasync('# Hello\n\nStreamed **word by word**...');
streamer.finalize();
}
stream();
</script>
```
### Stop mid-stream
```js
streamer.stop(); // halts markdownasync() immediately
```
---
## API
| Method | Description |
|---|---|
| `new MarkdownStreamer(rootEl)` | Create a new instance. Clears `rootEl` and attaches the parser. |
| `markdown(text)` | Render the full text synchronously (instant). |
| `markdownasync(text)` | Render the text asynchronously with animated streaming. Returns a `Promise`. |
| `finalize()` | Flush any remaining state and close open elements. Always call this after rendering. |
| `setSpeed(n)` | Set streaming speed (1–100). Controls the batch size and delay between frames. |
| `stop()` | Abort an in-progress `markdownasync()` call. |
### Real-world: LLM chat via Server-Sent Events
A common pattern is to stream LLM output chunk by chunk using the browser's `EventSource` API (SSE). Each incoming chunk is fed into `markdownasync()`. Because chunks arrive asynchronously and out of order, the calls are chained through a `Promise` so they are always processed sequentially.
```js
var streamer;
let eventSource = new EventSource('/api/Chat/Events');
// Chain incoming chunks so they are rendered in order
let processingPromise = Promise.resolve();
eventSource.onmessage = function (event) {
const text = event.data.replace(/\\n/g, '\n');
processingPromise = processingPromise.then(() => streamer.markdownasync(text));
};
```
When the user sends a message, a new `div` and `MarkdownStreamer` are created for the assistant reply, and `setSpeed()` is tuned for near-real-time output:
```js
async function sendMessage(text) {
// Render the user message instantly
const divUser = document.createElement('div');
divUser.classList.add('user');
const userStreamer = new MarkdownStreamer(divUser);
userStreamer.markdown(text);
userStreamer.finalize();
output.append(divUser);
// Prepare the assistant reply container
const divAssistant = document.createElement('div');
divAssistant.classList.add('assistant');
streamer = new MarkdownStreamer(divAssistant);
streamer.setSpeed(95); // near-real-time
output.append(divAssistant);
// POST to the API — SSE events will drive the streamer above
await fetch('/api/Chat/Say', { method: 'POST', body: JSON.stringify({ text }) });
}
```
Existing chat history (already complete messages) is rendered synchronously with `markdown()` + `finalize()`:
```js
function renderHistory(messages) {
messages.forEach(item => {
if (item.role === 'system') return;
const div = document.createElement('div');
div.classList.add(item.role); // 'user' or 'assistant'
const s = new MarkdownStreamer(div);
s.markdown(item.content);
s.finalize();
output.append(div);
});
}
```
**Key points:**
- Use **one `MarkdownStreamer` instance per message bubble** — do not reuse across messages.
- Chain `markdownasync()` calls via a `Promise` when chunks arrive concurrently.
- Use `markdown()` + `finalize()` for already-complete text (history, user input).
- `setSpeed(95)` gives smooth, near-real-time LLM output animation.
---
## Implemented Markdown features
### Headings
```markdown
# H1
## H2
### H3
#### H4
##### H5
###### H6
Setext H1
=========
Setext H2
---------
## Heading with closing hashes ##
```
### Inline formatting
| Syntax | Result |
|---|---|
| `**bold**` | **bold** |
| `*italic*` | *italic* |
| `__underline__` | underline |
| `~~strikethrough~~` | ~~strikethrough~~ |
| `==highlight==` | highlighted |
| `` `inline code` `` | `inline code` |
| `x^sup^` | superscript |
| `H~sub~` | subscript |
| `***bold italic***` | ***bold italic*** |
### Hard line breaks
```markdown
Line one (two trailing spaces)
Line two
Line one\
Line two
```
### Links
```markdown
[label](https://example.com)
[label](https://example.com "title")
<https://example.com> <!-- autolink -->
<info@example.com> <!-- email autolink -->
https://example.com <!-- bare URL (auto-detected) -->
[Google][ref] <!-- reference link -->
[Google] <!-- implicit reference link -->
[ref]: https://www.google.com "optional title"
```
### Images
```markdown

[](https://example.com)
```
### Blockquotes (nested)
```markdown
> Level 1
>
> > Level 2
> >
> > > Level 3
```
### Lists
**Unordered:**
```markdown
- Item A
- Item B
- Sub B1
- Sub B2
```
**Ordered:**
```markdown
1. First
2. Second
1. Sub 2a
3. Third
1) Alternative style
2) With parentheses
```
**Mixed:**
```markdown
- Fruit
1. Apple
2. Pear
```
### Task lists
```markdown
- [x] Done
- [ ] Open task
```
### Code blocks
**Fenced (backticks or tildes):**
````markdown
```javascript
function hello() { return 'world'; }
```
~~~css
body { color: red; }
~~~
~~~~
four-tilde fence
~~~~
````
**Indented (4 spaces):**
```markdown
this is a code block
indented by 4 spaces
```
### Tables
```markdown
| Left | Center | Right |
|:-------|:-------:|------:|
| a | b | 1 |
| **vet**| *cursief*| `code`|
```
Column alignment: `:---` left, `:---:` center, `---:` right.
### Horizontal rules
```markdown
---
***
_ _ _
- - -
```
### Definition lists
```markdown
Markdown
: A lightweight markup language
HTML
: HyperText Markup Language
: The structure language of the web
```
### Footnotes
```markdown
This has a footnote.[^1]
[^1]: Footnote text here.
```
### Abbreviations
```markdown
The HTML spec is used daily.
*[HTML]: HyperText Markup Language
```
Abbreviations are automatically wrapped in `<abbr title="...">` throughout the document.
### Raw HTML
Block-level HTML elements are passed through directly:
```markdown
<details>
<summary>Click to expand</summary>
Hidden content.
</details>
```
Inline HTML comments are also supported:
```markdown
before <!-- hidden --> after
```
### Backslash escapes
```markdown
\*not italic\* \`not code\` \[not a link\]
```
### HTML entities
Named and numeric entities are decoded:
```markdown
© & < > € — 😀
```
---
## File overview
| File | Description |
|---|---|
| `tests/md4.js` | The parser — include this in your page |
| `tests/md4.css` | Full stylesheet for rendered output (dark/light) |
| `tests/md4-light.css` | Light-theme-only stylesheet |
| `tests/md4.html` | Interactive demo with live streaming, speed control, and theme toggle |
| `tests/md4start.js` | Demo wiring (stream/stop buttons, theme toggle) |
---
## License
Copyright (c) 2025–2026, Alphons van der Heijden.
[https://github.com/alphons/MarkdownStreamer](https://github.com/alphons/MarkdownStreamer)