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

[Vega] Replace EUICodeEditor with Monaco #116041

Merged
merged 9 commits into from
Nov 11, 2021
Merged
Show file tree
Hide file tree
Changes from 7 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
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@ export { LANG as CssLang } from './css/constants';
export { LANG as MarkdownLang } from './markdown/constants';
export { LANG as YamlLang } from './yaml/constants';
export { LANG as HandlebarsLang } from './handlebars/constants';
export { LANG as HJsonLang } from './hjson/constants';
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/*
* 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.
*/

export const LANG = 'hjson';
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
/*
* 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 { LangModuleType } from '@kbn/monaco';
import { languageConfiguration, lexerRules } from './language';
import { LANG } from './constants';

export const Lang: LangModuleType = { ID: LANG, languageConfiguration, lexerRules };
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
/*
* 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 { monaco } from '@kbn/monaco';

export const languageConfiguration: monaco.languages.LanguageConfiguration = {
brackets: [
['{', '}'],
['[', ']'],
],
autoClosingPairs: [
{ open: '{', close: '}' },
{ open: '[', close: ']' },
{ open: '"', close: '"', notIn: ['string'] },
],
comments: {
lineComment: '//',
blockComment: ['/*', '*/'],
},
};

export const lexerRules: monaco.languages.IMonarchLanguage = {
defaultToken: '',
tokenPostfix: '',
escapes: /\\(?:[abfnrtv\\"']|x[0-9A-Fa-f]{1,4}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})/,
digits: /-?(?:0|[1-9]\d*)(?:(?:\.\d+)?(?:[eE][+-]?\d+)?)?/,
symbols: /[,:]+/,
tokenizer: {
root: [
[/(@digits)n?/, 'number'],
[/(@symbols)n?/, 'delimiter'],

{ include: '@keyword' },
{ include: '@url' },
{ include: '@whitespace' },
{ include: '@brackets' },
{ include: '@keyName' },
{ include: '@string' },
],

keyword: [[/(?:true|false|null)\b/, 'keyword']],

url: [
[
/(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^\s]{2,}|www\.[a-zA-Z0-9]+\.[^\s]{2,})/,
'string',
],
],

keyName: [[/(?:[^,\{\[\}\]\s]+|"(?:[^"\\]|\\.)*")\s*(?=:)/, 'variable']],

brackets: [[/{/, '@push'], [/}/, '@pop'], [/[[(]/], [/[\])]/]],

whitespace: [
[/[ \t\r\n]+/, ''],
[/\/\*/, 'comment', '@comment'],
[/\/\/.*$/, 'comment'],
],

comment: [
[/[^\/*]+/, 'comment'],
[/\*\//, 'comment', '@pop'],
[/[\/*]/, 'comment'],
],

string: [
[/(?:[^,\{\[\}\]\s]+|"(?:[^"\\]|\\.)*")\s*/, 'string'],
[/"""/, 'string', '@stringLiteral'],
[/"/, 'string', '@stringDouble'],
],

stringDouble: [
[/[^\\"]+/, 'string'],
[/@escapes/, 'string.escape'],
[/\\./, 'string.escape.invalid'],
[/"/, 'string', '@pop'],
],

stringLiteral: [
[/"""/, 'string', '@pop'],
[/\\""""/, 'string', '@pop'],
[/./, 'string'],
],
},
} as monaco.languages.IMonarchLanguage;
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,6 @@ import { Lang as CssLang } from './css';
import { Lang as HandlebarsLang } from './handlebars';
import { Lang as MarkdownLang } from './markdown';
import { Lang as YamlLang } from './yaml';
import { Lang as HJson } from './hjson';

export { CssLang, HandlebarsLang, MarkdownLang, YamlLang };
export { CssLang, HandlebarsLang, MarkdownLang, YamlLang, HJson };
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@
* Side Public License, v 1.
*/
import { registerLanguage } from '@kbn/monaco';
import { CssLang, HandlebarsLang, MarkdownLang, YamlLang } from './languages';
import { CssLang, HandlebarsLang, MarkdownLang, YamlLang, HJson } from './languages';

registerLanguage(CssLang);
registerLanguage(HandlebarsLang);
registerLanguage(MarkdownLang);
registerLanguage(YamlLang);
registerLanguage(HJson);
2 changes: 1 addition & 1 deletion src/plugins/vis_types/vega/kibana.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"ui": true,
"requiredPlugins": ["data", "visualizations", "mapsEms", "expressions", "inspector"],
"optionalPlugins": ["home","usageCollection"],
"requiredBundles": ["kibanaUtils", "kibanaReact", "visDefaultEditor", "esUiShared"],
"requiredBundles": ["kibanaUtils", "kibanaReact", "visDefaultEditor"],
"owner": {
"name": "Vis Editors",
"githubTeam": "kibana-vis-editors"
Expand Down
20 changes: 15 additions & 5 deletions src/plugins/vis_types/vega/public/components/vega_editor.scss
Original file line number Diff line number Diff line change
@@ -1,18 +1,28 @@
.visEditor--vega {
.visEditorSidebar__config {
padding: 0;
display: flex;
flex-direction: row;
overflow: hidden;

min-height: $euiSize * 15;

@include euiBreakpoint('xs', 's', 'm') {
max-height: $euiSize * 15;
}
}
}

.vgaEditor {
@include euiBreakpoint('xs', 's', 'm') {
@include euiScrollBar;
max-height: $euiSize * 15;
overflow-y: auto;
width: 100%;
flex-grow: 1;

.kibanaCodeEditor {
width: 100%;
}
}

.vgaEditor__aceEditorActions {
.vgaEditor__editorActions {
position: absolute;
z-index: $euiZLevel1;
top: $euiSizeS;
Expand Down
114 changes: 72 additions & 42 deletions src/plugins/vis_types/vega/public/components/vega_vis_editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,43 +6,35 @@
* Side Public License, v 1.
*/

import React, { useCallback } from 'react';
import compactStringify from 'json-stringify-pretty-compact';
import { XJsonLang } from '@kbn/monaco';
import useMount from 'react-use/lib/useMount';
import hjson from 'hjson';
import 'brace/mode/hjson';

import React, { useCallback, useState } from 'react';
import compactStringify from 'json-stringify-pretty-compact';
import { i18n } from '@kbn/i18n';

import { VisEditorOptionsProps } from 'src/plugins/visualizations/public';
import { EuiCodeEditor } from '../../../../es_ui_shared/public';
import { CodeEditor, HJsonLang } from '../../../../kibana_react/public';
import { getNotifications } from '../services';
import { VisParams } from '../vega_fn';
import { VegaHelpMenu } from './vega_help_menu';
import { VegaActionsMenu } from './vega_actions_menu';

import './vega_editor.scss';

const aceOptions = {
maxLines: Infinity,
highlightActiveLine: false,
showPrintMargin: false,
tabSize: 2,
useSoftTabs: true,
wrap: true,
};

const hjsonStringifyOptions = {
bracesSameLine: true,
keepWsc: true,
};

function format(
value: string,
stringify: typeof hjson.stringify | typeof compactStringify,
options?: any
) {
try {
const spec = hjson.parse(value, { legacyRoot: false, keepWsc: true });
return stringify(spec, options);

return {
value: stringify(spec, options),
isValid: true,
};
} catch (err) {
// This is a common case - user tries to format an invalid HJSON text
getNotifications().toasts.addError(err, {
Expand All @@ -51,44 +43,82 @@ function format(
}),
});

return value;
return { value, isValid: false };
}
}

function VegaVisEditor({ stateParams, setValue }: VisEditorOptionsProps<VisParams>) {
const onChange = useCallback(
(value: string) => {
const [languageId, setLanguageId] = useState<string>();

useMount(() => {
let specLang = XJsonLang.ID;
try {
JSON.parse(stateParams.spec);
} catch {
specLang = HJsonLang;
}
setLanguageId(specLang);
});

const setSpec = useCallback(
(value: string, specLang?: string) => {
setValue('spec', value);
if (specLang) {
setLanguageId(specLang);
}
},
[setValue]
);

const formatJson = useCallback(
() => setValue('spec', format(stateParams.spec, compactStringify)),
[setValue, stateParams.spec]
);
const onChange = useCallback((value: string) => setSpec(value), [setSpec]);

const formatHJson = useCallback(
() => setValue('spec', format(stateParams.spec, hjson.stringify, hjsonStringifyOptions)),
[setValue, stateParams.spec]
);
const formatJson = useCallback(() => {
const { value, isValid } = format(stateParams.spec, compactStringify);

if (isValid) {
setSpec(value, XJsonLang.ID);
}
}, [setSpec, stateParams.spec]);

const formatHJson = useCallback(() => {
const { value, isValid } = format(stateParams.spec, hjson.stringify, {
bracesSameLine: true,
keepWsc: true,
});

if (isValid) {
setSpec(value, HJsonLang);
}
}, [setSpec, stateParams.spec]);

if (!languageId) {
return null;
}

return (
<div className="vgaEditor">
<EuiCodeEditor
data-test-subj="vega-editor"
mode="hjson"
theme="textmate"
width="100%"
height="auto"
onChange={onChange}
value={stateParams.spec}
setOptions={aceOptions}
/>
<div className="vgaEditor__aceEditorActions">
<div className="vgaEditor" data-test-subj="vega-editor">
<div className="vgaEditor__editorActions">
<VegaHelpMenu />
<VegaActionsMenu formatHJson={formatHJson} formatJson={formatJson} />
</div>
<CodeEditor
width="100%"
height="100%"
languageId={languageId}
value={stateParams.spec}
onChange={onChange}
options={{
lineNumbers: 'on',
fontSize: 12,
minimap: {
enabled: false,
},
folding: true,
wordWrap: 'on',
wrappingIndent: 'indent',
automaticLayout: true,
}}
/>
</div>
);
}
Expand Down
Loading