@djangocfg/ui-tools 2.1.297 → 2.1.299

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 (28) hide show
  1. package/README.md +126 -2
  2. package/dist/{DocsLayout-3HNAQQRE.mjs → DocsLayout-MWRKNFXR.mjs} +3 -3
  3. package/dist/{DocsLayout-3HNAQQRE.mjs.map → DocsLayout-MWRKNFXR.mjs.map} +1 -1
  4. package/dist/{DocsLayout-O4ONSD67.cjs → DocsLayout-NWJUF42A.cjs} +48 -48
  5. package/dist/{DocsLayout-O4ONSD67.cjs.map → DocsLayout-NWJUF42A.cjs.map} +1 -1
  6. package/dist/{chunk-DKJTH4GE.mjs → chunk-CKD7GNE5.mjs} +236 -186
  7. package/dist/chunk-CKD7GNE5.mjs.map +1 -0
  8. package/dist/{chunk-QTO5LWMK.cjs → chunk-SEXWBCLX.cjs} +272 -221
  9. package/dist/chunk-SEXWBCLX.cjs.map +1 -0
  10. package/dist/index.cjs +13 -9
  11. package/dist/index.d.cts +82 -59
  12. package/dist/index.d.ts +82 -59
  13. package/dist/index.mjs +4 -4
  14. package/package.json +6 -6
  15. package/src/components/markdown/MarkdownMessage/CodeBlock.tsx +69 -0
  16. package/src/components/markdown/MarkdownMessage/CollapseToggle.tsx +60 -0
  17. package/src/components/markdown/MarkdownMessage/MarkdownMessage.story.tsx +171 -0
  18. package/src/components/markdown/MarkdownMessage/MarkdownMessage.tsx +202 -0
  19. package/src/components/markdown/MarkdownMessage/components.tsx +154 -0
  20. package/src/components/markdown/MarkdownMessage/index.ts +13 -0
  21. package/src/components/markdown/MarkdownMessage/linkRules.ts +83 -0
  22. package/src/components/markdown/MarkdownMessage/plainText.ts +50 -0
  23. package/src/components/markdown/MarkdownMessage/sanitize.ts +78 -0
  24. package/src/components/markdown/MarkdownMessage/types.ts +104 -0
  25. package/src/components/markdown/index.ts +6 -1
  26. package/dist/chunk-DKJTH4GE.mjs.map +0 -1
  27. package/dist/chunk-QTO5LWMK.cjs.map +0 -1
  28. package/src/components/markdown/MarkdownMessage.tsx +0 -686
@@ -1,686 +0,0 @@
1
- 'use client';
2
-
3
- import React from 'react';
4
- import ReactMarkdown from 'react-markdown';
5
- import rehypeRaw from 'rehype-raw';
6
- import rehypeSanitize, { defaultSchema } from 'rehype-sanitize';
7
- import remarkGfm from 'remark-gfm';
8
-
9
- // Allow-list HTML that OpenAPI descriptions commonly use — we want
10
- // ``<b>``/``<code>``/``<br>`` to render, not to appear as literal text.
11
- // Built on top of ``rehype-sanitize``'s default schema so we keep the
12
- // XSS protection (no ``<script>``, no ``on*`` handlers, no ``javascript:``
13
- // URLs); we just extend the tag allow-list with safe presentational
14
- // elements that are in wide use in API docs.
15
- const HTML_SCHEMA_BASE = {
16
- ...defaultSchema,
17
- tagNames: [
18
- ...(defaultSchema.tagNames ?? []),
19
- 'br',
20
- 'b',
21
- 'i',
22
- 'u',
23
- 's',
24
- 'sub',
25
- 'sup',
26
- 'small',
27
- 'mark',
28
- 'kbd',
29
- 'code',
30
- 'pre',
31
- 'details',
32
- 'summary',
33
- ],
34
- };
35
-
36
- // Build a sanitize schema with extra href-URL protocols allowed on
37
- // `<a>`. The default schema only lets `http(s)/mailto/xmpp/irc(s)`
38
- // through; consumers that emit custom URI schemes (e.g. `cmdop://`,
39
- // `obsidian://`, `vscode://`) need to opt them in so their custom
40
- // link renderer actually receives the href instead of `undefined`.
41
- function buildSchema(extraProtocols: readonly string[] | undefined) {
42
- if (!extraProtocols || extraProtocols.length === 0) return HTML_SCHEMA_BASE;
43
- const baseProtocols = (HTML_SCHEMA_BASE as { protocols?: Record<string, string[]> }).protocols
44
- ?? (defaultSchema as { protocols?: Record<string, string[]> }).protocols
45
- ?? {};
46
- const baseHref = baseProtocols.href ?? ['http', 'https', 'mailto', 'xmpp', 'irc', 'ircs'];
47
- return {
48
- ...HTML_SCHEMA_BASE,
49
- protocols: {
50
- ...baseProtocols,
51
- href: [...baseHref, ...extraProtocols],
52
- },
53
- };
54
- }
55
-
56
- import { CopyButton } from '@djangocfg/ui-core/components';
57
- import { useResolvedTheme } from '@djangocfg/ui-core/hooks';
58
-
59
- import Mermaid from '../../tools/Mermaid';
60
- import PrettyCode from '../../tools/PrettyCode';
61
- import { useCollapsibleContent } from './useCollapsibleContent';
62
-
63
- import type { Components } from 'react-markdown';
64
-
65
- // Helper function to extract text content from React children
66
- const extractTextFromChildren = (children: React.ReactNode): string => {
67
- if (typeof children === 'string') {
68
- return children;
69
- }
70
-
71
- if (typeof children === 'number') {
72
- return String(children);
73
- }
74
-
75
- if (React.isValidElement(children)) {
76
- const props = children.props as { children?: React.ReactNode };
77
- return extractTextFromChildren(props.children);
78
- }
79
-
80
- if (Array.isArray(children)) {
81
- return children.map(extractTextFromChildren).join('');
82
- }
83
-
84
- return '';
85
- };
86
-
87
- export interface MarkdownMessageProps {
88
- /** Markdown content to render */
89
- content: string;
90
- /** Additional CSS classes */
91
- className?: string;
92
- /** Whether the message is from the user (affects styling) */
93
- isUser?: boolean;
94
- /** Use compact size (text-xs instead of text-sm) */
95
- isCompact?: boolean;
96
- /**
97
- * Per-tag overrides merged on top of the built-in renderers.
98
- *
99
- * Use this when you need custom rendering for a specific tag without
100
- * losing the chat-tuned defaults (links, code blocks with copy, etc).
101
- * Example — render `cmdop://machine/<uuid>` links as a chip:
102
- *
103
- * ```tsx
104
- * <MarkdownMessage
105
- * content={text}
106
- * extraHrefProtocols={['cmdop']}
107
- * customComponents={{
108
- * a: ({ href, children }) =>
109
- * href?.startsWith('cmdop://machine/')
110
- * ? <MachineChip href={href}>{children}</MachineChip>
111
- * : <a href={href}>{children}</a>,
112
- * }}
113
- * />
114
- * ```
115
- *
116
- * If you provide a renderer for a tag the built-in version is replaced
117
- * for that tag; other tags keep the defaults.
118
- *
119
- * Important: when `customComponents` is set, the plain-text fast path
120
- * is bypassed for the affected content so your renderers always run.
121
- */
122
- customComponents?: Partial<Components>;
123
- /**
124
- * Extra URL protocols allowed in `<a href>` after sanitize.
125
- *
126
- * The default schema strips anything that isn't
127
- * `http(s)/mailto/xmpp/irc(s)` — your custom renderer would receive
128
- * `href={undefined}` for `cmdop://…` / `obsidian://…` etc. Listing
129
- * the bare scheme here (e.g. `'cmdop'`, NOT `'cmdop://'`) opts it in.
130
- *
131
- * Use carefully: every protocol you add increases what the rendered
132
- * HTML can do via clicks. Stick to schemes you control.
133
- */
134
- extraHrefProtocols?: readonly string[];
135
- /**
136
- * Enable collapsible "Read more..." functionality
137
- * When enabled, long content will be truncated with a toggle button
138
- * @default false
139
- */
140
- collapsible?: boolean;
141
- /**
142
- * Maximum character length before showing "Read more..."
143
- * Only applies when collapsible is true
144
- * If both maxLength and maxLines are set, the stricter limit applies
145
- */
146
- maxLength?: number;
147
- /**
148
- * Maximum number of lines before showing "Read more..."
149
- * Only applies when collapsible is true
150
- * If both maxLength and maxLines are set, the stricter limit applies
151
- */
152
- maxLines?: number;
153
- /**
154
- * Custom "Read more" button text
155
- * @default "Read more..."
156
- */
157
- readMoreLabel?: string;
158
- /**
159
- * Custom "Show less" button text
160
- * @default "Show less"
161
- */
162
- showLessLabel?: string;
163
- /**
164
- * Start expanded (only applies when collapsible is true)
165
- * @default false
166
- */
167
- defaultExpanded?: boolean;
168
- /**
169
- * Callback when collapsed state changes
170
- */
171
- onCollapseChange?: (isCollapsed: boolean) => void;
172
- }
173
-
174
- // Code block component with copy functionality
175
- interface CodeBlockProps {
176
- code: string;
177
- language: string;
178
- isUser: boolean;
179
- isCompact?: boolean;
180
- }
181
-
182
- const CodeBlock: React.FC<CodeBlockProps> = ({ code, language, isUser, isCompact = false }) => {
183
- const theme = useResolvedTheme();
184
-
185
- return (
186
- <div className="relative group my-3">
187
- {/* Copy button */}
188
- <CopyButton
189
- value={code}
190
- variant="ghost"
191
- className={`
192
- absolute top-2 right-2 z-10 opacity-0 group-hover:opacity-100 transition-opacity
193
- h-8 w-8
194
- ${isUser
195
- ? 'hover:bg-white/20 text-white'
196
- : 'hover:bg-muted-foreground/20 text-muted-foreground hover:text-foreground'
197
- }
198
- `}
199
- title="Copy code"
200
- />
201
-
202
- {/* Code content */}
203
- <PrettyCode
204
- data={code}
205
- language={language}
206
- className={isCompact ? 'text-xs' : 'text-sm'}
207
- customBg={isUser ? "bg-white/10" : "bg-muted dark:bg-muted"}
208
- mode={theme}
209
- isCompact={isCompact}
210
- />
211
- </div>
212
- );
213
- };
214
-
215
- // Custom components for markdown in chat
216
- // Base size: text-sm (14px) for normal, text-xs (12px) for compact
217
- const createMarkdownComponents = (isUser: boolean = false, isCompact: boolean = false): Components => {
218
- // Text size classes based on compact mode
219
- const textSize = isCompact ? 'text-xs' : 'text-sm';
220
- const headingBase = isCompact ? 'text-sm' : 'text-base';
221
- const headingSm = isCompact ? 'text-xs' : 'text-sm';
222
-
223
- return {
224
- // Headings - scaled for chat context
225
- h1: ({ children }) => (
226
- <h1 className={`${headingBase} font-bold mb-2 mt-3 first:mt-0`}>{children}</h1>
227
- ),
228
- h2: ({ children }) => (
229
- <h2 className={`${headingSm} font-bold mb-2 mt-3 first:mt-0`}>{children}</h2>
230
- ),
231
- h3: ({ children }) => (
232
- <h3 className={`${headingSm} font-semibold mb-1 mt-2 first:mt-0`}>{children}</h3>
233
- ),
234
- h4: ({ children }) => (
235
- <h4 className={`${headingSm} font-semibold mb-1 mt-2 first:mt-0`}>{children}</h4>
236
- ),
237
- h5: ({ children }) => (
238
- <h5 className={`${headingSm} font-medium mb-1 mt-2 first:mt-0`}>{children}</h5>
239
- ),
240
- h6: ({ children }) => (
241
- <h6 className={`${headingSm} font-medium mb-1 mt-2 first:mt-0`}>{children}</h6>
242
- ),
243
-
244
- // Paragraphs - optimized for chat readability
245
- p: ({ children }) => (
246
- <p className={`${textSize} mb-4 last:mb-0 leading-7 break-words font-light`}>{children}</p>
247
- ),
248
-
249
- // Lists - compact
250
- ul: ({ children }) => (
251
- <ul className={`list-disc list-inside mb-2 space-y-1 ${textSize}`}>{children}</ul>
252
- ),
253
- ol: ({ children }) => (
254
- <ol className={`list-decimal list-inside mb-2 space-y-1 ${textSize}`}>{children}</ol>
255
- ),
256
- li: ({ children }) => (
257
- <li className="break-words">{children}</li>
258
- ),
259
-
260
- // Links - appropriate for chat context
261
- a: ({ href, children }) => (
262
- <a
263
- href={href}
264
- className={`${textSize} ${
265
- isUser
266
- ? 'text-white/90 underline hover:text-white'
267
- : 'text-primary underline hover:text-primary/80'
268
- } transition-colors break-all`}
269
- target={href?.startsWith('http') ? '_blank' : undefined}
270
- rel={href?.startsWith('http') ? 'noopener noreferrer' : undefined}
271
- >
272
- {children}
273
- </a>
274
- ),
275
-
276
- // Code blocks - using CodeBlock component with copy functionality
277
- pre: ({ children }) => {
278
- // Extract code content and language
279
- let codeContent = '';
280
- let language = 'plaintext';
281
-
282
- if (React.isValidElement(children)) {
283
- const child = children;
284
-
285
- if (child.type === 'code' || (typeof child.type === 'function' && child.type.name === 'code')) {
286
- const codeProps = child.props as { className?: string; children?: React.ReactNode };
287
- const rawClassName = codeProps.className;
288
- language = rawClassName?.replace(/language-/, '').trim() || 'plaintext';
289
- codeContent = extractTextFromChildren(codeProps.children).trim();
290
- } else {
291
- codeContent = extractTextFromChildren(children).trim();
292
- }
293
- } else {
294
- codeContent = extractTextFromChildren(children).trim();
295
- }
296
-
297
- // If still no content, show placeholder
298
- if (!codeContent) {
299
- return (
300
- <div className="my-3 p-3 bg-muted rounded text-sm text-muted-foreground">
301
- No content available
302
- </div>
303
- );
304
- }
305
-
306
- // Handle Mermaid diagrams separately
307
- if (language === 'mermaid') {
308
- return (
309
- <div className="my-3 max-w-full overflow-x-auto">
310
- <Mermaid chart={codeContent} className="max-w-[600px] mx-auto" isCompact={isCompact} />
311
- </div>
312
- );
313
- }
314
-
315
- // Try to use CodeBlock component, fallback to simple pre if it fails
316
- try {
317
- return <CodeBlock code={codeContent} language={language} isUser={isUser} isCompact={isCompact} />;
318
- } catch (error) {
319
- // Fallback to simple pre element with copy button
320
- console.warn('CodeBlock failed, using fallback:', error);
321
- return (
322
- <div className="relative group my-3">
323
- <CopyButton
324
- value={codeContent}
325
- variant="ghost"
326
- className={`
327
- absolute top-2 right-2 z-10 opacity-0 group-hover:opacity-100 transition-opacity
328
- h-8 w-8
329
- ${isUser
330
- ? 'hover:bg-white/20 text-white'
331
- : 'hover:bg-muted-foreground/20 text-muted-foreground hover:text-foreground'
332
- }
333
- `}
334
- title="Copy code"
335
- />
336
- <pre className={`
337
- p-3 rounded text-xs font-mono overflow-x-auto
338
- ${isUser
339
- ? 'bg-white/10 text-white'
340
- : 'bg-muted text-foreground'
341
- }
342
- `}>
343
- <code>{codeContent}</code>
344
- </pre>
345
- </div>
346
- );
347
- }
348
- },
349
-
350
- // Inline code
351
- code: ({ children, className }) => {
352
- // If it's inside a pre tag, let pre handle it
353
- if (className?.includes('language-')) {
354
- return <code className={className}>{children}</code>;
355
- }
356
-
357
- // Extract text content safely
358
- const codeContent = extractTextFromChildren(children);
359
-
360
- // Inline code styling
361
- return (
362
- <code className="px-1.5 py-0.5 rounded text-xs font-mono bg-muted text-foreground break-all">
363
- {codeContent}
364
- </code>
365
- );
366
- },
367
-
368
- // Blockquotes
369
- blockquote: ({ children }) => (
370
- <blockquote className={`${textSize} border-l-2 border-border pl-3 my-2 italic text-muted-foreground break-words`}>
371
- {children}
372
- </blockquote>
373
- ),
374
-
375
- // Tables - compact for chat
376
- table: ({ children }) => (
377
- <div className="overflow-x-auto my-3">
378
- <table className={`min-w-full ${textSize} border-collapse`}>
379
- {children}
380
- </table>
381
- </div>
382
- ),
383
- thead: ({ children }) => (
384
- <thead className="bg-muted/50">
385
- {children}
386
- </thead>
387
- ),
388
- tbody: ({ children }) => (
389
- <tbody>{children}</tbody>
390
- ),
391
- tr: ({ children }) => (
392
- <tr className="border-b border-border/50">{children}</tr>
393
- ),
394
- th: ({ children }) => (
395
- <th className="px-2 py-1 text-left font-medium break-words">{children}</th>
396
- ),
397
- td: ({ children }) => (
398
- <td className="px-2 py-1 break-words">{children}</td>
399
- ),
400
-
401
- // Horizontal rule
402
- hr: () => (
403
- <hr className="my-3 border-0 h-px bg-border" />
404
- ),
405
-
406
- // Strong and emphasis
407
- strong: ({ children }) => (
408
- <strong className="font-semibold">{children}</strong>
409
- ),
410
- em: ({ children }) => (
411
- <em className="italic">{children}</em>
412
- ),
413
- };};
414
-
415
- // Check if content contains markdown syntax or line breaks
416
- const hasMarkdownSyntax = (text: string): boolean => {
417
- // If there are line breaks (after trim), treat as markdown for proper paragraph rendering
418
- if (text.trim().includes('\n')) {
419
- return true;
420
- }
421
-
422
- // Inline HTML tags (``<br>``, ``<b>``, ``<code>``, …) — used widely
423
- // in OpenAPI descriptions. Without this branch the plain-text fast
424
- // path would escape them and the user sees literal angle brackets.
425
- // The regex matches opening, closing, and self-closing tags without
426
- // being too clever about malformed HTML; it's an affordance test,
427
- // not a validator.
428
- if (/<\/?[a-zA-Z][a-zA-Z0-9-]*(\s[^>]*)?\/?>/.test(text)) {
429
- return true;
430
- }
431
-
432
- // Common markdown patterns
433
- const markdownPatterns = [
434
- /^#{1,6}\s/m, // Headers
435
- /\*\*[^*]+\*\*/, // Bold
436
- /\*[^*]+\*/, // Italic
437
- /__[^_]+__/, // Bold (underscore)
438
- /_[^_]+_/, // Italic (underscore)
439
- /\[.+\]\(.+\)/, // Links
440
- /!\[.*\]\(.+\)/, // Images
441
- /```[\s\S]*```/, // Code blocks
442
- /`[^`]+`/, // Inline code
443
- /^\s*[-*+]\s/m, // Unordered lists
444
- /^\s*\d+\.\s/m, // Ordered lists
445
- /^\s*>/m, // Blockquotes
446
- /\|.+\|/, // Tables
447
- /^---+$/m, // Horizontal rules
448
- /~~[^~]+~~/, // Strikethrough
449
- ];
450
-
451
- return markdownPatterns.some(pattern => pattern.test(text));
452
- };
453
-
454
- /**
455
- * Read more / Show less toggle button
456
- */
457
- interface CollapseToggleProps {
458
- isCollapsed: boolean;
459
- onClick: () => void;
460
- readMoreLabel: string;
461
- showLessLabel: string;
462
- isUser: boolean;
463
- isCompact: boolean;
464
- }
465
-
466
- const CollapseToggle: React.FC<CollapseToggleProps> = ({
467
- isCollapsed,
468
- onClick,
469
- readMoreLabel,
470
- showLessLabel,
471
- isUser,
472
- isCompact,
473
- }) => {
474
- const textSize = isCompact ? 'text-xs' : 'text-sm';
475
-
476
- return (
477
- <button
478
- type="button"
479
- onClick={onClick}
480
- className={`
481
- ${textSize} font-medium cursor-pointer
482
- transition-colors duration-200
483
- ${isUser
484
- ? 'text-white/80 hover:text-white'
485
- : 'text-primary hover:text-primary/80'
486
- }
487
- inline-flex items-center gap-1
488
- mt-1
489
- `}
490
- >
491
- {isCollapsed ? (
492
- <>
493
- {readMoreLabel}
494
- <svg
495
- className="w-3 h-3"
496
- fill="none"
497
- stroke="currentColor"
498
- viewBox="0 0 24 24"
499
- >
500
- <path
501
- strokeLinecap="round"
502
- strokeLinejoin="round"
503
- strokeWidth={2}
504
- d="M19 9l-7 7-7-7"
505
- />
506
- </svg>
507
- </>
508
- ) : (
509
- <>
510
- {showLessLabel}
511
- <svg
512
- className="w-3 h-3"
513
- fill="none"
514
- stroke="currentColor"
515
- viewBox="0 0 24 24"
516
- >
517
- <path
518
- strokeLinecap="round"
519
- strokeLinejoin="round"
520
- strokeWidth={2}
521
- d="M5 15l7-7 7 7"
522
- />
523
- </svg>
524
- </>
525
- )}
526
- </button>
527
- );
528
- };
529
-
530
- /**
531
- * MarkdownMessage - Renders markdown content with syntax highlighting and GFM support
532
- *
533
- * Features:
534
- * - GitHub Flavored Markdown (GFM) support
535
- * - Syntax highlighted code blocks with copy button
536
- * - Mermaid diagram rendering
537
- * - Tables, lists, blockquotes
538
- * - User/assistant styling modes
539
- * - Plain text optimization (skips ReactMarkdown for simple text)
540
- * - Collapsible "Read more..." for long messages
541
- *
542
- * @example
543
- * ```tsx
544
- * <MarkdownMessage content="# Hello\n\nThis is **bold** text." />
545
- *
546
- * // User message styling
547
- * <MarkdownMessage content="Some content" isUser />
548
- *
549
- * // Collapsible long content (for chat apps)
550
- * <MarkdownMessage
551
- * content={longText}
552
- * collapsible
553
- * maxLength={300}
554
- * maxLines={5}
555
- * />
556
- * ```
557
- */
558
- export const MarkdownMessage: React.FC<MarkdownMessageProps> = ({
559
- content,
560
- className = "",
561
- isUser = false,
562
- isCompact = false,
563
- customComponents,
564
- extraHrefProtocols,
565
- collapsible = false,
566
- maxLength,
567
- maxLines,
568
- readMoreLabel = "Read more...",
569
- showLessLabel = "Show less",
570
- defaultExpanded = false,
571
- onCollapseChange,
572
- }) => {
573
- // Trim content to remove leading/trailing whitespace and empty lines
574
- const trimmedContent = content.trim();
575
-
576
- // Collapsible content logic - use defaults when collapsible is enabled
577
- const collapsibleOptions = React.useMemo(() => {
578
- if (!collapsible) return {};
579
- // Default limits when collapsible is enabled but no limits specified
580
- const effectiveMaxLength = maxLength ?? 1000;
581
- const effectiveMaxLines = maxLines ?? 10;
582
- return { maxLength: effectiveMaxLength, maxLines: effectiveMaxLines, defaultExpanded };
583
- }, [collapsible, maxLength, maxLines, defaultExpanded]);
584
-
585
- const {
586
- isCollapsed,
587
- toggleCollapsed,
588
- displayContent,
589
- shouldCollapse,
590
- } = useCollapsibleContent(
591
- trimmedContent,
592
- collapsible ? collapsibleOptions : {}
593
- );
594
-
595
- // Call onCollapseChange when state changes
596
- React.useEffect(() => {
597
- if (collapsible && shouldCollapse && onCollapseChange) {
598
- onCollapseChange(isCollapsed);
599
- }
600
- }, [isCollapsed, collapsible, shouldCollapse, onCollapseChange]);
601
-
602
- const components = React.useMemo(() => {
603
- const base = createMarkdownComponents(isUser, isCompact);
604
- return customComponents ? { ...base, ...customComponents } : base;
605
- }, [isUser, isCompact, customComponents]);
606
-
607
- const schema = React.useMemo(() => buildSchema(extraHrefProtocols), [extraHrefProtocols]);
608
-
609
- const textSizeClass = isCompact ? 'text-xs' : 'text-sm';
610
- const proseClass = isCompact ? 'prose-xs' : 'prose-sm';
611
-
612
- // For plain text without markdown, render directly without ReactMarkdown.
613
- // Skip the fast path when caller provided custom renderers — they may
614
- // need to fire on plain `[label](custom://…)` links that the fast path
615
- // would print verbatim.
616
- const isPlainText = !customComponents && !hasMarkdownSyntax(displayContent);
617
-
618
- // Render plain text - use CSS white-space: pre-line to preserve newlines
619
- if (isPlainText) {
620
- return (
621
- <span className={`${textSizeClass} leading-7 break-words whitespace-pre-line font-light ${className}`}>
622
- {displayContent}
623
- {collapsible && shouldCollapse && (
624
- <>
625
- {isCollapsed && '... '}
626
- <CollapseToggle
627
- isCollapsed={isCollapsed}
628
- onClick={toggleCollapsed}
629
- readMoreLabel={readMoreLabel}
630
- showLessLabel={showLessLabel}
631
- isUser={isUser}
632
- isCompact={isCompact}
633
- />
634
- </>
635
- )}
636
- </span>
637
- );
638
- }
639
-
640
- // Render markdown
641
- return (
642
- <div className={className}>
643
- <div
644
- className={`
645
- prose ${proseClass} max-w-none break-words overflow-hidden ${textSizeClass}
646
- ${isUser ? 'prose-invert' : 'dark:prose-invert'}
647
- [&>*]:leading-7
648
- `}
649
- style={{
650
- // Inherit colors from parent - fixes issues with external CSS variables
651
- '--tw-prose-body': 'inherit',
652
- '--tw-prose-headings': 'inherit',
653
- '--tw-prose-bold': 'inherit',
654
- '--tw-prose-links': 'inherit',
655
- color: 'inherit',
656
- } as React.CSSProperties}
657
- >
658
- <ReactMarkdown
659
- remarkPlugins={[remarkGfm]}
660
- // ``rehype-raw`` parses inline HTML in the source (OpenAPI
661
- // ``description`` fields often contain ``<br>`` / ``<b>`` /
662
- // ``<code>``). ``rehype-sanitize`` with our extended schema
663
- // runs after it so the allowed tags pass through while
664
- // anything risky (scripts, event handlers, javascript: urls)
665
- // is stripped.
666
- rehypePlugins={[rehypeRaw, [rehypeSanitize, schema]]}
667
- components={components}
668
- >
669
- {displayContent}
670
- </ReactMarkdown>
671
- </div>
672
- {collapsible && shouldCollapse && (
673
- <CollapseToggle
674
- isCollapsed={isCollapsed}
675
- onClick={toggleCollapsed}
676
- readMoreLabel={readMoreLabel}
677
- showLessLabel={showLessLabel}
678
- isUser={isUser}
679
- isCompact={isCompact}
680
- />
681
- )}
682
- </div>
683
- );
684
- };
685
-
686
- export default MarkdownMessage;