@swisper.ai/web-chat-ui 0.4.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 (32) hide show
  1. package/dist/components/chat-notification-card/chat-notification-card.d.ts +11 -3
  2. package/dist/components/chat-notification-card/chat-notification-card.d.ts.map +1 -1
  3. package/dist/components/chat-notification-card/chat-notification-card.stories.d.ts +4 -0
  4. package/dist/components/chat-notification-card/chat-notification-card.stories.d.ts.map +1 -1
  5. package/dist/components/html-viewer/html-viewer.d.ts +18 -0
  6. package/dist/components/html-viewer/html-viewer.d.ts.map +1 -0
  7. package/dist/components/html-viewer/html-viewer.stories.d.ts +14 -0
  8. package/dist/components/html-viewer/html-viewer.stories.d.ts.map +1 -0
  9. package/dist/components/html-viewer/index.d.ts +3 -0
  10. package/dist/components/html-viewer/index.d.ts.map +1 -0
  11. package/dist/components/html-viewer/types.d.ts +7 -0
  12. package/dist/components/html-viewer/types.d.ts.map +1 -0
  13. package/dist/components/html-viewer/utils.d.ts +8 -0
  14. package/dist/components/html-viewer/utils.d.ts.map +1 -0
  15. package/dist/components/index.d.ts +1 -0
  16. package/dist/components/index.d.ts.map +1 -1
  17. package/dist/index.css +1 -1
  18. package/dist/index.es.js +1199 -1053
  19. package/dist/index.es.js.map +1 -1
  20. package/package.json +3 -1
  21. package/src/components/chat-notification-card/chat-notification-card.json +4 -1
  22. package/src/components/chat-notification-card/chat-notification-card.stories.tsx +82 -31
  23. package/src/components/chat-notification-card/chat-notification-card.tsx +20 -5
  24. package/src/components/chat-notification-popup/__stories__/notification-item.tsx +1 -1
  25. package/src/components/html-viewer/__tests__/html-viewer.spec.tsx +105 -0
  26. package/src/components/html-viewer/html-viewer.json +81 -0
  27. package/src/components/html-viewer/html-viewer.stories.tsx +118 -0
  28. package/src/components/html-viewer/html-viewer.tsx +134 -0
  29. package/src/components/html-viewer/index.ts +2 -0
  30. package/src/components/html-viewer/types.ts +8 -0
  31. package/src/components/html-viewer/utils.ts +58 -0
  32. package/src/components/index.ts +1 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@swisper.ai/web-chat-ui",
3
- "version": "0.4.1",
3
+ "version": "0.5.0",
4
4
  "description": "React components for the Swisper chat: messages, composer and cards",
5
5
  "keywords": [
6
6
  "react",
@@ -75,6 +75,7 @@
75
75
  "date-fns": "4.1.0",
76
76
  "date-fns-tz": "^3.2.0",
77
77
  "eventsource-parser": "^3.1.0",
78
+ "hast-util-to-jsx-runtime": "^2.3.6",
78
79
  "inline-style-parser": "^0.2.7",
79
80
  "katex": "^0.16.22",
80
81
  "lexical": "^0.46.0",
@@ -83,6 +84,7 @@
83
84
  "motion": "^12.23.22",
84
85
  "nanoid": "^5.1.16",
85
86
  "react-intersection-observer": "9.16.0",
87
+ "rehype-parse": "^9.0.1",
86
88
  "rehype-sanitize": "^6.0.0",
87
89
  "remark-gfm": "4.0.1",
88
90
  "remark-parse": "^11.0.0",
@@ -45,7 +45,7 @@
45
45
  " </ChatNotificationCardHead>",
46
46
  " <ChatNotificationCardContent>",
47
47
  " <ChatNotificationCardContentTitle />",
48
- " <ChatNotificationCardContentDescription />",
48
+ " <ChatNotificationCardContentDescription html={html} />",
49
49
  " <ChatNotificationCardContentActions />",
50
50
  " </ChatNotificationCardContent>",
51
51
  "</ChatNotificationCard>"
@@ -100,6 +100,8 @@
100
100
  "ChatNotificationCardSnoozeButton with snoozeUntilDate in the future renders a text button showing the time left (formatDate, 'in 2 minutes' by default); hovering swaps the text for cancelLabel and clicking calls onCancel. Otherwise it is an icon button that calls onClick. The snoozed check runs on render, so re-render when the time passes",
101
101
  "getSnoozeUntilDate(minutes) returns a Date that many minutes from now; formatSnoozeDate(date) formats the remaining days, hours and minutes",
102
102
  "ChatNotificationCardHeaderTitleLabel is semibold, uppercase and truncated to one line",
103
+ "ChatNotificationCardContentDescription takes the text as an HTML fragment in html (required; it has no children) and renders it through web-chat-ui/html-viewer: parsed, sanitised, and mapped through htmlComponents merged over the viewer's defaults. Links open in a new tab and do not fire the card's onClick",
104
+ "While collapsed, paragraphs and lists in the description lose their vertical margins and table parts render as display: inline-block, so the two-line clamp holds for email-style table HTML too",
103
105
  "ChatNotificationCardContentActions shows only while the card is expanded",
104
106
  "variant is set on the root as data-variant: floating adds a border in the divider colour, default has none",
105
107
  "Every part carries data-slot='chat-notification-card-{part}' and takes className, merged last. State is on attributes: data-expanded and data-variant on the root, data-priority on the status chip, data-read on the read button, data-snoozed on the snooze button",
@@ -167,6 +169,7 @@
167
169
  "relatedComponents": [
168
170
  "web-chat-ui/chat-notification-popup",
169
171
  "web-chat-ui/chat-card",
172
+ "web-chat-ui/html-viewer",
170
173
  "ui/banner",
171
174
  "ui/chip",
172
175
  "ui/icon-button"
@@ -139,9 +139,7 @@ export const Default: Story = {
139
139
  </ChatNotificationCardHead>
140
140
  <ChatNotificationCardContent>
141
141
  <ChatNotificationCardContentTitle>{FLIGHT_CHECK_IN.title}</ChatNotificationCardContentTitle>
142
- <ChatNotificationCardContentDescription>
143
- {FLIGHT_CHECK_IN.body}
144
- </ChatNotificationCardContentDescription>
142
+ <ChatNotificationCardContentDescription html={FLIGHT_CHECK_IN.body} />
145
143
  <ChatNotificationCardContentActions>
146
144
  <Button variant="secondary" size="sm">
147
145
  Check in now
@@ -193,10 +191,7 @@ export const Snoozed: Story = {
193
191
  </ChatNotificationCardActions>
194
192
  </ChatNotificationCardHead>
195
193
  <ChatNotificationCardContent>
196
- <ChatNotificationCardContentDescription>
197
- The expense report for the Lisbon trip was due yesterday. Three receipts are still
198
- missing.
199
- </ChatNotificationCardContentDescription>
194
+ <ChatNotificationCardContentDescription html="The expense report for the Lisbon trip was due yesterday. Three receipts are still missing." />
200
195
  </ChatNotificationCardContent>
201
196
  </ChatNotificationCard>
202
197
  );
@@ -237,16 +232,7 @@ export const Read: Story = {
237
232
  </ChatNotificationCardHead>
238
233
 
239
234
  <ChatNotificationCardContent>
240
- <ChatNotificationCardContentDescription>
241
- The quarterly budget review was due on Monday and is still open. Finance needs the
242
- updated headcount plan and the tooling costs before they can close the quarter, and the
243
- leadership meeting on Friday depends on both. The draft you started last week covers
244
- salaries and contractors but leaves out the two open engineering roles, the design
245
- tooling renewal in May and the travel budget for the customer summit. Two teammates have
246
- commented on the draft: one asks to split infrastructure costs by environment, the other
247
- flags that the training budget was counted twice. Once the review is submitted, finance
248
- takes about two working days to confirm it, so sending it today keeps Friday on track.
249
- </ChatNotificationCardContentDescription>
235
+ <ChatNotificationCardContentDescription html="The quarterly budget review was due on Monday and is still open. Finance needs the updated headcount plan and the tooling costs before they can close the quarter, and the leadership meeting on Friday depends on both. The draft you started last week covers salaries and contractors but leaves out the two open engineering roles, the design tooling renewal in May and the travel budget for the customer summit. Two teammates have commented on the draft: one asks to split infrastructure costs by environment, the other flags that the training budget was counted twice. Once the review is submitted, finance takes about two working days to confirm it, so sending it today keeps Friday on track." />
250
236
  <ChatNotificationCardContentActions>
251
237
  <Button variant="secondary" size="sm">
252
238
  View task
@@ -287,10 +273,7 @@ export const Floating: Story = {
287
273
  </ChatNotificationCardHead>
288
274
 
289
275
  <ChatNotificationCardContent>
290
- <ChatNotificationCardContentDescription>
291
- The signed supplier contract was due at 12:00 today. Legal can't release the purchase
292
- order until it arrives, and the supplier's offer expires on Friday.
293
- </ChatNotificationCardContentDescription>
276
+ <ChatNotificationCardContentDescription html="The signed supplier contract was due at 12:00 today. Legal can't release the purchase order until it arrives, and the supplier's offer expires on Friday." />
294
277
  <ChatNotificationCardContentActions>
295
278
  <Button variant="secondary" size="sm">
296
279
  View task
@@ -302,6 +285,79 @@ export const Floating: Story = {
302
285
  },
303
286
  };
304
287
 
288
+ const HTML_DESCRIPTION = [
289
+ '<p>Your flight <strong>LX 1820</strong> to Lisbon leaves at <em>07:45</em> tomorrow. Online check-in closes three hours before departure.</p>',
290
+ '<ul><li>Gate opens at 07:00, terminal 2</li><li>One cabin bag up to 8 kg</li></ul>',
291
+ '<p>Read the <a href="https://example.com/baggage">baggage rules</a> before you pack.</p>',
292
+ ].join('');
293
+
294
+ const EMAIL_HTML = [
295
+ '<table width="600" cellpadding="0" cellspacing="0" border="0"><tbody>',
296
+ '<tr><td><p>Swisper</p><h1>Introducing Voice</h1></td></tr>',
297
+ '<tr><td>',
298
+ '<p>Hi,</p>',
299
+ "<p>We're excited to introduce Voice, a new way to use Swisper. Starting <strong>25.11.2026</strong>, you can speak instead of type, so it's faster and easier to get things done on the go.</p>",
300
+ "<p>We built Voice because many of you asked for a hands-free option that fits into busy days, commutes, and moments when typing just isn't practical.</p>",
301
+ '</td></tr>',
302
+ '<tr><td height="40" nowrap><h2>What you can do with Voice</h2></td></tr>',
303
+ '</tbody></table>',
304
+ ].join('');
305
+
306
+ /** Email-template HTML with a `width="600"` layout table. Collapsed, the table text still clamps to two lines; expanded, the table fits the card. */
307
+ export const EmailHtmlDescription: Story = {
308
+ args: {
309
+ className: 'max-w-90',
310
+ },
311
+ render: (args) => (
312
+ <ChatNotificationCard {...args}>
313
+ <ChatNotificationCardHead>
314
+ <ChatNotificationCardHeader>
315
+ <ChatNotificationCardHeaderIcon>
316
+ <FlightIcon />
317
+ </ChatNotificationCardHeaderIcon>
318
+ <ChatNotificationCardHeaderTitle>
319
+ <ChatNotificationCardHeaderTitleLabel>Swisper</ChatNotificationCardHeaderTitleLabel>
320
+ </ChatNotificationCardHeaderTitle>
321
+ </ChatNotificationCardHeader>
322
+ <ChatNotificationCardActions>
323
+ <ChatNotificationCardTimestamp>5 min. ago</ChatNotificationCardTimestamp>
324
+ </ChatNotificationCardActions>
325
+ </ChatNotificationCardHead>
326
+ <ChatNotificationCardContent>
327
+ <ChatNotificationCardContentTitle>Introducing Voice</ChatNotificationCardContentTitle>
328
+ <ChatNotificationCardContentDescription html={EMAIL_HTML} />
329
+ </ChatNotificationCardContent>
330
+ </ChatNotificationCard>
331
+ ),
332
+ };
333
+
334
+ /** A description from HTML: paragraphs, a list, emphasis and a link. Collapsed, it still clamps to two lines; the link opens a new tab without firing the card's `onClick`. */
335
+ export const HtmlDescription: Story = {
336
+ render: (args) => (
337
+ <ChatNotificationCard {...args}>
338
+ <ChatNotificationCardHead>
339
+ <ChatNotificationCardHeader>
340
+ <ChatNotificationCardHeaderIcon>
341
+ <FlightIcon />
342
+ </ChatNotificationCardHeaderIcon>
343
+ <ChatNotificationCardHeaderTitle>
344
+ <ChatNotificationCardHeaderTitleLabel>Travel</ChatNotificationCardHeaderTitleLabel>
345
+ </ChatNotificationCardHeaderTitle>
346
+ </ChatNotificationCardHeader>
347
+ <ChatNotificationCardActions>
348
+ <ChatNotificationCardTimestamp>5 min. ago</ChatNotificationCardTimestamp>
349
+ </ChatNotificationCardActions>
350
+ </ChatNotificationCardHead>
351
+ <ChatNotificationCardContent>
352
+ <ChatNotificationCardContentTitle>
353
+ Check in for your flight
354
+ </ChatNotificationCardContentTitle>
355
+ <ChatNotificationCardContentDescription html={HTML_DESCRIPTION} />
356
+ </ChatNotificationCardContent>
357
+ </ChatNotificationCard>
358
+ ),
359
+ };
360
+
305
361
  /** The expand button reveals the follow-up action and reports the new state without firing the card's `onClick`. */
306
362
  export const ExpandAndCollapse: Story = {
307
363
  ...Default,
@@ -426,9 +482,7 @@ function NotificationSignalListItem({ signal, onRead, onAction }: NotificationSi
426
482
  </ChatNotificationCardHead>
427
483
  <ChatNotificationCardContent>
428
484
  <ChatNotificationCardContentTitle>{signal.title}</ChatNotificationCardContentTitle>
429
- <ChatNotificationCardContentDescription>
430
- {signal.body}
431
- </ChatNotificationCardContentDescription>
485
+ <ChatNotificationCardContentDescription html={signal.body} />
432
486
  {signal.actions.length > 0 && (
433
487
  <ChatNotificationCardContentActions>
434
488
  {signal.actions.map((action) => (
@@ -511,9 +565,7 @@ export const Examples: Story = {
511
565
  <ChatNotificationCardContentTitle>
512
566
  {BOARD_MEETING_MOVED.title}
513
567
  </ChatNotificationCardContentTitle>
514
- <ChatNotificationCardContentDescription>
515
- {BOARD_MEETING_MOVED.body}
516
- </ChatNotificationCardContentDescription>
568
+ <ChatNotificationCardContentDescription html={BOARD_MEETING_MOVED.body} />
517
569
  </ChatNotificationCardContent>
518
570
  </ChatNotificationCard>
519
571
  </div>
@@ -647,9 +699,7 @@ function ChatNotificationCardPlayground({
647
699
  {hasContentTitle && (
648
700
  <ChatNotificationCardContentTitle>{title}</ChatNotificationCardContentTitle>
649
701
  )}
650
- <ChatNotificationCardContentDescription>
651
- {description}
652
- </ChatNotificationCardContentDescription>
702
+ <ChatNotificationCardContentDescription html={description} />
653
703
  {hasContentActions && (
654
704
  <ChatNotificationCardContentActions>
655
705
  <Button variant="secondary" size="sm" onClick={onAction}>
@@ -751,7 +801,8 @@ export const Playground: StoryObj<typeof ChatNotificationCardPlayground> = {
751
801
  title: { control: 'text', description: 'Text of `ChatNotificationCardContentTitle`.' },
752
802
  description: {
753
803
  control: 'text',
754
- description: 'Text of `ChatNotificationCardContentDescription`.',
804
+ description:
805
+ 'HTML of `ChatNotificationCardContentDescription` (its `html` prop), rendered through `HtmlViewer`.',
755
806
  },
756
807
  hasContentActions: {
757
808
  control: 'boolean',
@@ -24,6 +24,8 @@ import { Button, Chip, IconButton, Typography } from '@swisper.ai/ui';
24
24
  import type { ChipProps, IconButtonProps } from '@swisper.ai/ui';
25
25
  import { cn } from '@swisper.ai/web-core';
26
26
 
27
+ import { HtmlViewer, type HtmlViewerComponents } from '../html-viewer';
28
+
27
29
  import type { ChatNotificationCardPriority } from './types';
28
30
  import { formatSnoozeDate } from './utils';
29
31
 
@@ -657,13 +659,21 @@ export function ChatNotificationCardContentTitle({
657
659
  }
658
660
 
659
661
  export interface ChatNotificationCardContentDescriptionProps {
660
- children?: ReactNode;
662
+ /** Notification text as an HTML fragment, rendered through `HtmlViewer` (parsed and sanitised). */
663
+ html: string;
664
+ /** Renderers keyed by tag name, merged over `HtmlViewer`'s defaults. Links open in a new tab and don't fire the card's `onClick`. */
665
+ htmlComponents?: HtmlViewerComponents;
661
666
  className?: string;
662
667
  }
663
668
 
664
- /** Notification text, clamped to two lines until the card is expanded. */
669
+ /**
670
+ * Notification text rendered from HTML, clamped to two lines until the card is expanded. While
671
+ * collapsed, paragraphs and lists lose their vertical margins and table parts render as
672
+ * `display: inline-block`, so table text counts towards the two lines too.
673
+ */
665
674
  export function ChatNotificationCardContentDescription({
666
- children,
675
+ html,
676
+ htmlComponents,
667
677
  className,
668
678
  }: ChatNotificationCardContentDescriptionProps) {
669
679
  return (
@@ -675,12 +685,17 @@ export function ChatNotificationCardContentDescription({
675
685
  'text-text-primary',
676
686
  'mt-8',
677
687
  'group-data-[expanded=false]/chat-notification-card:line-clamp-2',
678
- 'w-full [&>div>*]:wrap-break-word',
688
+ '[&_:is(p,ul,ol)]:my-0!',
689
+ '[&_:is(a)]:inline-block!',
690
+ 'group-data-[expanded=false]/chat-notification-card:[&_:is(table,thead,tbody,tfoot,tr,td,th)]:contents!',
691
+ 'w-full',
679
692
  className,
680
693
  )}
681
694
  asChild
682
695
  >
683
- <div>{children}</div>
696
+ <div>
697
+ <HtmlViewer html={html} components={htmlComponents} />
698
+ </div>
684
699
  </Typography>
685
700
  );
686
701
  }
@@ -68,7 +68,7 @@ export function NotificationItem({
68
68
  </ChatNotificationCardHead>
69
69
  <ChatNotificationCardContent>
70
70
  <ChatNotificationCardContentTitle>{title}</ChatNotificationCardContentTitle>
71
- <ChatNotificationCardContentDescription>{body}</ChatNotificationCardContentDescription>
71
+ <ChatNotificationCardContentDescription html={body} />
72
72
  {hasActions && actions.length > 0 && (
73
73
  <ChatNotificationCardContentActions className="flex-wrap">
74
74
  {actions.map((action) => (
@@ -0,0 +1,105 @@
1
+ /**
2
+ * HtmlViewer turns untrusted-shaped HTML into React elements. These tests pin the sanitising
3
+ * safety net, the component overrides, and the default link's behaviour inside clickable parents.
4
+ */
5
+ import { cleanup, fireEvent, render, screen } from '@testing-library/react';
6
+ import { afterEach, describe, expect, test, vi } from 'vitest';
7
+
8
+ import { HtmlViewer } from '../html-viewer';
9
+
10
+ afterEach(() => {
11
+ cleanup();
12
+ });
13
+
14
+ describe('HtmlViewer', () => {
15
+ test('renders the HTML as elements', () => {
16
+ const { container } = render(
17
+ <HtmlViewer html="<p>Hello <strong>there</strong></p><ul><li>One</li></ul>" />,
18
+ );
19
+
20
+ expect(container.querySelector('p strong')?.textContent).toBe('there');
21
+ expect(container.querySelector('ul li')?.textContent).toBe('One');
22
+ });
23
+
24
+ test('strips scripts, event handlers and javascript: links', () => {
25
+ const { container } = render(
26
+ <HtmlViewer html='<p onclick="alert(1)">Text</p><script>alert(1)</script><a href="javascript:alert(1)">Link</a>' />,
27
+ );
28
+
29
+ expect(container.querySelector('script')).toBeNull();
30
+ expect(container.querySelector('[onclick]')).toBeNull();
31
+ expect(container.querySelector('a')?.getAttribute('href')).toBeFalsy();
32
+ });
33
+
34
+ test('sanitizeSchema extends the default schema', () => {
35
+ const { container } = render(
36
+ <HtmlViewer html="<p><mark>Kept</mark></p>" sanitizeSchema={{ tagNames: ['mark'] }} />,
37
+ );
38
+
39
+ expect(container.querySelector('mark')?.textContent).toBe('Kept');
40
+ expect(container.querySelector('p')).not.toBeNull();
41
+ });
42
+
43
+ test('removes width, height and noWrap so the HTML fits its container', () => {
44
+ const { container } = render(
45
+ <HtmlViewer html='<table width="600" height="400"><tbody><tr><td width="300" height="20" nowrap>Cell</td></tr></tbody></table>' />,
46
+ );
47
+
48
+ expect(container.querySelector('[width]')).toBeNull();
49
+ expect(container.querySelector('[height]')).toBeNull();
50
+ expect(container.querySelector('[nowrap]')).toBeNull();
51
+ expect(container.querySelector('td')?.textContent).toBe('Cell');
52
+ });
53
+
54
+ test('images keep width and height as their aspect ratio', () => {
55
+ const { container } = render(
56
+ <HtmlViewer html='<img src="https://example.com/a.png" alt="" width="800" height="600">' />,
57
+ );
58
+
59
+ const image = container.querySelector('img');
60
+
61
+ expect(image?.getAttribute('width')).toBe('800');
62
+ expect(image?.getAttribute('height')).toBe('600');
63
+ });
64
+
65
+ test('sanitizeSchema can keep width on other elements', () => {
66
+ const { container } = render(
67
+ <HtmlViewer
68
+ html='<table width="600"></table>'
69
+ sanitizeSchema={{ attributes: { table: ['width'] } }}
70
+ />,
71
+ );
72
+
73
+ expect(container.querySelector('table')?.getAttribute('width')).toBe('600');
74
+ });
75
+
76
+ test('components override the default renderers', () => {
77
+ render(
78
+ <HtmlViewer
79
+ html="<p>Body</p>"
80
+ components={{ p: ({ children }) => <p data-testid="custom-p">{children}</p> }}
81
+ />,
82
+ );
83
+
84
+ expect(screen.getByTestId('custom-p').textContent).toBe('Body');
85
+ });
86
+
87
+ test('the default link opens a new tab and keeps its click from the parent', () => {
88
+ const onParentClick = vi.fn();
89
+
90
+ // React stops native propagation at its root, so a listener above the root sees no click.
91
+ document.body.addEventListener('click', onParentClick);
92
+
93
+ render(<HtmlViewer html='<a href="https://example.com">Example</a>' />);
94
+
95
+ const link = screen.getByRole('link', { name: 'Example' });
96
+
97
+ expect(link.getAttribute('target')).toBe('_blank');
98
+ expect(link.getAttribute('rel')).toBe('noopener noreferrer');
99
+
100
+ fireEvent.click(link);
101
+ document.body.removeEventListener('click', onParentClick);
102
+
103
+ expect(onParentClick).not.toHaveBeenCalled();
104
+ });
105
+ });
@@ -0,0 +1,81 @@
1
+ {
2
+ "$schema": "../../../../int-eslint-config/schemas/component.schema.json",
3
+ "component": "html-viewer",
4
+ "purpose": "Renders an HTML fragment as React elements: parses it with rehype, sanitises it with rehype-sanitize, and maps each tag through overridable components.",
5
+ "anatomy": [
6
+ "import { HtmlViewer } from '@swisper.ai/web-chat-ui';",
7
+ "",
8
+ "<HtmlViewer html={html} />"
9
+ ],
10
+ "useWhen": [
11
+ "Content arrives as HTML (e.g. a notification body from a backend template) and must render as formatted text",
12
+ "Specific tags need custom React renderers, e.g. in-app routing for links"
13
+ ],
14
+ "avoidWhen": [
15
+ "The content is markdown or streams in from a model — use web-chat-ui/markdown-viewer",
16
+ "A notification description — use web-chat-ui/ChatNotificationCardContentDescription with its html prop, which wraps this",
17
+ "Plain, unformatted text — use ui/typography"
18
+ ],
19
+ "uxPrinciples": [
20
+ "Inherit typography from the parent: the viewer sets no font size or colour, so it reads as part of its container.",
21
+ "Links inside clickable surfaces keep their own click: following a link never also triggers the surface."
22
+ ],
23
+ "accessibility": {
24
+ "required": [
25
+ "Images in the HTML need alt text in the HTML itself",
26
+ "Components passed in components own their own accessibility"
27
+ ],
28
+ "keyboard": ["Not interactive itself; links follow standard keyboard behaviour"],
29
+ "aria": [
30
+ "Semantic HTML from the fragment (paragraphs, lists, links); no role or live region is added"
31
+ ],
32
+ "focus": [
33
+ "No focus management; focusable elements are those the HTML or the custom components render"
34
+ ]
35
+ },
36
+ "behaviour": {
37
+ "states": ["static"],
38
+ "rules": [
39
+ "html is parsed as a fragment with rehype-parse and sanitised with rehype-sanitize's default schema minus width, height and noWrap before rendering; it is never set as innerHTML",
40
+ "sanitizeSchema is added to that base schema: its tag names, attributes, protocols and required attributes are appended to the base lists",
41
+ "width, height and noWrap attributes are removed from every element except img, so fixed-size markup such as <table width=\"600\"> fits its container; pass them in sanitizeSchema.attributes to keep them",
42
+ "img keeps width and height as its aspect ratio; the root caps images (max-w-full, h-auto) and tables (max-w-full) at its width and wraps long words anywhere, even when a custom renderer draws them",
43
+ "Scripts, event-handler attributes, style attributes and javascript: URLs are removed by the default schema",
44
+ "components is merged over the defaults (a, p, ul, ol, li, strong, b, em, i, code); every other allowed tag renders as a plain element",
45
+ "The default a renders ui/link with target=\"_blank\" and rel=\"noopener noreferrer\", and stops click and mousedown propagation so a clickable parent does not react",
46
+ "Default block elements (p, ul, ol) have no top margin when first and an 8px top margin otherwise",
47
+ "className is merged last onto the root element (data-slot=\"html-viewer\")"
48
+ ]
49
+ },
50
+ "composition": {
51
+ "allowedParents": ["web-chat-ui/ChatNotificationCardContentDescription", "ui/typography"],
52
+ "allowedChildren": ["HTML string", "tag renderers (components)"],
53
+ "avoidCombinations": [
54
+ "Wrapping in a flex or grid container that should line-clamp — -webkit-line-clamp only counts lines in block flow"
55
+ ],
56
+ "contexts": ["notification card description", "any surface that receives backend HTML"]
57
+ },
58
+ "content": {
59
+ "labelRules": [],
60
+ "helperTextRules": [],
61
+ "errorRules": []
62
+ },
63
+ "aiDecisionRules": [
64
+ {
65
+ "condition": "Passing components or sanitizeSchema",
66
+ "decision": "Create the object once (module scope or useMemo)",
67
+ "reason": "Its identity is a memo dependency: a new object each render re-parses the HTML"
68
+ },
69
+ {
70
+ "condition": "Links must navigate inside the app",
71
+ "decision": "Override a in components with a renderer that routes in-app",
72
+ "reason": "The default a always opens a new tab"
73
+ }
74
+ ],
75
+ "relatedComponents": [
76
+ "web-chat-ui/markdown-viewer",
77
+ "web-chat-ui/chat-notification-card",
78
+ "ui/link",
79
+ "ui/typography"
80
+ ]
81
+ }
@@ -0,0 +1,118 @@
1
+ import type { Meta, StoryObj } from '@storybook/react-vite';
2
+ import { expect } from 'storybook/test';
3
+
4
+ import { HtmlViewer } from './html-viewer';
5
+ import type { HtmlViewerComponents } from './types';
6
+
7
+ const MIXED_HTML = [
8
+ '<p>Your flight <strong>LX 1820</strong> to Lisbon leaves at <em>07:45</em> tomorrow.</p>',
9
+ '<ul><li>Gate opens at 07:00, terminal 2</li><li>One cabin bag up to 8 kg</li></ul>',
10
+ '<ol><li>Check in online</li><li>Download the boarding pass</li></ol>',
11
+ '<p>Booking reference: <code>X7K2QP</code><br>Read the <a href="https://example.com/baggage">baggage rules</a> before you pack.</p>',
12
+ ].join('');
13
+
14
+ const EMAIL_HTML = [
15
+ '<table width="600" cellpadding="0" cellspacing="0" border="0"><tbody>',
16
+ '<tr><td><p>Swisper</p><h1>Introducing Voice</h1></td></tr>',
17
+ '<tr><td>',
18
+ '<p>Hi,</p>',
19
+ "<p>We're excited to introduce Voice, a new way to use Swisper. Starting <strong>25.11.2026</strong>, you can speak instead of type, so it's faster and easier to get things done on the go.</p>",
20
+ "<p>We built Voice because many of you asked for a hands-free option that fits into busy days, commutes, and moments when typing just isn't practical.</p>",
21
+ '</td></tr>',
22
+ '<tr><td height="40" nowrap><h2>What you can do with Voice</h2></td></tr>',
23
+ '</tbody></table>',
24
+ ].join('');
25
+
26
+ const meta: Meta<typeof HtmlViewer> = {
27
+ title: 'Chat/HtmlViewer',
28
+ component: HtmlViewer,
29
+ parameters: {
30
+ layout: 'padded',
31
+ },
32
+ tags: ['autodocs'],
33
+ argTypes: {
34
+ html: {
35
+ control: 'text',
36
+ description: 'HTML fragment to render. It is parsed and sanitised, never set as `innerHTML`.',
37
+ },
38
+ className: {
39
+ control: 'text',
40
+ description: 'Classes merged last onto the root element (`data-slot="html-viewer"`).',
41
+ },
42
+ components: {
43
+ control: false,
44
+ description:
45
+ 'Renderers keyed by tag name, merged over the defaults (`a`, `p`, `ul`, `ol`, `li`, `strong`, `b`, `em`, `i`, `code`).',
46
+ table: { defaultValue: { summary: '{}' } },
47
+ },
48
+ sanitizeSchema: {
49
+ control: false,
50
+ description:
51
+ "Added to the base schema (`rehype-sanitize`'s default without `width`, `height` and `noWrap`, except on `img`), e.g. to allow an extra tag or attribute.",
52
+ },
53
+ },
54
+ args: {
55
+ html: MIXED_HTML,
56
+ className: 'text-text-primary',
57
+ },
58
+ };
59
+
60
+ export default meta;
61
+ type Story = StoryObj<typeof HtmlViewer>;
62
+
63
+ /** Paragraphs, lists, emphasis, inline code and a link with the default renderers. */
64
+ export const Default: Story = {};
65
+
66
+ const CUSTOM_COMPONENTS: HtmlViewerComponents = {
67
+ a: ({ href, children }) => (
68
+ <a href={href} className="text-primary-main font-semibold no-underline">
69
+ {children} ↗
70
+ </a>
71
+ ),
72
+ p: ({ children }) => <p className="my-0 not-first:mt-12 text-text-secondary">{children}</p>,
73
+ };
74
+
75
+ /** `components` replaces the default `a` and `p`; the other tags keep their defaults. */
76
+ export const CustomComponents: Story = {
77
+ args: {
78
+ components: CUSTOM_COMPONENTS,
79
+ },
80
+ };
81
+
82
+ /** Scripts, event handlers and `javascript:` links are stripped before rendering. */
83
+ export const Sanitized: Story = {
84
+ args: {
85
+ html: [
86
+ '<p onclick="alert(1)">This paragraph had an <code>onclick</code> handler.</p>',
87
+ '<script>alert(1)</script>',
88
+ '<p><a href="javascript:alert(1)">This link had a javascript: href</a>.</p>',
89
+ ].join(''),
90
+ },
91
+ play: async ({ canvasElement }) => {
92
+ await expect(canvasElement.querySelector('script')).toBeNull();
93
+ await expect(canvasElement.querySelector('[onclick]')).toBeNull();
94
+ await expect(canvasElement.querySelector('a')?.getAttribute('href')).toBeFalsy();
95
+ },
96
+ };
97
+
98
+ /** Email-template HTML with a `width="600"` layout table, in a 320px container: `width`, `height` and `noWrap` are stripped, so it fits. */
99
+ export const FixedSizeHtml: Story = {
100
+ args: {
101
+ html: EMAIL_HTML,
102
+ },
103
+ decorators: [
104
+ (Story) => (
105
+ <div className="w-80 border border-dashed border-border-primary">
106
+ <Story />
107
+ </div>
108
+ ),
109
+ ],
110
+ play: async ({ canvasElement }) => {
111
+ const root = canvasElement.querySelector<HTMLElement>('[data-slot="html-viewer"]');
112
+ const table = canvasElement.querySelector('table');
113
+
114
+ await expect(table?.getAttribute('width')).toBeNull();
115
+ await expect(canvasElement.querySelector('[height], [nowrap]')).toBeNull();
116
+ await expect(table!.getBoundingClientRect().width).toBeLessThanOrEqual(root!.clientWidth);
117
+ },
118
+ };