Skip to content

Commit

Permalink
feat(search-indexes): add annotations in the editor when there are sy…
Browse files Browse the repository at this point in the history
…ntax errors in the search index definition COMPASS-7246 (#4921)

chore: add anotations in the editor when there are syntax errors
  • Loading branch information
kmruiz authored Oct 2, 2023
1 parent 89d23fd commit 7b7bafb
Showing 1 changed file with 28 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import {
Banner,
rafraf,
} from '@mongodb-js/compass-components';
import type { Annotation } from '@mongodb-js/compass-editor';
import {
CodemirrorMultilineEditor,
createSearchIndexAutocompleter,
Expand Down Expand Up @@ -85,6 +86,11 @@ const footerStyles = css({
gap: spacing[2],
});

type ParsingError = {
message: string;
pos: number | undefined;
};

type BaseSearchIndexModalProps = {
mode: 'create' | 'update';
initialIndexName: string;
Expand Down Expand Up @@ -116,10 +122,28 @@ export const BaseSearchIndexModal: React.FunctionComponent<
const [indexDefinition, setIndexDefinition] = useState(
initialIndexDefinition
);
const [parsingError, setParsingError] = useState<string | undefined>(
const [parsingError, setParsingError] = useState<ParsingError | undefined>(
undefined
);

// https://github.com/mongodb-js/ejson-shell-parser/blob/master/src/index.ts#L30
// Wraps the input in (\n$input\n) so we need to substract 4 chars from the position.
const annotations = useMemo<Annotation[]>(() => {
if (parsingError && parsingError.pos) {
const pos = Math.max(parsingError.pos - 4, 0);
return [
{
message: parsingError.message,
severity: 'error',
from: pos,
to: pos,
},
];
}

return [];
}, [parsingError]);

useTrackOnChange(
'COMPASS-SEARCH-INDEXES-UI',
(track) => {
Expand Down Expand Up @@ -157,15 +181,14 @@ export const BaseSearchIndexModal: React.FunctionComponent<
parseShellBSON(newDefinition);
setIndexDefinition(newDefinition);
} catch (ex) {
setParsingError((ex as Error).message);
setParsingError(ex as ParsingError);
}
},
[setIndexDefinition, setParsingError]
);

const onSubmitIndex = useCallback(() => {
if (parsingError) {
setParsingError('The index definition is invalid.');
return;
}

Expand Down Expand Up @@ -266,12 +289,13 @@ export const BaseSearchIndexModal: React.FunctionComponent<
data-testid="definition-of-search-index"
className={editorStyles}
text={indexDefinition}
annotations={annotations}
onChangeText={onSearchIndexDefinitionChanged}
minLines={16}
completer={completer}
/>
</div>
{parsingError && <WarningSummary warnings={parsingError} />}
{parsingError && <WarningSummary warnings={parsingError.message} />}
{!parsingError && error && <ErrorSummary errors={error} />}
{mode === 'update' && (
<Banner>
Expand Down

0 comments on commit 7b7bafb

Please sign in to comment.