Repository navigation
[FEATURE] Support Markdown in panel description #380
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
117cdc7
[FEATURE] Support Markdown in panel description
AntoineThebaud 13f1e50
Address review comment (support for non-browser builds)
AntoineThebaud 6adb5cd
Merge branch 'main' into antoinethebaud/markdown-panel-desc
AntoineThebaud bf7139a
address review comments
AntoineThebaud fa4d58f
Merge remote-tracking branch 'origin/main' into antoinethebaud/markdo…
Copilot 0a5c31e
address review comment
AntoineThebaud ce51bda
Merge branch 'main' into antoinethebaud/markdown-panel-desc
AntoineThebaud File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
116 changes: 116 additions & 0 deletions
116
dashboards/src/components/Panel/PanelDescriptionTooltip.test.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,116 @@ | ||
| // Copyright The Perses Authors | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
|
|
||
| import { marked } from 'marked'; | ||
|
|
||
| import { panelDescriptionToHTML } from './PanelDescriptionTooltip'; | ||
|
|
||
| // Renders the HTML in a detached element, to check which elements and attributes the browser would actually create. | ||
| function toElement(html: string): HTMLElement { | ||
| const element = document.createElement('div'); | ||
| element.innerHTML = html; | ||
| return element; | ||
| } | ||
|
|
||
| describe('panelDescriptionToHTML', () => { | ||
| it('keeps plain text descriptions unchanged', () => { | ||
| expect(panelDescriptionToHTML('Simple description')).toBe('<p>Simple description</p>\n'); | ||
| }); | ||
|
|
||
| it('preserves single line breaks', () => { | ||
| expect(panelDescriptionToHTML('first line\nsecond line')).toBe('<p>first line<br>second line</p>\n'); | ||
| }); | ||
|
|
||
| it('renders markdown', () => { | ||
| const html = panelDescriptionToHTML('Some **bold** text\n\n- item 1\n- item 2'); | ||
| expect(html).toContain('<strong>bold</strong>'); | ||
| expect(html).toContain('<ul>\n<li>item 1</li>\n<li>item 2</li>\n</ul>'); | ||
| }); | ||
|
|
||
| it('opens links in a new tab', () => { | ||
| expect(panelDescriptionToHTML('[docs](https://example.com)')).toContain( | ||
| '<a href="https://example.com" target="_blank" rel="noopener noreferrer">docs</a>', | ||
| ); | ||
| }); | ||
|
|
||
| it('displays raw HTML as text', () => { | ||
| expect(panelDescriptionToHTML('Expected format: <host>:<port>')).toBe( | ||
| '<p>Expected format: <host>:<port></p>\n', | ||
| ); | ||
| expect(panelDescriptionToHTML('<div>\nblock\n</div>')).toBe('<div>\nblock\n</div>'); | ||
| }); | ||
|
|
||
| it('still renders autolinks', () => { | ||
| expect(toElement(panelDescriptionToHTML('See <https://example.com>')).querySelector('a')).toHaveAttribute( | ||
| 'href', | ||
| 'https://example.com', | ||
| ); | ||
| }); | ||
|
|
||
| it.each([ | ||
| ['scripts', '<script>alert(1)</script>', 'script'], | ||
| ['event handlers', '<img src="x" onerror="alert(1)">', '[onerror]'], | ||
| ['style elements', 'foo\n\n<style>body{display:none}</style>', 'style'], | ||
| ['style elements inside svg', '<svg><style>body{display:none}</style></svg>', 'svg, style'], | ||
| ['inline styles', '<div style="position:fixed;inset:0">overlay</div>', '[style]'], | ||
| ['forms', '<form action="https://example.com"><input type="password"><button>go</button></form>', 'form, input'], | ||
| ['buttons', '<button>go</button>', 'button'], | ||
| ['textareas', '<textarea></textarea>', 'textarea'], | ||
| ['selects', '<select><option>a</option></select>', 'select'], | ||
| ['class attributes', '<span class="MuiBackdrop-root">x</span>', '[class]'], | ||
| ['id attributes', '<span id="root">x</span>', '[id]'], | ||
| ])('does not create %s from raw HTML', (_, description, forbiddenSelector) => { | ||
| const element = toElement(panelDescriptionToHTML(description)); | ||
| expect(element.querySelector(forbiddenSelector)).toBeNull(); | ||
| // The raw HTML is still visible as text. | ||
| expect(element.textContent).toContain(description.trim().split('\n').pop()); | ||
| }); | ||
|
|
||
| it.each([ | ||
| ['links', '[click](javascript:alert(1))'], | ||
| ['images', ')'], | ||
| ])('removes javascript: URLs from Markdown %s', (_, description) => { | ||
| const element = toElement(panelDescriptionToHTML(description)); | ||
| expect(element.querySelector('[href^="javascript:"], [src^="javascript:"]')).toBeNull(); | ||
| }); | ||
|
|
||
| it('removes class attributes produced from Markdown', () => { | ||
| expect(toElement(panelDescriptionToHTML('```js\nconst a = 1;\n```')).querySelector('[class]')).toBeNull(); | ||
| }); | ||
|
|
||
| it('renders task lists without input elements', () => { | ||
| expect(panelDescriptionToHTML('- [x] done\n- [ ] todo')).toBe('<ul>\n<li>☑ done</li>\n<li>☐ todo</li>\n</ul>\n'); | ||
| }); | ||
|
|
||
| it('is not affected by the global marked configuration', () => { | ||
| marked.use({ renderer: { strong: (): string => 'overridden' } }); | ||
| try { | ||
| expect(panelDescriptionToHTML('**bold**')).toBe('<p><strong>bold</strong></p>\n'); | ||
| } finally { | ||
| marked.setOptions(marked.getDefaults()); | ||
| } | ||
| }); | ||
|
|
||
| it('can be imported and falls back to escaped plain text when no DOM is available', async () => { | ||
| vi.resetModules(); | ||
| vi.stubGlobal('window', undefined); | ||
| try { | ||
| const module = await import('./PanelDescriptionTooltip'); | ||
| expect(module.panelDescriptionToHTML('**bold** <img src=x onerror="alert(1)">')).toBe( | ||
| '**bold** <img src=x onerror="alert(1)">', | ||
| ); | ||
| } finally { | ||
| vi.unstubAllGlobals(); | ||
| } | ||
| }); | ||
| }); |
191 changes: 191 additions & 0 deletions
191
dashboards/src/components/Panel/PanelDescriptionTooltip.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,191 @@ | ||
| // Copyright The Perses Authors | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
|
|
||
| import type { TooltipProps } from '@mui/material'; | ||
| import { Box, styled, Tooltip, tooltipClasses } from '@mui/material'; | ||
| import type { DOMPurify as DOMPurifyInstance } from 'dompurify'; | ||
| import DOMPurify from 'dompurify'; | ||
| import { Marked } from 'marked'; | ||
| import type { ReactElement, ReactNode } from 'react'; | ||
| import { useMemo } from 'react'; | ||
|
|
||
| // Dedicated Marked instance, so that global `marked.use()` / `marked.setOptions()` calls elsewhere in the host | ||
| // application do not change how descriptions are rendered. | ||
| const descriptionMarked = new Marked({ | ||
| gfm: true, | ||
| breaks: true, | ||
| renderer: { | ||
| // Task list items are rendered as text, since `<input>` elements are removed by the sanitizer. | ||
| checkbox: ({ checked }): string => (checked ? '☑' : '☐'), | ||
| // Raw HTML is not supported: it is displayed as text, so that e.g. `<host>:<port>` is not parsed as tags and | ||
| // then removed by the sanitizer. | ||
| html: ({ text }): string => escapeHTML(text), | ||
| }, | ||
| }); | ||
|
|
||
| // Elements and attributes that could affect the page outside the tooltip (which is portaled to `document.body`), | ||
| // e.g. restyle or cover the application, or collect user input. Raw HTML is already escaped by the renderer, so | ||
| // this is a second layer of defense for the HTML produced from Markdown. | ||
| const FORBIDDEN_TAGS = ['style', 'form', 'input', 'button', 'textarea', 'select']; | ||
| const FORBIDDEN_ATTRIBUTES = ['style', 'class', 'id']; | ||
|
|
||
| let descriptionPurifier: DOMPurifyInstance | undefined; | ||
|
|
||
| // Lazily create an isolated DOMPurify instance, so that: | ||
| // - the hook below does not affect other consumers of the default singleton, | ||
| // - importing this module does not fail in environments without a DOM (e.g. SSR), where DOMPurify is not supported. | ||
| function getDescriptionPurifier(): DOMPurifyInstance { | ||
| if (descriptionPurifier === undefined) { | ||
| descriptionPurifier = DOMPurify(); | ||
| if (descriptionPurifier.isSupported) { | ||
| descriptionPurifier.addHook('afterSanitizeAttributes', (node) => { | ||
| if (!(node instanceof Element) || node.tagName !== 'A') { | ||
| return; | ||
| } | ||
| // Links are always opened in a new tab, so that the dashboard being viewed is not left. | ||
| node.setAttribute('target', '_blank'); | ||
| node.setAttribute('rel', 'noopener noreferrer'); | ||
| }); | ||
| } | ||
| } | ||
| return descriptionPurifier; | ||
| } | ||
|
|
||
| /** | ||
| * Escapes the HTML special characters of a text, so that it is displayed as-is instead of being interpreted as HTML. | ||
| * Used for raw HTML in descriptions, and as a safe fallback when DOMPurify is not supported and the rendered Markdown | ||
| * therefore cannot be sanitized. | ||
| */ | ||
| function escapeHTML(text: string): string { | ||
| return text | ||
| .replace(/&/g, '&') | ||
| .replace(/</g, '<') | ||
| .replace(/>/g, '>') | ||
| .replace(/"/g, '"') | ||
| .replace(/'/g, '''); | ||
| } | ||
|
|
||
| /** | ||
| * Converts a (GitHub Flavored) Markdown panel description into sanitized HTML. Raw HTML is displayed as text. | ||
| * When HTML cannot be sanitized (no DOM available), the description is returned as escaped plain text. | ||
| */ | ||
| export function panelDescriptionToHTML(description: string): string { | ||
| const purifier = getDescriptionPurifier(); | ||
| if (!purifier.isSupported) { | ||
| return escapeHTML(description); | ||
| } | ||
| const html = descriptionMarked.parse(description, { async: false }); | ||
| return purifier.sanitize(html, { | ||
| ADD_ATTR: ['target', 'rel'], | ||
| FORBID_TAGS: FORBIDDEN_TAGS, | ||
| FORBID_ATTR: FORBIDDEN_ATTRIBUTES, | ||
| }); | ||
| } | ||
|
|
||
| export interface PanelDescriptionTooltipProps { | ||
| id?: string; | ||
| /** | ||
| * Panel description, written in Markdown. | ||
| */ | ||
| description: string; | ||
| children: ReactNode; | ||
| enterDelay?: number; | ||
| } | ||
|
|
||
| /** | ||
| * Tooltip displaying a panel description rendered as Markdown. | ||
| * The tooltip is interactive, so that links can be clicked and long descriptions can be scrolled. | ||
| */ | ||
| export function PanelDescriptionTooltip({ | ||
| id, | ||
| description, | ||
| children, | ||
| enterDelay, | ||
| }: PanelDescriptionTooltipProps): ReactElement { | ||
| const title = useMemo(() => <PanelDescriptionContent description={description} />, [description]); | ||
| return ( | ||
| <StyledTooltip arrow id={id} placement="top" title={title} enterDelay={enterDelay ?? 500} enterNextDelay={500}> | ||
|
AntoineThebaud marked this conversation as resolved.
Resolved
|
||
| {/* Wrap in a span so that the tooltip always has a child that can hold a ref. */} | ||
| <span>{children}</span> | ||
| </StyledTooltip> | ||
| ); | ||
| } | ||
|
|
||
| // Tooltip content is only mounted when the tooltip is open, so the Markdown is only parsed on demand. | ||
| function PanelDescriptionContent({ description }: { description: string }): ReactElement { | ||
| const innerHTML = useMemo(() => ({ __html: panelDescriptionToHTML(description) }), [description]); | ||
| return <MarkdownContent data-testid="panel-description-content" dangerouslySetInnerHTML={innerHTML} />; | ||
| } | ||
|
|
||
| const MarkdownContent = styled(Box)(({ theme }) => ({ | ||
| ...theme.typography.caption, | ||
| color: theme.palette.text.primary, | ||
| maxHeight: '50vh', | ||
| overflowY: 'auto', | ||
| overflowWrap: 'anywhere', | ||
| '& > :first-child': { marginTop: 0 }, | ||
| '& > :last-child': { marginBottom: 0 }, | ||
| '& p, & ul, & ol, & pre, & table, & blockquote': { | ||
| margin: theme.spacing(0, 0, 1), | ||
| }, | ||
| '& ul, & ol': { paddingLeft: theme.spacing(2.5) }, | ||
| '& h1, & h2, & h3, & h4, & h5, & h6': { | ||
| margin: theme.spacing(1, 0, 0.5), | ||
| fontSize: theme.typography.body2.fontSize, | ||
| fontWeight: theme.typography.fontWeightMedium, | ||
| }, | ||
| '& a': { color: theme.palette.primary.main }, | ||
| '& code': { | ||
| fontFamily: 'monospace', | ||
| fontSize: '0.95em', | ||
| padding: '0.1em 0.3em', | ||
| borderRadius: '3px', | ||
| backgroundColor: theme.palette.action.hover, | ||
| }, | ||
| '& pre': { | ||
| padding: theme.spacing(1), | ||
| overflowX: 'auto', | ||
| borderRadius: '4px', | ||
| backgroundColor: theme.palette.action.hover, | ||
| }, | ||
| '& pre code': { padding: 0, backgroundColor: 'transparent' }, | ||
| '& blockquote': { | ||
| paddingLeft: theme.spacing(1), | ||
| borderLeft: `3px solid ${theme.palette.divider}`, | ||
| color: theme.palette.text.secondary, | ||
| }, | ||
| '& table, & th, & td': { | ||
| padding: theme.spacing(0.5), | ||
| border: `1px solid ${theme.palette.divider}`, | ||
| borderCollapse: 'collapse', | ||
| }, | ||
| '& img': { maxWidth: '100%' }, | ||
| })); | ||
|
|
||
| function PopperClassTooltip({ className, ...props }: TooltipProps): ReactElement { | ||
| const classes = useMemo(() => ({ popper: className }), [className]); | ||
| return <Tooltip {...props} classes={classes} />; | ||
| } | ||
|
|
||
| const StyledTooltip = styled(PopperClassTooltip)(({ theme }) => ({ | ||
| [`& .${tooltipClasses.tooltip}`]: { | ||
| backgroundColor: theme.palette.background.tooltip, | ||
| color: theme.palette.text.primary, | ||
| maxWidth: '500px', | ||
| padding: theme.spacing(1), | ||
| boxShadow: theme.shadows[1], | ||
| }, | ||
| [`& .${tooltipClasses.arrow}`]: { | ||
| color: theme.palette.background.tooltip, | ||
| }, | ||
| })); | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.