|
| 1 | +import React from 'react'; |
| 2 | + |
| 3 | +import {parseYqlQueryWithoutCursor} from '@gravity-ui/websql-autocomplete/yql'; |
| 4 | +import {debounce} from 'lodash'; |
| 5 | +import {MarkerSeverity, editor} from 'monaco-editor'; |
| 6 | + |
| 7 | +import {useCancellableFunction} from '../hooks/useCancellable'; |
| 8 | + |
| 9 | +import i18n from './i18n'; |
| 10 | + |
| 11 | +const owner = 'ydb'; |
| 12 | + |
| 13 | +const debouncedHighlightErrors = debounce(highlightErrors, 500); |
| 14 | + |
| 15 | +export function useUpdateErrorsHighlighting() { |
| 16 | + const highlightErrors = useCancellableFunction(debouncedHighlightErrors); |
| 17 | + const updateErrorsHighlighting = React.useCallback(() => { |
| 18 | + unHighlightErrors(); |
| 19 | + |
| 20 | + highlightErrors(); |
| 21 | + }, [highlightErrors]); |
| 22 | + return updateErrorsHighlighting; |
| 23 | +} |
| 24 | + |
| 25 | +function highlightErrors() { |
| 26 | + const model = window.ydbEditor?.getModel(); |
| 27 | + if (!model) { |
| 28 | + console.error('unable to retrieve model when highlighting errors'); |
| 29 | + return; |
| 30 | + } |
| 31 | + |
| 32 | + const errors = parseYqlQueryWithoutCursor(model.getValue()).errors; |
| 33 | + if (!errors.length) { |
| 34 | + unHighlightErrors(); |
| 35 | + return; |
| 36 | + } |
| 37 | + |
| 38 | + const markers = errors.map( |
| 39 | + (error): editor.IMarkerData => ({ |
| 40 | + message: i18n('context_syntax-error'), |
| 41 | + source: error.message, |
| 42 | + severity: MarkerSeverity.Error, |
| 43 | + startLineNumber: error.startLine, |
| 44 | + startColumn: error.startColumn + 1, |
| 45 | + endLineNumber: error.endLine, |
| 46 | + endColumn: error.endColumn + 1, |
| 47 | + }), |
| 48 | + ); |
| 49 | + editor.setModelMarkers(model, owner, markers); |
| 50 | +} |
| 51 | + |
| 52 | +function unHighlightErrors(): void { |
| 53 | + editor.removeAllMarkers(owner); |
| 54 | +} |
0 commit comments