@swisper.ai/web-chat-ui 0.4.1 → 0.5.1

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 (33) 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 +20 -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 -1052
  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/__stories__/transactional-email.html +154 -0
  26. package/src/components/html-viewer/__tests__/html-viewer.spec.tsx +105 -0
  27. package/src/components/html-viewer/html-viewer.json +82 -0
  28. package/src/components/html-viewer/html-viewer.stories.tsx +145 -0
  29. package/src/components/html-viewer/html-viewer.tsx +134 -0
  30. package/src/components/html-viewer/index.ts +2 -0
  31. package/src/components/html-viewer/types.ts +8 -0
  32. package/src/components/html-viewer/utils.ts +65 -0
  33. package/src/components/index.ts +1 -0
@@ -0,0 +1,145 @@
1
+ import type { Meta, StoryObj } from '@storybook/react-vite';
2
+ import { expect } from 'storybook/test';
3
+
4
+ import TRANSACTIONAL_EMAIL_HTML from './__stories__/transactional-email.html?raw';
5
+ import { HtmlViewer } from './html-viewer';
6
+ import type { HtmlViewerComponents } from './types';
7
+
8
+ const MIXED_HTML = [
9
+ '<p>Your flight <strong>LX 1820</strong> to Lisbon leaves at <em>07:45</em> tomorrow.</p>',
10
+ '<ul><li>Gate opens at 07:00, terminal 2</li><li>One cabin bag up to 8 kg</li></ul>',
11
+ '<ol><li>Check in online</li><li>Download the boarding pass</li></ol>',
12
+ '<p>Booking reference: <code>X7K2QP</code><br>Read the <a href="https://example.com/baggage">baggage rules</a> before you pack.</p>',
13
+ ].join('');
14
+
15
+ const EMAIL_HTML = [
16
+ '<table width="600" cellpadding="0" cellspacing="0" border="0"><tbody>',
17
+ '<tr><td><p>Swisper</p><h1>Introducing Voice</h1></td></tr>',
18
+ '<tr><td>',
19
+ '<p>Hi,</p>',
20
+ "<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>",
21
+ "<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>",
22
+ '</td></tr>',
23
+ '<tr><td height="40" nowrap><h2>What you can do with Voice</h2></td></tr>',
24
+ '</tbody></table>',
25
+ ].join('');
26
+
27
+ const meta: Meta<typeof HtmlViewer> = {
28
+ title: 'Chat/HtmlViewer',
29
+ component: HtmlViewer,
30
+ parameters: {
31
+ layout: 'padded',
32
+ },
33
+ tags: ['autodocs'],
34
+ argTypes: {
35
+ html: {
36
+ control: 'text',
37
+ description: 'HTML fragment to render. It is parsed and sanitised, never set as `innerHTML`.',
38
+ },
39
+ className: {
40
+ control: 'text',
41
+ description: 'Classes merged last onto the root element (`data-slot="html-viewer"`).',
42
+ },
43
+ components: {
44
+ control: false,
45
+ description:
46
+ 'Renderers keyed by tag name, merged over the defaults (`a`, `p`, `ul`, `ol`, `li`, `strong`, `b`, `em`, `i`, `code`).',
47
+ table: { defaultValue: { summary: '{}' } },
48
+ },
49
+ sanitizeSchema: {
50
+ control: false,
51
+ description:
52
+ "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.",
53
+ },
54
+ },
55
+ args: {
56
+ html: MIXED_HTML,
57
+ className: 'text-text-primary',
58
+ },
59
+ };
60
+
61
+ export default meta;
62
+ type Story = StoryObj<typeof HtmlViewer>;
63
+
64
+ /** Paragraphs, lists, emphasis, inline code and a link with the default renderers. */
65
+ export const Default: Story = {};
66
+
67
+ const CUSTOM_COMPONENTS: HtmlViewerComponents = {
68
+ a: ({ href, children }) => (
69
+ <a href={href} className="text-primary-main font-semibold no-underline">
70
+ {children} ↗
71
+ </a>
72
+ ),
73
+ p: ({ children }) => <p className="my-0 not-first:mt-12 text-text-secondary">{children}</p>,
74
+ };
75
+
76
+ /** `components` replaces the default `a` and `p`; the other tags keep their defaults. */
77
+ export const CustomComponents: Story = {
78
+ args: {
79
+ components: CUSTOM_COMPONENTS,
80
+ },
81
+ };
82
+
83
+ /** Scripts, event handlers and `javascript:` links are stripped before rendering. */
84
+ export const Sanitized: Story = {
85
+ args: {
86
+ html: [
87
+ '<p onclick="alert(1)">This paragraph had an <code>onclick</code> handler.</p>',
88
+ '<script>alert(1)</script>',
89
+ '<p><a href="javascript:alert(1)">This link had a javascript: href</a>.</p>',
90
+ ].join(''),
91
+ },
92
+ play: async ({ canvasElement }) => {
93
+ await expect(canvasElement.querySelector('script')).toBeNull();
94
+ await expect(canvasElement.querySelector('[onclick]')).toBeNull();
95
+ await expect(canvasElement.querySelector('a')?.getAttribute('href')).toBeFalsy();
96
+ },
97
+ };
98
+
99
+ /** Email-template HTML with a `width="600"` layout table, in a 320px container: `width`, `height` and `noWrap` are stripped, so it fits. */
100
+ export const FixedSizeHtml: Story = {
101
+ args: {
102
+ html: EMAIL_HTML,
103
+ },
104
+ decorators: [
105
+ (Story) => (
106
+ <div className="w-80 border border-dashed border-border-primary">
107
+ <Story />
108
+ </div>
109
+ ),
110
+ ],
111
+ play: async ({ canvasElement }) => {
112
+ const root = canvasElement.querySelector<HTMLElement>('[data-slot="html-viewer"]');
113
+ const table = canvasElement.querySelector('table');
114
+
115
+ await expect(table?.getAttribute('width')).toBeNull();
116
+ await expect(canvasElement.querySelector('[height], [nowrap]')).toBeNull();
117
+ await expect(table!.getBoundingClientRect().width).toBeLessThanOrEqual(root!.clientWidth);
118
+ },
119
+ };
120
+
121
+ /**
122
+ * A whole email document (`<!doctype>`, `<head>` with `<title>` and `<style>`, nested layout
123
+ * tables, inline styles, comments) in a 320px container. `<title>` and `<style>` are removed with
124
+ * their text, inline styles and comments are dropped, and the layout tables fit.
125
+ */
126
+ export const ComplexEmail: Story = {
127
+ args: {
128
+ html: TRANSACTIONAL_EMAIL_HTML,
129
+ },
130
+ decorators: [
131
+ (Story) => (
132
+ <div className="w-80 border border-dashed border-border-primary">
133
+ <Story />
134
+ </div>
135
+ ),
136
+ ],
137
+ play: async ({ canvasElement }) => {
138
+ const root = canvasElement.querySelector<HTMLElement>('[data-slot="html-viewer"]');
139
+
140
+ await expect(root?.textContent).not.toContain('Simple Transactional Email');
141
+ await expect(root?.textContent).not.toContain('@media');
142
+ await expect(canvasElement.querySelector('style, title, [style]')).toBeNull();
143
+ await expect(root!.scrollWidth).toBeLessThanOrEqual(root!.clientWidth);
144
+ },
145
+ };
@@ -0,0 +1,134 @@
1
+ import { toJsxRuntime, type ExtraProps } from 'hast-util-to-jsx-runtime';
2
+ import { useMemo, type ComponentProps, type MouseEvent } from 'react';
3
+ import { Fragment, jsx, jsxs } from 'react/jsx-runtime';
4
+ import rehypeParse from 'rehype-parse';
5
+ import rehypeSanitize from 'rehype-sanitize';
6
+ import { unified } from 'unified';
7
+
8
+ import { Link } from '@swisper.ai/ui';
9
+ import { cn } from '@swisper.ai/web-core';
10
+
11
+ import type { HtmlViewerComponents, HtmlViewerSanitizeSchema } from './types';
12
+ import { mergeSanitizeSchema } from './utils';
13
+
14
+ export interface HtmlViewerProps {
15
+ /** HTML fragment to render. It is parsed and sanitised; it is never set as `innerHTML`. */
16
+ html: string;
17
+ /** Classes merged last onto the root element (`data-slot="html-viewer"`). */
18
+ className?: string;
19
+ /** Renderers keyed by tag name, merged over the defaults (`a`, `p`, `ul`, `ol`, `li`, `strong`, `b`, `em`, `i`, `code`). */
20
+ components?: HtmlViewerComponents;
21
+ /** 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. */
22
+ sanitizeSchema?: HtmlViewerSanitizeSchema;
23
+ }
24
+
25
+ /**
26
+ * Renders an HTML fragment as React elements: parsed with rehype, sanitised, and mapped through
27
+ * `components`. The root keeps the content inside its container: long words wrap anywhere, and
28
+ * images and tables are capped at its width, whichever renderer draws them.
29
+ */
30
+ export function HtmlViewer({ html, className, components, sanitizeSchema }: HtmlViewerProps) {
31
+ const schema = useMemo(() => mergeSanitizeSchema(sanitizeSchema), [sanitizeSchema]);
32
+
33
+ const processor = useMemo(
34
+ () => unified().use(rehypeParse, { fragment: true }).use(rehypeSanitize, schema),
35
+ [schema],
36
+ );
37
+
38
+ const content = useMemo(() => {
39
+ const tree = processor.runSync(processor.parse(html));
40
+
41
+ return toJsxRuntime(tree, {
42
+ Fragment,
43
+ jsx,
44
+ jsxs,
45
+ components: { ...DEFAULT_COMPONENTS, ...components },
46
+ });
47
+ }, [processor, html, components]);
48
+
49
+ return (
50
+ <div
51
+ data-slot="html-viewer"
52
+ data-testid="html-viewer"
53
+ className={cn(
54
+ 'min-w-0 wrap-anywhere',
55
+ '[&_img]:h-auto [&_img]:max-w-full [&_table]:max-w-full',
56
+ className,
57
+ )}
58
+ >
59
+ {content}
60
+ </div>
61
+ );
62
+ }
63
+
64
+ type ElementProps<TagName extends keyof JSX.IntrinsicElements> = ComponentProps<TagName> &
65
+ ExtraProps;
66
+
67
+ function stopPropagation(event: MouseEvent<HTMLAnchorElement>) {
68
+ event.stopPropagation();
69
+ }
70
+
71
+ /** Opens in a new tab; its clicks don't reach a clickable parent such as a notification card. */
72
+ function HtmlViewerLink({ href, title, className, children }: ElementProps<'a'>) {
73
+ return (
74
+ <Link
75
+ href={href}
76
+ title={title}
77
+ className={cn('inline-block!', className)}
78
+ isExternal
79
+ onMouseDown={stopPropagation}
80
+ onClick={stopPropagation}
81
+ >
82
+ {children}
83
+ </Link>
84
+ );
85
+ }
86
+
87
+ function HtmlViewerParagraph({ node: _node, className, ...rest }: ElementProps<'p'>) {
88
+ return <p className={cn('my-0 not-first:mt-8', className)} {...rest} />;
89
+ }
90
+
91
+ function HtmlViewerUnorderedList({ node: _node, className, ...rest }: ElementProps<'ul'>) {
92
+ return <ul className={cn('my-0 not-first:mt-8 pl-20 list-disc', className)} {...rest} />;
93
+ }
94
+
95
+ function HtmlViewerOrderedList({ node: _node, className, ...rest }: ElementProps<'ol'>) {
96
+ return <ol className={cn('my-0 not-first:mt-8 pl-20 list-decimal', className)} {...rest} />;
97
+ }
98
+
99
+ function HtmlViewerListItem({ node: _node, className, ...rest }: ElementProps<'li'>) {
100
+ return <li className={cn('my-0', className)} {...rest} />;
101
+ }
102
+
103
+ function HtmlViewerStrong({ node: _node, className, ...rest }: ElementProps<'strong'>) {
104
+ return <strong className={cn('font-semibold', className)} {...rest} />;
105
+ }
106
+
107
+ function HtmlViewerBold({ node: _node, className, ...rest }: ElementProps<'b'>) {
108
+ return <b className={cn('font-semibold', className)} {...rest} />;
109
+ }
110
+
111
+ function HtmlViewerEmphasis({ node: _node, className, ...rest }: ElementProps<'em'>) {
112
+ return <em className={cn('italic', className)} {...rest} />;
113
+ }
114
+
115
+ function HtmlViewerItalic({ node: _node, className, ...rest }: ElementProps<'i'>) {
116
+ return <i className={cn('italic', className)} {...rest} />;
117
+ }
118
+
119
+ function HtmlViewerCode({ node: _node, className, ...rest }: ElementProps<'code'>) {
120
+ return <code className={cn('font-mono text-[0.9em]', className)} {...rest} />;
121
+ }
122
+
123
+ const DEFAULT_COMPONENTS: HtmlViewerComponents = {
124
+ a: HtmlViewerLink,
125
+ p: HtmlViewerParagraph,
126
+ ul: HtmlViewerUnorderedList,
127
+ ol: HtmlViewerOrderedList,
128
+ li: HtmlViewerListItem,
129
+ strong: HtmlViewerStrong,
130
+ b: HtmlViewerBold,
131
+ em: HtmlViewerEmphasis,
132
+ i: HtmlViewerItalic,
133
+ code: HtmlViewerCode,
134
+ };
@@ -0,0 +1,2 @@
1
+ export { HtmlViewer, type HtmlViewerProps } from './html-viewer';
2
+ export type { HtmlViewerComponents, HtmlViewerSanitizeSchema } from './types';
@@ -0,0 +1,8 @@
1
+ import type { Components } from 'hast-util-to-jsx-runtime';
2
+ import type { Options as SanitizeSchema } from 'rehype-sanitize';
3
+
4
+ /** Renderers keyed by HTML tag name. Each receives the element's props plus its hast `node`. */
5
+ export type HtmlViewerComponents = Partial<Components>;
6
+
7
+ /** A `rehype-sanitize` schema. Its lists are added to the base schema, not swapped for it. */
8
+ export type HtmlViewerSanitizeSchema = SanitizeSchema;
@@ -0,0 +1,65 @@
1
+ import { defaultSchema } from 'rehype-sanitize';
2
+
3
+ import type { HtmlViewerSanitizeSchema } from './types';
4
+
5
+ /** Attributes that pin a size and push content past its container, e.g. `<table width="600">`. */
6
+ const FIXED_LAYOUT_ATTRIBUTES = new Set(['width', 'height', 'noWrap']);
7
+
8
+ const defaultAttributes = Object.fromEntries(
9
+ Object.entries(defaultSchema.attributes ?? {}).map(([tagName, values]) => [
10
+ tagName,
11
+ values.filter((value) => !FIXED_LAYOUT_ATTRIBUTES.has(Array.isArray(value) ? value[0] : value)),
12
+ ]),
13
+ );
14
+
15
+ /**
16
+ * Elements removed with their content. A whole document (e.g. an email template) parsed as a
17
+ * fragment keeps `<title>` and `<style>`; unwrapped, their text would render as visible content.
18
+ */
19
+ const STRIPPED_TAG_NAMES = ['style', 'title'];
20
+
21
+ /**
22
+ * `rehype-sanitize`'s default schema without `width`, `height` and `noWrap`, which it allows on
23
+ * every element. `img` keeps `width` and `height` as its aspect ratio; the viewer caps images with
24
+ * `max-w-full h-auto`, so they never overflow. `style` and `title` are removed with their content.
25
+ */
26
+ const BASE_SCHEMA: HtmlViewerSanitizeSchema = {
27
+ ...defaultSchema,
28
+ strip: [...(defaultSchema.strip ?? []), ...STRIPPED_TAG_NAMES],
29
+ attributes: {
30
+ ...defaultAttributes,
31
+ img: [...(defaultAttributes.img ?? []), 'width', 'height'],
32
+ },
33
+ };
34
+
35
+ /**
36
+ * Adds `extra` to the base schema (`rehype-sanitize`'s default without `width`, `height` and
37
+ * `noWrap`, except on `img`): tag names, per-tag attributes, protocols and required attributes are
38
+ * appended to the base lists; any other key replaces the base value.
39
+ */
40
+ export function mergeSanitizeSchema(extra?: HtmlViewerSanitizeSchema): HtmlViewerSanitizeSchema {
41
+ if (!extra) {
42
+ return BASE_SCHEMA;
43
+ }
44
+
45
+ const attributes = { ...BASE_SCHEMA.attributes };
46
+
47
+ for (const [tagName, values] of Object.entries(extra.attributes ?? {})) {
48
+ attributes[tagName] = [...(attributes[tagName] ?? []), ...values];
49
+ }
50
+
51
+ const protocols = { ...BASE_SCHEMA.protocols };
52
+
53
+ for (const [attribute, values] of Object.entries(extra.protocols ?? {})) {
54
+ protocols[attribute] = [...(protocols[attribute] ?? []), ...(values ?? [])];
55
+ }
56
+
57
+ return {
58
+ ...BASE_SCHEMA,
59
+ ...extra,
60
+ tagNames: [...(BASE_SCHEMA.tagNames ?? []), ...(extra.tagNames ?? [])],
61
+ attributes,
62
+ protocols,
63
+ required: { ...BASE_SCHEMA.required, ...extra.required },
64
+ };
65
+ }
@@ -20,6 +20,7 @@ export * from './new-chat-trigger';
20
20
  export * from './chat-reasoning';
21
21
  export * from './chat-thinking-process';
22
22
  export * from './deprecated-empty-state';
23
+ export * from './html-viewer';
23
24
  export * from './markdown-viewer';
24
25
  export * from './rich-text-area';
25
26
  export * from './rich-text-field';