@dxos/react-ui-markdown 0.8.4-main.422d1c7879 → 0.8.4-main.43cb759274

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 +550 -4
  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 -30
  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} +6 -6
  41. package/src/{MarkdownViewer/MarkdownViewer.tsx → MarkdownView/MarkdownView.tsx} +20 -4
  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
package/LICENSE CHANGED
@@ -1,8 +1,105 @@
1
- MIT License
2
- Copyright (c) 2022 DXOS
1
+ # Functional Source License, Version 1.1, ALv2 Future License
3
2
 
4
- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
3
+ ## Abbreviation
5
4
 
6
- The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
5
+ FSL-1.1-Apache-2.0
7
6
 
8
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
7
+ ## Notice
8
+
9
+ Copyright 2026 DXOS
10
+
11
+ ## Terms and Conditions
12
+
13
+ ### Licensor ("We")
14
+
15
+ The party offering the Software under these Terms and Conditions.
16
+
17
+ ### The Software
18
+
19
+ The "Software" is each version of the software that we make available under
20
+ these Terms and Conditions, as indicated by our inclusion of these Terms and
21
+ Conditions with the Software.
22
+
23
+ ### License Grant
24
+
25
+ Subject to your compliance with this License Grant and the Patents,
26
+ Redistribution and Trademark clauses below, we hereby grant you the right to
27
+ use, copy, modify, create derivative works, publicly perform, publicly display
28
+ and redistribute the Software for any Permitted Purpose identified below.
29
+
30
+ ### Permitted Purpose
31
+
32
+ A Permitted Purpose is any purpose other than a Competing Use. A Competing Use
33
+ means making the Software available to others in a commercial product or
34
+ service that:
35
+
36
+ 1. substitutes for the Software;
37
+
38
+ 2. substitutes for any other product or service we offer using the Software
39
+ that exists as of the date we make the Software available; or
40
+
41
+ 3. offers the same or substantially similar functionality as the Software.
42
+
43
+ Permitted Purposes specifically include using the Software:
44
+
45
+ 1. for your internal use and access;
46
+
47
+ 2. for non-commercial education;
48
+
49
+ 3. for non-commercial research; and
50
+
51
+ 4. in connection with professional services that you provide to a licensee
52
+ using the Software in accordance with these Terms and Conditions.
53
+
54
+ ### Patents
55
+
56
+ To the extent your use for a Permitted Purpose would necessarily infringe our
57
+ patents, the license grant above includes a license under our patents. If you
58
+ make a claim against any party that the Software infringes or contributes to
59
+ the infringement of any patent, then your patent license to the Software ends
60
+ immediately.
61
+
62
+ ### Redistribution
63
+
64
+ The Terms and Conditions apply to all copies, modifications and derivatives of
65
+ the Software.
66
+
67
+ If you redistribute any copies, modifications or derivatives of the Software,
68
+ you must include a copy of or a link to these Terms and Conditions and not
69
+ remove any copyright notices provided in or with the Software.
70
+
71
+ ### Disclaimer
72
+
73
+ THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR
74
+ IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR
75
+ PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT.
76
+
77
+ IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO THE
78
+ SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES,
79
+ EVEN IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE.
80
+
81
+ ### Trademarks
82
+
83
+ Except for displaying the License Details and identifying us as the origin of
84
+ the Software, you have no right under these Terms and Conditions to use our
85
+ trademarks, trade names, service marks or product names.
86
+
87
+ ## Grant of Future License
88
+
89
+ We hereby irrevocably grant you an additional license to use the Software under
90
+ the Apache License, Version 2.0 that is effective on the second anniversary of
91
+ the date we make the Software available. On or after that date, you may use the
92
+ Software under the Apache License, Version 2.0, in which case the following
93
+ will apply:
94
+
95
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use
96
+ this file except in compliance with the License.
97
+
98
+ You may obtain a copy of the License at
99
+
100
+ http://www.apache.org/licenses/LICENSE-2.0
101
+
102
+ Unless required by applicable law or agreed to in writing, software distributed
103
+ under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
104
+ CONDITIONS OF ANY KIND, either express or implied. See the License for the
105
+ specific language governing permissions and limitations under the License.
@@ -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, {
@@ -34,8 +35,13 @@ var defaultComponents = {
34
35
  className: "pt-1 pb-1 text-accent-text text-base"
35
36
  }, children);
36
37
  },
38
+ h4: ({ children }) => {
39
+ return /* @__PURE__ */ React.createElement("h4", {
40
+ className: "pt-1 pb-1 uppercase text-base"
41
+ }, children);
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
@@ -79,7 +102,530 @@ var defaultComponents = {
79
102
  }, children);
80
103
  }
81
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
+ };
82
621
  export {
83
- MarkdownViewer
622
+ MarkdownStream,
623
+ MarkdownView,
624
+ createStreamer,
625
+ renderObjectLink,
626
+ splitFragments,
627
+ splitSentences,
628
+ splitSpans,
629
+ textStream
84
630
  };
85
631
  //# sourceMappingURL=index.mjs.map