@dxos/react-ui-markdown 0.8.4-main.d05673bc65 → 0.8.4-main.d9fc60f731

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 (47) hide show
  1. package/LICENSE +102 -5
  2. package/dist/lib/browser/index.mjs +562 -10
  3. package/dist/lib/browser/index.mjs.map +4 -4
  4. package/dist/lib/browser/meta.json +1 -1
  5. package/dist/types/src/MarkdownStream/MarkdownStream.d.ts +101 -0
  6. package/dist/types/src/MarkdownStream/MarkdownStream.d.ts.map +1 -0
  7. package/dist/types/src/MarkdownStream/MarkdownStream.stories.d.ts +23 -0
  8. package/dist/types/src/MarkdownStream/MarkdownStream.stories.d.ts.map +1 -0
  9. package/dist/types/src/MarkdownStream/footer.d.ts +23 -0
  10. package/dist/types/src/MarkdownStream/footer.d.ts.map +1 -0
  11. package/dist/types/src/MarkdownStream/index.d.ts +4 -0
  12. package/dist/types/src/MarkdownStream/index.d.ts.map +1 -0
  13. package/dist/types/src/MarkdownStream/stream.d.ts +39 -0
  14. package/dist/types/src/MarkdownStream/stream.d.ts.map +1 -0
  15. package/dist/types/src/MarkdownStream/stream.test.d.ts +2 -0
  16. package/dist/types/src/MarkdownStream/stream.test.d.ts.map +1 -0
  17. package/dist/types/src/MarkdownStream/testing/index.d.ts +2 -0
  18. package/dist/types/src/MarkdownStream/testing/index.d.ts.map +1 -0
  19. package/dist/types/src/MarkdownStream/testing/testing.d.ts +16 -0
  20. package/dist/types/src/MarkdownStream/testing/testing.d.ts.map +1 -0
  21. package/dist/types/src/{MarkdownViewer/MarkdownViewer.d.ts → MarkdownView/MarkdownView.d.ts} +3 -3
  22. package/dist/types/src/MarkdownView/MarkdownView.d.ts.map +1 -0
  23. package/dist/types/src/{MarkdownViewer/MarkdownViewer.stories.d.ts → MarkdownView/MarkdownView.stories.d.ts} +4 -4
  24. package/dist/types/src/MarkdownView/MarkdownView.stories.d.ts.map +1 -0
  25. package/dist/types/src/MarkdownView/index.d.ts +2 -0
  26. package/dist/types/src/MarkdownView/index.d.ts.map +1 -0
  27. package/dist/types/src/index.d.ts +2 -1
  28. package/dist/types/src/index.d.ts.map +1 -1
  29. package/dist/types/tsconfig.tsbuildinfo +1 -1
  30. package/package.json +37 -33
  31. package/src/MarkdownStream/MarkdownStream.stories.tsx +215 -0
  32. package/src/MarkdownStream/MarkdownStream.tsx +442 -0
  33. package/src/MarkdownStream/footer.ts +119 -0
  34. package/src/MarkdownStream/index.ts +8 -0
  35. package/src/MarkdownStream/stream.test.ts +126 -0
  36. package/src/MarkdownStream/stream.ts +229 -0
  37. package/src/{MarkdownViewer → MarkdownStream/testing}/index.ts +1 -1
  38. package/src/MarkdownStream/testing/testing.ts +56 -0
  39. package/src/MarkdownStream/testing/text.md +67 -0
  40. package/src/{MarkdownViewer/MarkdownViewer.stories.tsx → MarkdownView/MarkdownView.stories.tsx} +10 -10
  41. package/src/{MarkdownViewer/MarkdownViewer.tsx → MarkdownView/MarkdownView.tsx} +31 -10
  42. package/src/MarkdownView/index.ts +5 -0
  43. package/src/index.ts +2 -1
  44. package/dist/types/src/MarkdownViewer/MarkdownViewer.d.ts.map +0 -1
  45. package/dist/types/src/MarkdownViewer/MarkdownViewer.stories.d.ts.map +0 -1
  46. package/dist/types/src/MarkdownViewer/index.d.ts +0 -2
  47. package/dist/types/src/MarkdownViewer/index.d.ts.map +0 -1
@@ -1,10 +1,11 @@
1
- // src/MarkdownViewer/MarkdownViewer.tsx
1
+ // src/MarkdownView/MarkdownView.tsx
2
2
  import React from "react";
3
3
  import ReactMarkdown from "react-markdown";
4
4
  import remarkGfm from "remark-gfm";
5
+ import { MediaPlayer } from "@dxos/react-ui";
5
6
  import { SyntaxHighlighter } from "@dxos/react-ui-syntax-highlighter";
6
7
  import { mx } from "@dxos/ui-theme";
7
- var MarkdownViewer = ({ classNames, children, components, content = "" }) => {
8
+ var MarkdownView = ({ classNames, children, components, content = "" }) => {
8
9
  return /* @__PURE__ */ React.createElement("div", {
9
10
  className: mx(classNames)
10
11
  }, /* @__PURE__ */ React.createElement(ReactMarkdown, {
@@ -21,21 +22,26 @@ var MarkdownViewer = ({ classNames, children, components, content = "" }) => {
21
22
  var defaultComponents = {
22
23
  h1: ({ children }) => {
23
24
  return /* @__PURE__ */ React.createElement("h1", {
24
- className: "pt-1 pb-1 text-xl"
25
+ className: "pt-1 pb-1 text-accent-text text-xl"
25
26
  }, children);
26
27
  },
27
28
  h2: ({ children }) => {
28
29
  return /* @__PURE__ */ React.createElement("h2", {
29
- className: "pt-1 pb-1 text-lg"
30
+ className: "pt-1 pb-1 text-accent-text text-lg"
30
31
  }, children);
31
32
  },
32
33
  h3: ({ children }) => {
33
34
  return /* @__PURE__ */ React.createElement("h3", {
34
- className: "pt-1 pb-1 text-base"
35
+ className: "pt-1 pb-1 text-accent-text text-base"
36
+ }, children);
37
+ },
38
+ h4: ({ children }) => {
39
+ return /* @__PURE__ */ React.createElement("h4", {
40
+ className: "pt-1 pb-1 uppercase text-base"
35
41
  }, children);
36
42
  },
37
43
  blockquote: ({ children, ...props }) => /* @__PURE__ */ React.createElement("blockquote", {
38
- className: "ps-4 mt-2 mb-2 pt-2 pb-2 border-l-4 border-accent-text text-accent-text",
44
+ className: "my-2 py-2 ps-4 border-l-4 border-accent-text text-accent-text",
39
45
  ...props
40
46
  }, children),
41
47
  p: ({ children }) => {
@@ -50,6 +56,23 @@ var defaultComponents = {
50
56
  rel: "noopener noreferrer",
51
57
  ...props
52
58
  }, children),
59
+ // Hide broken images: many markdown sources reference remote URLs that
60
+ // 404 or are blocked. Drop the element on load failure rather than
61
+ // leaving the browser's broken-image placeholder.
62
+ //
63
+ // Media URLs (mp4/mp3/etc. or legacy `iframe`-style embeds) are swapped to a
64
+ // native `<video>` / `<audio>` element by {@link MediaPlayer} so playable
65
+ // media in the source document renders inline.
66
+ img: ({ src, alt }) => {
67
+ if (!src) {
68
+ return null;
69
+ }
70
+ return /* @__PURE__ */ React.createElement(MediaPlayer, {
71
+ src,
72
+ alt,
73
+ classNames: "w-full"
74
+ });
75
+ },
53
76
  ol: ({ children, ...props }) => /* @__PURE__ */ React.createElement("ol", {
54
77
  className: "pt-1 pb-1 ps-6 leading-tight list-decimal",
55
78
  ...props
@@ -63,17 +86,546 @@ var defaultComponents = {
63
86
  ...props
64
87
  }, children),
65
88
  pre: ({ children }) => children,
66
- // TODO(burdon): Copy/paste button.
67
- code: ({ children, className }) => {
89
+ code: ({ children, className, node }) => {
68
90
  const [, language] = /language-(\w+)/.exec(className || "") || [];
91
+ const inline = !className && node?.position?.start.line === node?.position?.end.line;
92
+ if (inline) {
93
+ return /* @__PURE__ */ React.createElement("code", {
94
+ className: "rounded-xs bg-group-surface px-1 py-0.5 text-sm text-info-text"
95
+ }, children);
96
+ }
69
97
  return /* @__PURE__ */ React.createElement(SyntaxHighlighter, {
70
98
  language,
71
- classNames: "mt-2 mb-2 border border-separator rounded-xs text-sm bg-group-surface",
99
+ classNames: "mt-2 mb-2 p-2 border border-separator rounded-xs text-sm bg-group-surface",
100
+ copyButton: true,
72
101
  PreTag: "pre"
73
102
  }, children);
74
103
  }
75
104
  };
105
+
106
+ // src/MarkdownStream/stream.ts
107
+ import * as Effect from "effect/Effect";
108
+ import * as Stream from "effect/Stream";
109
+ import { Obj } from "@dxos/echo";
110
+ var renderObjectLink = (obj, block) => `${block ? "!" : ""}[${Obj.getLabel(obj)}](${Obj.getURI(obj)})`;
111
+ var createStreamer = (source, { chunkSize = "span", delayMs = 0 } = {}) => {
112
+ const subdivide = chunkSize === "span" ? (token) => [
113
+ token
114
+ ] : (token) => isXmlFragment(token) ? [
115
+ token
116
+ ] : splitTextSpan(token, chunkSize);
117
+ let stream = source.pipe(Stream.flatMap((chunk) => Stream.fromIterable(splitFragments(chunk).flatMap(subdivide))));
118
+ if (delayMs > 0) {
119
+ stream = stream.pipe(Stream.tap(() => Effect.sleep(`${delayMs} millis`)));
120
+ }
121
+ return stream;
122
+ };
123
+ var isXmlFragment = (token) => token.startsWith("<");
124
+ var splitTextSpan = (span, chunkSize) => {
125
+ if (chunkSize === "character") {
126
+ return [
127
+ ...span
128
+ ];
129
+ }
130
+ return span.match(/\s+|\S+/g) ?? [
131
+ span
132
+ ];
133
+ };
134
+ var OPENING_TAG_NAME = /^<([a-zA-Z][\w-]*)(?:\s[^>]*)?>/;
135
+ var splitFragments = (text) => {
136
+ const initialTokens = splitSpans(text);
137
+ const tokens = [];
138
+ let i = 0;
139
+ while (i < initialTokens.length) {
140
+ const token = initialTokens[i];
141
+ if (token.startsWith("<") && !token.startsWith("</") && !token.endsWith("/>")) {
142
+ const tagMatch = token.match(OPENING_TAG_NAME);
143
+ if (tagMatch) {
144
+ const tagName = tagMatch[1];
145
+ const closingTag = `</${tagName}>`;
146
+ let fragment = token;
147
+ let foundClosing = false;
148
+ let j = i + 1;
149
+ while (j < initialTokens.length) {
150
+ fragment += initialTokens[j];
151
+ if (initialTokens[j] === closingTag) {
152
+ foundClosing = true;
153
+ break;
154
+ }
155
+ j++;
156
+ }
157
+ if (foundClosing) {
158
+ tokens.push(fragment);
159
+ i = j + 1;
160
+ } else {
161
+ tokens.push(token);
162
+ i++;
163
+ }
164
+ } else {
165
+ tokens.push(token);
166
+ i++;
167
+ }
168
+ } else {
169
+ tokens.push(token);
170
+ i++;
171
+ }
172
+ }
173
+ return tokens;
174
+ };
175
+ var splitSpans = (text) => {
176
+ const spans = [];
177
+ let currentText = "";
178
+ let i = 0;
179
+ while (i < text.length) {
180
+ if (text[i] === "<") {
181
+ if (currentText) {
182
+ spans.push(currentText);
183
+ currentText = "";
184
+ }
185
+ const closeIndex = text.indexOf(">", i);
186
+ if (closeIndex !== -1) {
187
+ spans.push(text.slice(i, closeIndex + 1));
188
+ i = closeIndex + 1;
189
+ } else {
190
+ currentText = text.slice(i);
191
+ break;
192
+ }
193
+ } else {
194
+ currentText += text[i];
195
+ i++;
196
+ }
197
+ }
198
+ if (currentText) {
199
+ spans.push(currentText);
200
+ }
201
+ return spans;
202
+ };
203
+ var splitSentences = (text) => {
204
+ const sentenceRegex = /[^.!?]*[.!?]+(?:\s+|$)/g;
205
+ const sentences = [];
206
+ let lastIndex = 0;
207
+ let match;
208
+ while ((match = sentenceRegex.exec(text)) !== null) {
209
+ sentences.push(match[0]);
210
+ lastIndex = match.index + match[0].length;
211
+ }
212
+ if (lastIndex < text.length) {
213
+ const remaining = text.slice(lastIndex);
214
+ if (remaining) {
215
+ sentences.push(remaining);
216
+ }
217
+ }
218
+ if (sentences.length === 0 && text) {
219
+ sentences.push(text);
220
+ }
221
+ return sentences;
222
+ };
223
+
224
+ // src/MarkdownStream/testing/testing.ts
225
+ async function* textStream(text, options = {}) {
226
+ const { chunkDelay = 100, variance = 0.3, wordsPerChunk = 3 } = options;
227
+ const words = text.match(/\S+|\s+/g) || [];
228
+ let i = 0;
229
+ while (i < words.length) {
230
+ const chunkWords = [];
231
+ let wordCount = 0;
232
+ while (i < words.length && wordCount < wordsPerChunk) {
233
+ const word = words[i];
234
+ chunkWords.push(word);
235
+ if (word.trim()) {
236
+ wordCount++;
237
+ }
238
+ i++;
239
+ }
240
+ const chunk = chunkWords.join("");
241
+ yield chunk;
242
+ const varianceMultiplier = 1 + (Math.random() - 0.5) * variance * 2;
243
+ const delay = chunkDelay * varianceMultiplier;
244
+ await new Promise((resolve) => setTimeout(resolve, delay));
245
+ }
246
+ }
247
+
248
+ // src/MarkdownStream/MarkdownStream.tsx
249
+ import { EditorSelection, Transaction } from "@codemirror/state";
250
+ import * as Effect2 from "effect/Effect";
251
+ import * as Fiber from "effect/Fiber";
252
+ import * as Queue from "effect/Queue";
253
+ import * as Stream2 from "effect/Stream";
254
+ import React2, { forwardRef, useCallback, useEffect, useImperativeHandle, useRef, useState } from "react";
255
+ import { createPortal } from "react-dom";
256
+ import { addEventListener } from "@dxos/async";
257
+ import { runAndForwardErrors } from "@dxos/effect";
258
+ import { ErrorBoundary, useDynamicRef, useStateWithRef, useThemeContext } from "@dxos/react-ui";
259
+ import { useTextEditor } from "@dxos/react-ui-editor";
260
+ import { createBasicExtensions, createThemeExtensions, decorateMarkdown, extendedMarkdown, navigateNextEffect, navigatePreviousEffect, preview, scroller, crawlerLineEffect, fader, typewriter, typewriterBypass, xmlTagContextEffect, xmlTagResetEffect, xmlTagUpdateEffect, xmlTags, documentSlots, xmlFormatting, xmlBlockDecoration } from "@dxos/ui-editor";
261
+ import { mx as mx2 } from "@dxos/ui-theme";
262
+ import { isTruthy } from "@dxos/util";
263
+
264
+ // src/MarkdownStream/footer.ts
265
+ import { StateEffect, StateField } from "@codemirror/state";
266
+ import { Decoration, EditorView, WidgetType } from "@codemirror/view";
267
+ import { Domino } from "@dxos/ui";
268
+ import { typewriterDrainingEffect } from "@dxos/ui-editor";
269
+ var setFooterVisibleEffect = StateEffect.define();
270
+ var footer = (setRoot) => {
271
+ const widget = new FooterWidget(setRoot);
272
+ const buildSet = (length) => Decoration.set([
273
+ Decoration.widget({
274
+ widget,
275
+ block: true,
276
+ side: 1
277
+ }).range(length)
278
+ ]);
279
+ const field = StateField.define({
280
+ create: () => ({
281
+ wanted: false,
282
+ draining: false,
283
+ decorations: Decoration.none
284
+ }),
285
+ update: (state, tr) => {
286
+ let { wanted, draining, decorations } = state;
287
+ for (const effect of tr.effects) {
288
+ if (effect.is(setFooterVisibleEffect)) {
289
+ wanted = effect.value;
290
+ }
291
+ if (effect.is(typewriterDrainingEffect)) {
292
+ draining = effect.value;
293
+ }
294
+ }
295
+ const docLength = tr.state.doc.length;
296
+ const visible = wanted && !draining && docLength > 0;
297
+ const wasVisible = decorations.size > 0;
298
+ if (visible !== wasVisible) {
299
+ decorations = visible ? buildSet(docLength) : Decoration.none;
300
+ } else if (tr.docChanged && decorations.size > 0) {
301
+ decorations = decorations.map(tr.changes);
302
+ }
303
+ return {
304
+ wanted,
305
+ draining,
306
+ decorations
307
+ };
308
+ },
309
+ provide: (f) => EditorView.decorations.from(f, (state) => state.decorations)
310
+ });
311
+ return [
312
+ field
313
+ ];
314
+ };
315
+ var FooterWidget = class extends WidgetType {
316
+ _setRoot;
317
+ constructor(_setRoot) {
318
+ super(), this._setRoot = _setRoot;
319
+ }
320
+ // Singleton equality so CM keeps the same DOM element across decoration rebuilds —
321
+ // the React subtree portaled into it is not unmounted on every doc change.
322
+ eq(_other) {
323
+ return true;
324
+ }
325
+ ignoreEvent() {
326
+ return true;
327
+ }
328
+ toDOM() {
329
+ const inner = Domino.of("div").classNames("cm-stream-footer-content").style({
330
+ position: "absolute",
331
+ left: "0",
332
+ top: "0"
333
+ });
334
+ const el = Domino.of("div").classNames("cm-stream-footer").style({
335
+ position: "relative",
336
+ height: "0"
337
+ }).append(inner);
338
+ this._setRoot(inner.root);
339
+ return el.root;
340
+ }
341
+ destroy() {
342
+ this._setRoot(null);
343
+ }
344
+ };
345
+
346
+ // src/MarkdownStream/MarkdownStream.tsx
347
+ var MarkdownStream = /* @__PURE__ */ forwardRef(({ classNames, debug, content, options, registry, extensions, footer: footer2, onEvent }, forwardedRef) => {
348
+ const contentRef = useRef(content ?? "");
349
+ const [footerRoot, setFooterRoot] = useState(null);
350
+ const { parentRef, view, viewRef, widgets } = useMarkdownStreamTextEditor(contentRef, {
351
+ debug,
352
+ registry,
353
+ options,
354
+ extensions,
355
+ setFooterRoot: footer2 ? setFooterRoot : void 0
356
+ });
357
+ const footerVisible = !!footer2;
358
+ useEffect(() => {
359
+ view?.dispatch({
360
+ effects: setFooterVisibleEffect.of(footerVisible)
361
+ });
362
+ }, [
363
+ view,
364
+ footerVisible
365
+ ]);
366
+ const [queue, setQueue, queueRef] = useStateWithRef(Effect2.runSync(Queue.unbounded()));
367
+ const onReset = useCallback(async (text) => {
368
+ contentRef.current = text;
369
+ if (!viewRef.current) {
370
+ return;
371
+ }
372
+ viewRef.current.dispatch({
373
+ effects: [
374
+ xmlTagContextEffect.of(null),
375
+ xmlTagResetEffect.of(null)
376
+ ],
377
+ changes: [
378
+ {
379
+ from: 0,
380
+ to: viewRef.current.state.doc.length,
381
+ insert: text
382
+ }
383
+ ],
384
+ annotations: typewriterBypass.of(true),
385
+ selection: EditorSelection.cursor(text.length)
386
+ });
387
+ setQueue(Effect2.runSync(Queue.unbounded()));
388
+ }, [
389
+ contentRef,
390
+ viewRef,
391
+ setQueue
392
+ ]);
393
+ useImperativeHandle(forwardedRef, () => createMarkdownStreamController({
394
+ contentRef,
395
+ viewRef,
396
+ queueRef,
397
+ onReset
398
+ }), [
399
+ onReset
400
+ ]);
401
+ useEffect(() => {
402
+ if (!parentRef.current) {
403
+ return;
404
+ }
405
+ return addEventListener(parentRef.current, "click", (event) => {
406
+ const button = event.target.closest('[data-action="submit"]');
407
+ if (button?.getAttribute("data-action") === "submit") {
408
+ onEvent?.({
409
+ type: "submit",
410
+ value: button.getAttribute("data-value")
411
+ });
412
+ }
413
+ });
414
+ }, [
415
+ view,
416
+ parentRef,
417
+ onEvent
418
+ ]);
419
+ useMarkdownStreamQueue(view, queue, {
420
+ chunkSize: options?.streamCadence,
421
+ delayMs: options?.streamDelayMs
422
+ });
423
+ useEffect(() => {
424
+ return () => {
425
+ view?.destroy();
426
+ };
427
+ }, [
428
+ view
429
+ ]);
430
+ return /* @__PURE__ */ React2.createElement(React2.Fragment, null, /* @__PURE__ */ React2.createElement("div", {
431
+ className: mx2("dx-container", classNames),
432
+ ref: parentRef
433
+ }), /* @__PURE__ */ React2.createElement(ErrorBoundary, {
434
+ name: "markdown-stream"
435
+ }, widgets.map(({ Component, root, id, props }) => /* @__PURE__ */ React2.createElement("div", {
436
+ key: id
437
+ }, /* @__PURE__ */ createPortal(/* @__PURE__ */ React2.createElement(Component, {
438
+ view,
439
+ ...props
440
+ }), root))), footerRoot && footerVisible && /* @__PURE__ */ createPortal(footer2, footerRoot)));
441
+ });
442
+ var useMarkdownStreamTextEditor = (currentContent, { debug, registry, options, extensions: extraExtensions, setFooterRoot }) => {
443
+ const { themeMode } = useThemeContext();
444
+ const [widgets, setWidgets] = useState([]);
445
+ const { view, parentRef } = useTextEditor(() => {
446
+ const content = currentContent.current;
447
+ return {
448
+ initialValue: content,
449
+ selection: EditorSelection.cursor(content?.length ?? 0),
450
+ extensions: [
451
+ createBasicExtensions({
452
+ lineWrapping: true,
453
+ readOnly: true
454
+ }),
455
+ createThemeExtensions({
456
+ slots: documentSlots,
457
+ scrollbarThin: true,
458
+ syntaxHighlighting: true,
459
+ themeMode
460
+ }),
461
+ xmlFormatting({
462
+ skip: debug ? [] : [
463
+ "prompt"
464
+ ]
465
+ }),
466
+ !debug && [
467
+ extendedMarkdown({
468
+ registry
469
+ }),
470
+ decorateMarkdown({
471
+ // `dxn:` links/images are reference widgets owned by `preview()` (PreviewInlineWidget /
472
+ // PreviewBlockWidget). Skipping them here avoids `decorateMarkdown` adding a
473
+ // non-functional `LinkButton` anchor on top of the same node — e.g. for
474
+ // `[DXOS](dxn:echo:BNPMIBEDJLRIILYUYZVM6GT64VWI6WPPZ:01KQ889PZBRNHAEECV0ANFAYX7)`.
475
+ skip: (node) => (node.name === "Link" || node.name === "Image") && node.url.startsWith("dxn:")
476
+ }),
477
+ preview(),
478
+ // NOTE: An ancestor element must set `data-hue` so `.dx-panel` resolves to the user's
479
+ // hue tokens (see `packages/ui/ui-theme/src/css/components/panel.css`). Tailwind picks
480
+ // up these utility classes from this source file.
481
+ xmlBlockDecoration({
482
+ tag: "prompt",
483
+ lineClass: "cm-prompt-line my-8",
484
+ contentClass: "cm-prompt-bubble dx-panel px-2 py-1.5 box-decoration-clone rounded-sm [&_*]:text-inherit!",
485
+ hideTags: true
486
+ }),
487
+ xmlTags({
488
+ registry,
489
+ setWidgets,
490
+ bookmarks: [
491
+ "prompt"
492
+ ]
493
+ }),
494
+ scroller({
495
+ overScroll: 80,
496
+ autoScroll: options?.autoScroll
497
+ }),
498
+ options?.typewriter && typewriter({
499
+ cursor: options?.cursor,
500
+ streamingTags: new Set(Object.entries(registry ?? {}).filter(([, def]) => def.streaming).map(([tag]) => tag))
501
+ }),
502
+ options?.fader && fader(),
503
+ setFooterRoot && footer(setFooterRoot)
504
+ ].filter(isTruthy),
505
+ extraExtensions
506
+ ].filter(isTruthy)
507
+ };
508
+ }, [
509
+ themeMode,
510
+ registry,
511
+ debug,
512
+ options?.autoScroll,
513
+ options?.typewriter,
514
+ options?.cursor,
515
+ options?.fader,
516
+ extraExtensions
517
+ ]);
518
+ const viewRef = useDynamicRef(view);
519
+ return {
520
+ view,
521
+ viewRef,
522
+ parentRef,
523
+ widgets
524
+ };
525
+ };
526
+ var useMarkdownStreamQueue = (view, queue, streamerOptions) => {
527
+ const chunkSize = streamerOptions?.chunkSize;
528
+ const delayMs = streamerOptions?.delayMs;
529
+ useEffect(() => {
530
+ if (!view) {
531
+ return;
532
+ }
533
+ const fork = Stream2.fromQueue(queue).pipe((source) => createStreamer(source, {
534
+ chunkSize,
535
+ delayMs
536
+ }), Stream2.runForEach((text) => Effect2.sync(() => {
537
+ const scrollTop = view.scrollDOM.scrollTop;
538
+ view.dispatch({
539
+ changes: [
540
+ {
541
+ from: view.state.doc.length,
542
+ insert: text
543
+ }
544
+ ],
545
+ annotations: Transaction.remote.of(true),
546
+ scrollIntoView: false
547
+ });
548
+ requestAnimationFrame(() => {
549
+ view.scrollDOM.scrollTop = scrollTop;
550
+ });
551
+ })), Effect2.runFork);
552
+ return () => {
553
+ void runAndForwardErrors(Fiber.interrupt(fork));
554
+ };
555
+ }, [
556
+ view,
557
+ queue,
558
+ chunkSize,
559
+ delayMs
560
+ ]);
561
+ };
562
+ var createMarkdownStreamController = ({ contentRef, viewRef, queueRef, onReset }) => {
563
+ return {
564
+ get length() {
565
+ return viewRef.current?.state.doc.length;
566
+ },
567
+ /** Focus the editor. */
568
+ focus: () => {
569
+ viewRef.current?.focus();
570
+ },
571
+ /** Scroll to bottom. */
572
+ scrollToBottom: (behavior) => {
573
+ viewRef.current?.dispatch({
574
+ effects: crawlerLineEffect.of({
575
+ line: -1,
576
+ behavior
577
+ })
578
+ });
579
+ },
580
+ /** Navigate previous prompt. */
581
+ navigatePrevious: () => {
582
+ viewRef.current?.dispatch({
583
+ effects: navigatePreviousEffect.of()
584
+ });
585
+ },
586
+ /** Navigate next prompt. */
587
+ navigateNext: () => {
588
+ viewRef.current?.dispatch({
589
+ effects: navigateNextEffect.of()
590
+ });
591
+ },
592
+ /** Set the context for widgets (XML tags). */
593
+ setContext: (context) => {
594
+ viewRef.current?.dispatch({
595
+ effects: xmlTagContextEffect.of(context)
596
+ });
597
+ },
598
+ /** Reset document. */
599
+ setContent: onReset,
600
+ /** Append to queue (and stream). */
601
+ append: async (text) => {
602
+ contentRef.current += text;
603
+ if (text.length) {
604
+ const queue = queueRef.current;
605
+ if (queue) {
606
+ await runAndForwardErrors(Queue.offer(queue, text));
607
+ }
608
+ }
609
+ },
610
+ /** Update widget state. */
611
+ updateWidget: (id, value) => {
612
+ viewRef.current?.dispatch({
613
+ effects: xmlTagUpdateEffect.of({
614
+ id,
615
+ value
616
+ })
617
+ });
618
+ }
619
+ };
620
+ };
76
621
  export {
77
- MarkdownViewer
622
+ MarkdownStream,
623
+ MarkdownView,
624
+ createStreamer,
625
+ renderObjectLink,
626
+ splitFragments,
627
+ splitSentences,
628
+ splitSpans,
629
+ textStream
78
630
  };
79
631
  //# sourceMappingURL=index.mjs.map