Skip to content
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

[markdown] chart & tooltip plugins #3479

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@
"remark-emoji": "^2.1.0",
"remark-highlight.js": "^5.2.0",
"remark-parse": "^7.0.2",
"remark-rehype": "^5.0.0",
"remark-rehype": "^6.0.0",
"resize-observer-polyfill": "^1.5.0",
"tabbable": "^3.0.0",
"unified": "^8.4.2",
Expand Down
20 changes: 17 additions & 3 deletions src-docs/src/views/markdown_editor/markdown_editor.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,26 @@
/* eslint-disable prettier/prettier */
import React, { useState } from 'react';

import { EuiMarkdownEditor } from '../../../../src/components/markdown_editor';
import { defaultParsingPlugins, defaultProcessingPlugins, EuiMarkdownEditor } from '../../../../src/components/markdown_editor';
import * as MarkdownChart from './plugins/markdown_chart';
import * as MarkdownTooltip from './plugins/markdown_tooltip';
Comment on lines +5 to +6
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I know this is just docs, but this wouldn't expose the plugin examples in the docs no? I know they're pretty big. Should we start making separate examples?

I'm likely thinking about docs too early. We can likely clean this up in the later PRs.

Copy link
Contributor Author

@chandlerprall chandlerprall May 15, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm likely thinking about docs too early. We can likely clean this up in the later PRs.

That ^. Tooltips likely moves to be a "default" plugin in the codebase, charts can't unless we make @elastic/charts a dependency. Finding the right boundaries & organization, then these docs can follow without a lot of re-writing.

this wouldn't expose the plugin examples in the docs no?

These imports are for the plugin definitions themselves, not doc sections. They are enabling the plugins for use within the existing docs section.

Copy link
Contributor

@snide snide May 15, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The reason I ask is because they live in src-docs. So right now you can't see how they work from the built docs site, you just see the import, but all the code you could learn from is hidden away.

Copy link
Contributor Author

@chandlerprall chandlerprall May 16, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Gotcha. That'll be better captured through helper utils & specific documentation. I left them in src-docs for now more as a "this isn't finalized yet" indicator than anything, so kinda purposefully obscuring 😀


// eslint-disable-next-line
const markdownExample = require('!!raw-loader!./markdown-example.md');

const exampleParsingList = [
...defaultParsingPlugins,
MarkdownChart.parser,
MarkdownTooltip.parser,
];

const exampleProcessingList = [...defaultProcessingPlugins]; // pretend mutation doesn't happen immediately next 😅
exampleProcessingList[0][1].handlers.chartDemoPlugin = MarkdownChart.handler;
exampleProcessingList[1][1].components.chartDemoPlugin = MarkdownChart.renderer;

exampleProcessingList[0][1].handlers.tooltipPlugin = MarkdownTooltip.handler;
exampleProcessingList[1][1].components.tooltipPlugin = MarkdownTooltip.renderer;

export default () => {
const [value, setValue] = useState(markdownExample);
return <EuiMarkdownEditor value={value} onChange={setValue} height={400} />;
return <EuiMarkdownEditor value={value} onChange={setValue} height={400} uiPlugins={[MarkdownChart.plugin, MarkdownTooltip.plugin]} parsingPluginList={exampleParsingList} processingPluginList={exampleProcessingList} />;
};
156 changes: 156 additions & 0 deletions src-docs/src/views/markdown_editor/plugins/markdown_chart.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
import React from 'react';
import {
Chart,
Settings,
Axis,
BarSeries,
DataGenerator,
} from '@elastic/charts';
import { EUI_CHARTS_THEME_LIGHT } from '../../../../../src/themes/charts/themes';
import {
euiPaletteColorBlind,
euiPaletteComplimentary,
euiPaletteCool,
euiPaletteForStatus,
euiPaletteForTemperature,
euiPaletteGray,
euiPaletteNegative,
euiPalettePositive,
euiPaletteWarm,
} from '../../../../../src/services/color';

const paletteData = {
euiPaletteColorBlind,
euiPaletteForStatus,
euiPaletteForTemperature,
euiPaletteComplimentary,
euiPaletteNegative,
euiPalettePositive,
euiPaletteCool,
euiPaletteWarm,
euiPaletteGray,
};
const paletteNames = Object.keys(paletteData);

const dg = new DataGenerator();
const data = dg.generateGroupedSeries(20, 5);

const chartDemoPlugin = {
name: 'chartDemoPlugin',
button: {
label: 'Chart',
iconType: 'visArea',
},
formatting: {
prefix: '!{chart',
suffix: '}',
trimFirst: true,
},
};

function ChartParser() {
const Parser = this.Parser;
const tokenizers = Parser.prototype.inlineTokenizers;
const methods = Parser.prototype.inlineMethods;

function tokenizeChart(eat, value, silent) {
if (value.startsWith('!{chart') === false) return false;

const nextChar = value[7];

if (nextChar !== ' ' && nextChar !== '}') return false; // this isn't actually a chart

if (silent) {
return true;
}

// is there a configuration?
const hasConfiguration = nextChar === ' ';

let match = '!{chart';
let configuration = {};

if (hasConfiguration) {
match += ' ';
let configurationString = '';

let openObjects = 0;

for (let i = 8; i < value.length; i++) {
const char = value[i];
if (char === '{') {
openObjects++;
configurationString += char;
} else if (char === '}') {
openObjects--;
if (openObjects === -1) {
break;
}
configurationString += char;
} else {
configurationString += char;
}
}

match += configurationString;
try {
configuration = JSON.parse(configurationString);
// eslint-disable-next-line no-empty
} catch (e) {}
}

match += '}';
return eat(match)({
type: 'chartDemoPlugin',
configuration,
});
}
tokenizeChart.notInBlock = true;
tokenizeChart.notInList = true;
tokenizeChart.notInLink = true;

tokenizeChart.locator = function locateChart(value, fromIndex) {
return value.indexOf('!{chart', fromIndex);
};

tokenizers.chart = tokenizeChart;
methods.splice(methods.indexOf('text'), 0, 'chart');
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

According to the docs, this is how you inject things so they run before the text parser https://www.npmjs.com/package/remark-parse#extending-the-parser

}

const chartMarkdownHandler = (h, node) => {
return h(node.position, 'chartDemoPlugin', node.configuration, []);
};
const chartMarkdownRenderer = ({ height = 200, palette = 5 }) => {
const customColors = {
colors: {
vizColors: paletteData[paletteNames[palette]](5),
},
};
return (
<Chart size={{ height }}>
<Settings
theme={[customColors, EUI_CHARTS_THEME_LIGHT]}
showLegend={false}
showLegendDisplayValue={false}
/>
<BarSeries
id="status"
name="Status"
data={data}
xAccessor={'x'}
yAccessors={['y']}
splitSeriesAccessors={['g']}
stackAccessors={['g']}
/>
<Axis id="bottom-axis" position="bottom" showGridLines />
<Axis id="left-axis" position="left" showGridLines />
</Chart>
);
};

export {
chartDemoPlugin as plugin,
ChartParser as parser,
chartMarkdownHandler as handler,
chartMarkdownRenderer as renderer,
};
101 changes: 101 additions & 0 deletions src-docs/src/views/markdown_editor/plugins/markdown_tooltip.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
import React from 'react';
import all from 'mdast-util-to-hast/lib/all';
import { EuiToolTip } from '../../../../../src';

const tooltipPlugin = {
name: 'tooltipPlugin',
button: {
label: 'Tooltip',
iconType: 'flag',
},
formatting: {
prefix: '!{tooltip[',
suffix: ']()}',
trimFirst: true,
},
};

function TooltipParser() {
const Parser = this.Parser;
const tokenizers = Parser.prototype.inlineTokenizers;
const methods = Parser.prototype.inlineMethods;

function tokenizeTooltip(eat, value, silent) {
if (value.startsWith('!{tooltip') === false) return false;

const nextChar = value[9];

if (nextChar !== '[') return false; // this isn't actually a tooltip

let index = 9;
function readArg(open, close) {
if (value[index] !== open) throw 'Expected left bracket';
index++;

let body = '';
let openBrackets = 0;

for (index; index < value.length; index++) {
const char = value[index];

if (char === close && openBrackets === 0) {
index++;
return body;
} else if (char === close) {
openBrackets--;
} else if (char === open) {
openBrackets++;
}

body += char;
}

return '';
}
const tooltipAnchor = readArg('[', ']');
const tooltipText = readArg('(', ')');

if (!tooltipText || !tooltipAnchor) return false;

if (silent) {
return true;
}

const now = eat.now();
now.column += 11 + tooltipText.length;
now.offset += 11 + tooltipText.length;
const children = this.tokenizeInline(tooltipAnchor, now);

return eat(`!{tooltip[${tooltipAnchor}](${tooltipText})}`)({
type: 'tooltipPlugin',
configuration: { content: tooltipText },
children,
});
}
tokenizeTooltip.notInLink = true;

tokenizeTooltip.locator = function locateTooltip(value, fromIndex) {
return value.indexOf('!{tooltip', fromIndex);
};

tokenizers.tooltip = tokenizeTooltip;
methods.splice(methods.indexOf('text'), 0, 'tooltip');
}

const tooltipMarkdownHandler = (h, node) => {
return h(node.position, 'tooltipPlugin', node.configuration, all(h, node));
};
const tooltipMarkdownRenderer = ({ content, children }) => {
return (
<EuiToolTip content={content}>
<span>{children}</span>
</EuiToolTip>
);
};

export {
tooltipPlugin as plugin,
TooltipParser as parser,
tooltipMarkdownHandler as handler,
tooltipMarkdownRenderer as renderer,
};
31 changes: 13 additions & 18 deletions src/components/markdown_editor/markdown_actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,19 +17,10 @@
* under the License.
*/

interface StyleArgsToUpdate {
prefix?: string;
suffix?: string;
blockPrefix?: string;
blockSuffix?: string;
multiline?: boolean;
replaceNext?: string;
prefixSpace?: boolean;
scanFor?: string;
surroundWithNewlines?: boolean;
orderedList?: boolean;
trimFirst?: boolean;
}
import {
EuiMarkdownEditorUiPlugin,
EuiMarkdownFormatting,
} from './markdown_types';

/**
* Class for applying styles to a text editor. Accepts the HTML ID for the textarea
Expand All @@ -39,17 +30,21 @@ interface StyleArgsToUpdate {
* @param {string} editorID
*/
class MarkdownActions {
editorID: string;
styles: Record<string, StyleArgsToUpdate>;

constructor(editorID: string) {
this.editorID = editorID;
styles: Record<string, EuiMarkdownFormatting>;

constructor(public editorID: string, uiPlugins: EuiMarkdownEditorUiPlugin[]) {
/**
* This object is in the format:
* [nameOfAction]: {[styles to apply]}
*/
this.styles = {
...uiPlugins.reduce<MarkdownActions['styles']>(
(mappedPlugins, { name, formatting }) => {
mappedPlugins[name] = formatting;
return mappedPlugins;
},
{}
),
mdBold: {
prefix: '**',
suffix: '**',
Expand Down
Loading