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

Allow formatting PromQL expressions in the UI #11039

Merged
merged 6 commits into from
Jul 21, 2022
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
89 changes: 84 additions & 5 deletions web/ui/react-app/src/pages/graph/ExpressionInput.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import React, { FC, useState, useEffect, useRef } from 'react';
import { Button, InputGroup, InputGroupAddon, InputGroupText } from 'reactstrap';
import { Alert, Button, InputGroup, InputGroupAddon, InputGroupText } from 'reactstrap';

import { EditorView, highlightSpecialChars, keymap, ViewUpdate, placeholder } from '@codemirror/view';
import { EditorState, Prec, Compartment } from '@codemirror/state';
import { bracketMatching, indentOnInput, syntaxHighlighting, syntaxTree } from '@codemirror/language';
import { defaultKeymap, history, historyKeymap, insertNewlineAndIndent } from '@codemirror/commands';
import { highlightSelectionMatches } from '@codemirror/search';
import { lintKeymap } from '@codemirror/lint';
import { diagnosticCount, lintKeymap } from '@codemirror/lint';
import {
autocompletion,
completionKeymap,
Expand All @@ -18,12 +18,13 @@ import {
import { baseTheme, lightTheme, darkTheme, promqlHighlighter } from './CMTheme';

import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faSearch, faSpinner, faGlobeEurope } from '@fortawesome/free-solid-svg-icons';
import { faSearch, faSpinner, faGlobeEurope, faIndent, faCheck } from '@fortawesome/free-solid-svg-icons';
import MetricsExplorer from './MetricsExplorer';
import { usePathPrefix } from '../../contexts/PathPrefixContext';
import { useTheme } from '../../contexts/ThemeContext';
import { CompleteStrategy, PromQLExtension } from '@prometheus-io/codemirror-promql';
import { newCompleteStrategy } from '@prometheus-io/codemirror-promql/dist/esm/complete';
import { API_PATH } from '../../constants/constants';

const promqlExtension = new PromQLExtension();

Expand Down Expand Up @@ -98,6 +99,11 @@ const ExpressionInput: FC<CMExpressionInputProps> = ({
const pathPrefix = usePathPrefix();
const { theme } = useTheme();

const [formatError, setFormatError] = useState<string | null>(null);
const [isFormatting, setIsFormatting] = useState<boolean>(false);
const [exprFormatted, setExprFormatted] = useState<boolean>(false);
const [hasLinterErrors, setHasLinterErrors] = useState<boolean>(false);

// (Re)initialize editor based on settings / setting changes.
useEffect(() => {
// Build the dynamic part of the config.
Expand Down Expand Up @@ -169,7 +175,15 @@ const ExpressionInput: FC<CMExpressionInputProps> = ({
])
),
EditorView.updateListener.of((update: ViewUpdate): void => {
onExpressionChange(update.state.doc.toString());
setHasLinterErrors(diagnosticCount(view.state) > 0);

if (update.docChanged) {
onExpressionChange(update.state.doc.toString());

if (exprFormatted) {
setExprFormatted(false);
Copy link
Member

Choose a reason for hiding this comment

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

so if you format the expression, then the doc changed so exprFormatted is equal to false ?

Copy link
Member

Choose a reason for hiding this comment

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

also you could simply do

onExpressionChange(update.state.doc.toString());
setExprFormatted(false);

Copy link
Member Author

Choose a reason for hiding this comment

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

Yes, the only (weak) reason for the if condition is to not cause yet another React state update when it's not needed (if exprFormatted is already false, we don't need to set it to false), since this happens on every typed character. But yeah, probably it doesn't matter at all. I also tried to do the same with the setHasLinterErrors(), but it led to weird feedback issues due to the lag, so now I'm just always setting it.

}
}
}),
],
});
Expand Down Expand Up @@ -209,6 +223,47 @@ const ExpressionInput: FC<CMExpressionInputProps> = ({
);
};

const formatExpression = () => {
setFormatError(null);
setIsFormatting(true);

fetch(
`${pathPrefix}/${API_PATH}/format_query?${new URLSearchParams({
query: value,
})}`,
{
cache: 'no-store',
credentials: 'same-origin',
}
)
.then((resp) => {
if (!resp.ok && resp.status !== 400) {
throw new Error(`format HTTP request failed: ${resp.statusText}`);
}

return resp.json();
})
.then((json) => {
if (json.status !== 'success') {
throw new Error(json.error || 'invalid response JSON');
}

const view = viewRef.current;
if (view === null) {
return;
}

view.dispatch(view.state.update({ changes: { from: 0, to: view.state.doc.length, insert: json.data } }));
setExprFormatted(true);
})
.catch((err) => {
setFormatError(err.message);
})
.finally(() => {
setIsFormatting(false);
});
};

return (
<>
<InputGroup className="expression-input">
Expand All @@ -220,7 +275,29 @@ const ExpressionInput: FC<CMExpressionInputProps> = ({
<div ref={containerRef} className="cm-expression-input" />
<InputGroupAddon addonType="append">
<Button
className="metrics-explorer-btn"
className="expression-input-action-btn"
title={
isFormatting
? 'Formatting expression'
: exprFormatted
? 'Expression formatted'
: hasLinterErrors
? 'Cannot format invalid expression'
: 'Format expression'
}
onClick={formatExpression}
disabled={isFormatting || exprFormatted || hasLinterErrors}
>
{isFormatting ? (
<FontAwesomeIcon icon={faSpinner} spin />
) : exprFormatted ? (
<FontAwesomeIcon icon={faCheck} />
) : (
<FontAwesomeIcon icon={faIndent} />
)}
</Button>
<Button
className="expression-input-action-btn"
title="Open metrics explorer"
onClick={() => setShowMetricsExplorer(true)}
>
Expand All @@ -232,6 +309,8 @@ const ExpressionInput: FC<CMExpressionInputProps> = ({
</InputGroupAddon>
</InputGroup>

{formatError && <Alert color="danger">Error formatting expression: {formatError}</Alert>}

<MetricsExplorer
show={showMetricsExplorer}
updateShow={setShowMetricsExplorer}
Expand Down
4 changes: 2 additions & 2 deletions web/ui/react-app/src/themes/_shared.scss
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
Example:

$foo = '#000';

2. Add a style rule in _shared.scss (this file) that uses new variable.
Example:

Expand Down Expand Up @@ -58,7 +58,7 @@
.metrics-explorer .metric:hover {
background: $metrics-explorer-bg;
}
button.metrics-explorer-btn {
button.expression-input-action-btn {
color: $input-group-addon-color;
background-color: $input-group-addon-bg;
border: $input-border-width solid $input-group-addon-border-color;
Expand Down