revert to legacy markdown for TSVB Visualizations (#180053)

## Summary

This PR reverts the previous migration from the legacy markdown
component for the Markdown renderer in TSVB visualizations. The
Migration to the new component resulted in a regression where custom CSS
styles don't get applied, because of the change in the document
structure for the new markdown component, the fix proposed
[here](https://github.com/elastic/kibana/pull/179894) would not be
sufficient in the event that the provided user styles are specifically
targeting elements based on the document structure from the legacy
markdown component.


<!-- ### Checklist

Delete any items that are not applicable to this PR.

- [ ] Any text added follows [EUI's writing
guidelines](https://elastic.github.io/eui/#/guidelines/writing), uses
sentence case text and includes [i18n
support](https://github.com/elastic/kibana/blob/main/packages/kbn-i18n/README.md)
- [ ]
[Documentation](https://www.elastic.co/guide/en/kibana/master/development-documentation.html)
was added for features that require explanation or tutorials
- [ ] [Unit or functional
tests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)
were updated or added to match the most common scenarios
- [ ] [Flaky Test
Runner](https://ci-stats.kibana.dev/trigger_flaky_test_runner/1) was
used on any tests changed
- [ ] Any UI touched in this PR is usable by keyboard only (learn more
about [keyboard accessibility](https://webaim.org/techniques/keyboard/))
- [ ] Any UI touched in this PR does not create any new axe failures
(run axe in browser:
[FF](https://addons.mozilla.org/en-US/firefox/addon/axe-devtools/),
[Chrome](https://chrome.google.com/webstore/detail/axe-web-accessibility-tes/lhdoppojpmngadmnindnejefpokejbdd?hl=en-US))
- [ ] If a plugin configuration key changed, check if it needs to be
allowlisted in the cloud and added to the [docker
list](https://github.com/elastic/kibana/blob/main/src/dev/build/tasks/os_packages/docker_generator/resources/base/bin/kibana-docker)
- [ ] This renders correctly on smaller devices using a responsive
layout. (You can test this [in your
browser](https://www.browserstack.com/guide/responsive-testing-on-local-server))
- [ ] This was checked for [cross-browser
compatibility](https://www.elastic.co/support/matrix#matrix_browsers)


### Risk Matrix

Delete this section if it is not applicable to this PR.

Before closing this PR, invite QA, stakeholders, and other developers to
identify risks that should be tested prior to the change/feature
release.

When forming the risk matrix, consider some of the following examples
and how they may potentially impact the change:

| Risk | Probability | Severity | Mitigation/Notes |

|---------------------------|-------------|----------|-------------------------|
| Multiple Spaces&mdash;unexpected behavior in non-default Kibana Space.
| Low | High | Integration tests will verify that all features are still
supported in non-default Kibana Space and when user switches between
spaces. |
| Multiple nodes&mdash;Elasticsearch polling might have race conditions
when multiple Kibana nodes are polling for the same tasks. | High | Low
| Tasks are idempotent, so executing them multiple times will not result
in logical error, but will degrade performance. To test for this case we
add plenty of unit tests around this logic and document manual testing
procedure. |
| Code should gracefully handle cases when feature X or plugin Y are
disabled. | Medium | High | Unit tests will verify that any feature flag
or plugin combination still results in our service operational. |
| [See more potential risk
examples](https://github.com/elastic/kibana/blob/main/RISK_MATRIX.mdx) |


### For maintainers

- [ ] This was checked for breaking API changes and was [labeled
appropriately](https://www.elastic.co/guide/en/kibana/master/contributing.html#kibana-release-notes-process)
-->
This commit is contained in:
Eyo O. Eyo 2024-04-04 19:38:05 +02:00 committed by GitHub
parent 339e24ffe5
commit ee67c20899
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
10 changed files with 645 additions and 6 deletions

View file

@ -56,6 +56,9 @@ export { ValidatedDualRange } from './validated_range';
export type { ToastInput, KibanaReactNotifications } from './notifications';
export { createNotifications } from './notifications';
/** @deprecated use `Markdown` from `@kbn/shared-ux-markdown` */
export { Markdown, MarkdownSimple } from './markdown';
export { toMountPoint } from './util';
export type { ToMountPointOptions } from './util';

View file

@ -0,0 +1,60 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`props markdown 1`] = `
<div
className="kbnMarkdown__body"
dangerouslySetInnerHTML={
Object {
"__html": "<p>I am <em>some</em> <a href=\\"https://en.wikipedia.org/wiki/Content\\">content</a> with <code>markdown</code></p>
",
}
}
/>
`;
exports[`props openLinksInNewTab 1`] = `
<div
className="kbnMarkdown__body"
dangerouslySetInnerHTML={
Object {
"__html": "<p>I am <em>some</em> <a href=\\"https://en.wikipedia.org/wiki/Content\\" target=\\"_blank\\" rel=\\"noopener noreferrer\\">content</a> with <code>markdown</code></p>
",
}
}
/>
`;
exports[`props whiteListedRules 1`] = `
<div
className="kbnMarkdown__body"
dangerouslySetInnerHTML={
Object {
"__html": "<p>I am <em>some</em> [content](https://en.wikipedia.org/wiki/Content) with <code>markdown</code></p>
",
}
}
/>
`;
exports[`render 1`] = `
<div
className="kbnMarkdown__body"
dangerouslySetInnerHTML={
Object {
"__html": "",
}
}
/>
`;
exports[`should never render html tags 1`] = `
<div
className="kbnMarkdown__body"
dangerouslySetInnerHTML={
Object {
"__html": "<p>&lt;div&gt;I may be dangerous if rendered as html&lt;/div&gt;</p>
",
}
}
/>
`;

View file

@ -0,0 +1,328 @@
// Default styles for Markdown element
//
// 1. Links
// 2. Headings
// 3. Images
// 4. Blockquotes
// 5. Horizontal rules
// 6. Lists
// 7. Tables
// 8. Code blocks
// Functions
// Note: The inlined base font size is set in common/functions/font.js. It should match $kbnMdFontSize.
$kbnDefaultFontSize: 14px;
@function canvasToEm($size) {
@return #{calc($size / $kbnDefaultFontSize)}em;
}
.kbnMarkdown__body {
// Font size variables
$kbnMarkdownFontSizeS: canvasToEm(12px);
$kbnMarkdownFontSize: canvasToEm(14px);
$kbnMarkdownFontSizeL: canvasToEm(20px);
$kbnMarkdownFontSizeXL: canvasToEm(28px);
$kbnMarkdownFontSizeXXL: canvasToEm(36px);
// Spacing variables
$kbnMarkdownSizeL: canvasToEm(24px);
$kbnMarkdownSize: canvasToEm(16px);
$kbnMarkdownSizeS: canvasToEm(12px);
$kbnMarkdownSizeXS: canvasToEm(8px);
$kbnMarkdownSizeXXS: canvasToEm(4px);
// Grayscale variables
$kbnMarkdownAlphaLightestShade: rgba($euiColorFullShade, .05);
$kbnMarkdownAlphaLightShade: rgba($euiColorFullShade, .15);
$kbnMarkdownAlphaDarkShade: rgba($euiColorFullShade, .65);
// Reverse grayscale for opposite of theme
$kbnMarkdownAlphaLightestShadeReversed: rgba($euiColorEmptyShade, .05);
$kbnMarkdownAlphaLightShadeReversed: rgba($euiColorEmptyShade, .15);
$kbnMarkdownAlphaDarkShadeReversed: rgba($euiColorEmptyShade, .65);
&--reversed {
color: $euiColorLightestShade;
}
> *:first-child {
margin-top: 0 !important;
}
> *:last-child {
margin-bottom: 0 !important;
}
p,
blockquote,
ul,
ol,
dl,
table,
pre {
margin-top: 0;
margin-bottom: $kbnMarkdownSize;
line-height: 1.5em;
}
strong {
font-weight: 600;
}
// 1. Links
a {
color: inherit;
text-decoration: underline;
}
a:hover {
text-decoration: underline dotted;
}
a:active,
a:hover {
outline-width: 0;
}
a:not([href]) {
color: inherit;
text-decoration: none;
}
// 2. Headings
h1,
h2,
h3,
h4,
h5,
h6 {
margin-top: 0;
margin-bottom: $kbnMarkdownSizeXS;
}
h1 {
font-size: $kbnMarkdownFontSizeXXL;
line-height: 1.333333em;
font-weight: 300;
}
h2 {
font-size: $kbnMarkdownFontSizeXL;
line-height: 1.428571em;
font-weight: 300;
}
h3 {
font-size: $kbnMarkdownFontSizeL;
line-height: 1.6em;
font-weight: 600;
}
h4 {
font-size: $kbnMarkdownSize;
line-height: 1.5em;
font-weight: 600;
}
h5 {
font-size: $kbnMarkdownFontSize;
line-height: 1.142857em;
font-weight: 700;
}
h6 {
font-size: $kbnMarkdownFontSizeS;
line-height: 1.333333em;
font-weight: 700;
text-transform: uppercase;
}
// 3. Images
img {
max-width: 100%;
box-sizing: content-box;
border-style: none;
pointer-events: auto;
}
// 4. Blockquotes
blockquote {
padding: 0 1em;
border-left: $kbnMarkdownSizeXXS solid $kbnMarkdownAlphaLightShade;
}
&--reversed blockquote {
border-left-color: $kbnMarkdownAlphaLightShadeReversed;
}
// 5. Horizontal rules
hr {
overflow: hidden;
background: transparent;
height: 2px;
padding: 0;
margin: $kbnMarkdownSizeL 0;
background-color: $kbnMarkdownAlphaLightShade;
border: 0;
}
&--reversed hr {
background-color: $kbnMarkdownAlphaLightShadeReversed;
}
hr::before {
display: table;
content: '';
}
hr::after {
display: table;
clear: both;
content: '';
}
// 6. Lists
ul,
ol {
padding-left: $kbnMarkdownSizeL;
margin-top: 0;
margin-bottom: $kbnMarkdownSize;
}
ul {
list-style-type: disc;
}
ol {
list-style-type: decimal;
}
ul ul {
list-style-type: circle;
}
ol ol,
ul ol {
list-style-type: lower-roman;
}
ul ul ol,
ul ol ol,
ol ul ol,
ol ol ol {
list-style-type: lower-alpha;
}
dd {
margin-left: 0;
}
ul ul,
ul ol,
ol ol,
ol ul {
margin-top: 0;
margin-bottom: 0;
}
li > p {
margin-bottom: $kbnMarkdownSizeXS;
}
li + li {
margin-top: $kbnMarkdownSizeXXS;
}
// 7. Tables
table {
display: block;
width: 100%;
overflow: auto;
border-left: 1px solid $kbnMarkdownAlphaLightShade;
border-spacing: 0;
border-collapse: collapse;
}
&--reversed table {
border-left-color: $kbnMarkdownAlphaLightShadeReversed;
}
td,
th {
padding: 0;
}
table th,
table td {
padding: $kbnMarkdownSizeXXS $kbnMarkdownSizeS;
border-top: 1px solid $kbnMarkdownAlphaLightShade;
border-bottom: 1px solid $kbnMarkdownAlphaLightShade;
&:last-child {
border-right: 1px solid $kbnMarkdownAlphaLightShade;
}
}
&--reversed table th,
&--reversed table td {
border-color: $kbnMarkdownAlphaLightShadeReversed;
}
table tr {
background-color: transparent;
border-top: 1px solid $kbnMarkdownAlphaLightShade;
}
&--reversed table tr {
border-top-color: $kbnMarkdownAlphaLightShadeReversed;
}
// 8. Code blocks
code,
pre {
margin-bottom: $kbnMarkdownSizeXS;
font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace;
font-size: $kbnMarkdownFontSizeS;
}
code {
padding: $kbnMarkdownSizeXXS 0;
margin: 0;
background-color: $kbnMarkdownAlphaLightestShade;
border-radius: $kbnMarkdownSizeXXS;
}
&--reversed code {
background-color: $kbnMarkdownAlphaLightestShadeReversed;
}
code::before,
code::after {
letter-spacing: -.2em;
content: '\00a0';
}
pre {
padding: $kbnMarkdownSize;
overflow: auto;
font-size: $kbnMarkdownFontSizeS;
line-height: 1.333333em;
background-color: $kbnMarkdownAlphaLightestShade;
border-radius: $kbnMarkdownSizeXXS;
word-wrap: normal;
}
&--reversed pre {
background-color: $kbnMarkdownAlphaLightestShadeReversed;
}
pre code {
display: inline;
max-width: auto;
padding: 0;
overflow: visible;
line-height: inherit;
word-wrap: normal;
white-space: pre;
background-color: transparent;
border: 0;
}
pre code::before,
pre code::after {
content: normal;
}
}

View file

@ -0,0 +1 @@
@import './markdown';

View file

@ -0,0 +1,34 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import React from 'react';
import { EuiSkeletonText, EuiDelayRender } from '@elastic/eui';
import type { MarkdownSimpleProps } from './markdown_simple';
import type { MarkdownProps } from './markdown';
const Fallback = () => (
<EuiDelayRender>
<EuiSkeletonText lines={3} />
</EuiDelayRender>
);
/** @deprecated use `Markdown` from `@kbn/shared-ux-markdown` */
const LazyMarkdownSimple = React.lazy(() => import('./markdown_simple'));
export const MarkdownSimple = (props: MarkdownSimpleProps) => (
<React.Suspense fallback={<Fallback />}>
<LazyMarkdownSimple {...props} />
</React.Suspense>
);
/** @deprecated use `Markdown` from `@kbn/shared-ux-markdown` */
const LazyMarkdown = React.lazy(() => import('./markdown'));
export const Markdown = (props: MarkdownProps) => (
<React.Suspense fallback={<Fallback />}>
<LazyMarkdown {...props} />
</React.Suspense>
);

View file

@ -0,0 +1,83 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import React from 'react';
import { shallow } from 'enzyme';
import { Markdown } from './markdown';
test('render', () => {
const component = shallow(<Markdown />);
expect(component).toMatchSnapshot();
});
test('should never render html tags', () => {
const component = shallow(
<Markdown markdown="<div>I may be dangerous if rendered as html</div>" />
);
expect(component).toMatchSnapshot();
});
test('should render links with parentheses correctly', () => {
const component = shallow(
<Markdown markdown="[link](https://example.com/foo/bar?group=(()filters:!t))" />
);
expect(component.render().find('a').prop('href')).toBe(
'https://example.com/foo/bar?group=(()filters:!t)'
);
});
test('should add `noreferrer` and `nooopener` to all links in new tabs', () => {
const component = shallow(
<Markdown
openLinksInNewTab={true}
markdown="[link](https://example.com/foo/bar?group=(()filters:!t))"
/>
);
expect(component.render().find('a').prop('rel')).toBe('noopener noreferrer');
});
describe('props', () => {
const markdown = 'I am *some* [content](https://en.wikipedia.org/wiki/Content) with `markdown`';
test('markdown', () => {
const component = shallow(<Markdown markdown={markdown} />);
expect(component).toMatchSnapshot();
});
test('openLinksInNewTab', () => {
const component = shallow(<Markdown openLinksInNewTab={true} markdown={markdown} />);
expect(component).toMatchSnapshot();
});
test('whiteListedRules', () => {
const component = shallow(
<Markdown whiteListedRules={['backticks', 'emphasis']} markdown={markdown} />
);
expect(component).toMatchSnapshot();
});
test('should update markdown when openLinksInNewTab prop change', () => {
const component = shallow(<Markdown openLinksInNewTab={false} markdown={markdown} />);
expect(component.render().find('a').prop('target')).not.toBe('_blank');
component.setProps({ openLinksInNewTab: true });
expect(component.render().find('a').prop('target')).toBe('_blank');
});
test('should update markdown when whiteListedRules prop change', () => {
const md = '*emphasis* `backticks`';
const component = shallow(
<Markdown whiteListedRules={['emphasis', 'backticks']} markdown={md} />
);
expect(component.render().find('em')).toHaveLength(1);
expect(component.render().find('code')).toHaveLength(1);
component.setProps({ whiteListedRules: ['backticks'] });
expect(component.render().find('code')).toHaveLength(1);
expect(component.render().find('em')).toHaveLength(0);
});
});

View file

@ -0,0 +1,109 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import classNames from 'classnames';
import React, { useEffect } from 'react';
import MarkdownIt from 'markdown-it';
import { memoize } from 'lodash';
import { getSecureRelForTarget } from '@elastic/eui';
import './index.scss';
/**
* Return a memoized markdown rendering function that use the specified
* whiteListedRules and openLinksInNewTab configurations.
* @param {Array of Strings} whiteListedRules - white list of markdown rules
* list of rules can be found at https://github.com/markdown-it/markdown-it/issues/361
* @param {Boolean} openLinksInNewTab
* @return {Function} Returns an Object to use with dangerouslySetInnerHTML
* with the rendered markdown HTML
*/
export const markdownFactory = memoize(
(whiteListedRules: string[] = [], openLinksInNewTab: boolean = false) => {
let markdownIt: MarkdownIt;
// It is imperative that the html config property be set to false, to mitigate XSS: the output of markdown-it is
// fed directly to the DOM via React's dangerouslySetInnerHTML below.
if (whiteListedRules && whiteListedRules.length > 0) {
markdownIt = new MarkdownIt('zero', { html: false, linkify: true });
markdownIt.enable(whiteListedRules);
} else {
markdownIt = new MarkdownIt({ html: false, linkify: true });
}
if (openLinksInNewTab) {
// All links should open in new browser tab.
// Define custom renderer to add 'target' attribute
// https://github.com/markdown-it/markdown-it/blob/master/docs/architecture.md#renderer
const originalLinkRender =
markdownIt.renderer.rules.link_open ||
function (tokens, idx, options, env, self) {
return self.renderToken(tokens, idx, options);
};
markdownIt.renderer.rules.link_open = function (tokens, idx, options, env, self) {
const href = tokens[idx].attrGet('href');
const target = '_blank';
const rel = getSecureRelForTarget({ href: href === null ? undefined : href, target });
// https://www.jitbit.com/alexblog/256-targetblank---the-most-underestimated-vulnerability-ever/
tokens[idx].attrPush(['target', target]);
if (rel) {
tokens[idx].attrPush(['rel', rel]);
}
return originalLinkRender(tokens, idx, options, env, self);
};
}
/**
* This method is used to render markdown from the passed parameter
* into HTML. It will just return an empty string when the markdown is empty.
* @param {String} markdown - The markdown String
* @return {String} - Returns the rendered HTML as string.
*/
return (markdown: string) => {
return markdown ? markdownIt.render(markdown) : '';
};
},
(whiteListedRules: string[] = [], openLinksInNewTab: boolean = false) => {
return `${whiteListedRules.join('_')}${openLinksInNewTab}`;
}
);
export interface MarkdownProps extends React.HTMLAttributes<HTMLDivElement> {
className?: string;
markdown?: string;
openLinksInNewTab?: boolean;
whiteListedRules?: string[];
onRender?: () => void;
}
export const Markdown = (props: MarkdownProps) => {
useEffect(() => {
props.onRender?.();
}, [props]);
const { className, markdown = '', openLinksInNewTab, whiteListedRules, ...rest } = props;
const classes = classNames('kbnMarkdown__body', className);
const markdownRenderer = markdownFactory(whiteListedRules, openLinksInNewTab);
const renderedMarkdown = markdownRenderer(markdown);
return (
<div
{...rest}
className={classes}
/*
* Justification for dangerouslySetInnerHTML:
* The Markdown Visualization is, believe it or not, responsible for rendering Markdown.
* This relies on `markdown-it` to produce safe and correct HTML.
*/
dangerouslySetInnerHTML={{ __html: renderedMarkdown }} // eslint-disable-line react/no-danger
/>
);
};
// Needed for React.lazy
// eslint-disable-next-line import/no-default-export
export default Markdown;

View file

@ -0,0 +1,23 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import React from 'react';
import ReactMarkdown from 'react-markdown';
export interface MarkdownSimpleProps {
children: string;
}
// Render markdown string into JSX inside of a Fragment.
export const MarkdownSimple = ({ children }: MarkdownSimpleProps) => (
<ReactMarkdown>{children}</ReactMarkdown>
);
// Needed for React.lazy
// eslint-disable-next-line import/no-default-export
export default MarkdownSimple;

View file

@ -11,7 +11,7 @@ import React from 'react';
import classNames from 'classnames';
import { get } from 'lodash';
import { ClassNames } from '@emotion/react';
import { Markdown } from '@kbn/shared-ux-markdown';
import { Markdown } from '@kbn/kibana-react-plugin/public';
import { ErrorComponent } from '../../error';
import { replaceVars } from '../../lib/replace_vars';
@ -79,11 +79,9 @@ function MarkdownVisualization(props) {
{!markdownError && (
<Markdown
onRender={initialRender}
markdown={markdownSource}
openLinksInNewTab={model.markdown_openLinksInNewTab}
readOnly
>
{markdownSource}
</Markdown>
/>
)}
</div>
</div>

View file

@ -80,7 +80,7 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) {
const html = '<h1>hello world</h1>';
await visualBuilder.enterMarkdown(html);
const markdownText = await visualBuilder.getMarkdownText();
expect(markdownText).to.be('');
expect(markdownText).to.be(html);
});
it('markdown variables should be clickable', async () => {