-
Notifications
You must be signed in to change notification settings - Fork 8.6k
Expand file tree
/
Copy pathexpression.tsx
More file actions
171 lines (151 loc) · 5.99 KB
/
expression.tsx
File metadata and controls
171 lines (151 loc) · 5.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
/*
* 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", the "GNU Affero General Public License v3.0 only", 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", the "GNU Affero General Public
* License v3.0 only", or the "Server Side Public License, v 1".
*/
import type { CodeEditorProps, monaco } from '@kbn/code-editor';
import { CodeEditor } from '@kbn/code-editor';
import React, { useRef, useState, useEffect, useMemo } from 'react';
import { css } from '@emotion/react';
import { useEuiTheme } from '@elastic/eui';
import { useResizeChecker } from '@kbn/react-hooks';
import { DraftGrokExpression, type GrokCollection } from '../models';
import { colourToClassName } from './utils';
// Matches %{SYNTAX:SEMANTIC} and %{SYNTAX:SEMANTIC:TYPE} tokens
const GROK_FIELD_PATTERN_REGEX =
/%\{[A-Z0-9_@#$%&*+=\-\.]+:([A-Za-z0-9_@#$%&*+=\-\.]+)(?::[A-Za-z]+)?\}/g;
export const Expression = ({
grokCollection,
pattern,
onChange,
height = '100px',
dataTestSubj,
}: {
grokCollection: GrokCollection;
pattern: string;
onChange?: (pattern: string) => void;
height?: CodeEditorProps['height'];
dataTestSubj?: string;
}) => {
const [suggestionProvider] = useState(() => {
return grokCollection.getSuggestionProvider();
});
const { euiTheme } = useEuiTheme();
const draftGrokExpression = useMemo(() => {
return new DraftGrokExpression(grokCollection, pattern);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [grokCollection]);
// Sync pattern prop with internal DraftGrokExpression
useEffect(() => {
const currentExpression = draftGrokExpression.getExpression();
if (currentExpression !== pattern) {
draftGrokExpression.updateExpression(pattern);
}
}, [pattern, draftGrokExpression]);
const grokEditorRef = useRef<monaco.editor.IStandaloneCodeEditor | null>(null);
const decorationsRef = useRef<monaco.editor.IEditorDecorationsCollection | null>(null);
const { containerRef, setupResizeChecker, destroyResizeChecker } = useResizeChecker();
// Monaco can't accept inline styles per-decoration; we pass class names via inlineClassName
// and inject the corresponding CSS rules onto the wrapper via Emotion so the classes resolve.
const colourPaletteStyles = useMemo(
() => grokCollection.getColourPaletteStyles(euiTheme),
[euiTheme, grokCollection]
);
const onGrokEditorMount: CodeEditorProps['editorDidMount'] = (
editor: monaco.editor.IStandaloneCodeEditor
) => {
grokEditorRef.current = editor;
decorationsRef.current = editor.createDecorationsCollection();
setupResizeChecker(editor);
updateDecorations(draftGrokExpression, grokEditorRef, decorationsRef);
};
const onGrokEditorWillUnmount: CodeEditorProps['editorWillUnmount'] = () => {
destroyResizeChecker();
};
const onGrokEditorChange: CodeEditorProps['onChange'] = (value) => {
draftGrokExpression.updateExpression(value);
onChange?.(value);
updateDecorations(draftGrokExpression, grokEditorRef, decorationsRef);
};
// Re-apply decorations when the pattern prop changes externally (e.g. form state rewrites
// the value, or another consumer drives the editor).
useEffect(() => {
updateDecorations(draftGrokExpression, grokEditorRef, decorationsRef);
}, [pattern, draftGrokExpression]);
return (
<div
ref={containerRef}
css={css`
${colourPaletteStyles}
`}
style={{
width: '100%',
height,
overflow: 'hidden',
minWidth: 0,
}}
>
<CodeEditor
languageId="grok"
value={pattern}
height={height}
fullWidth={true}
editorDidMount={onGrokEditorMount}
editorWillUnmount={onGrokEditorWillUnmount}
onChange={onGrokEditorChange}
suggestionProvider={suggestionProvider}
dataTestSubj={dataTestSubj}
/>
</div>
);
};
// Scans the editor's current text for `%{SYNTAX:field}` tokens and applies an inline class on
// each so the token background matches the colour assigned to that field by the resolved
// pattern (and by extension the preview-table highlight for the same field).
const updateDecorations = (
draftGrokExpression: DraftGrokExpression,
editorRef: React.MutableRefObject<monaco.editor.IStandaloneCodeEditor | null>,
decorationsCollectionRef: React.MutableRefObject<monaco.editor.IEditorDecorationsCollection | null>
) => {
const editor = editorRef.current;
const decorationsCollection = decorationsCollectionRef.current;
if (!editor || !decorationsCollection) return;
const model = editor.getModel();
if (!model) return;
const fields = draftGrokExpression.getFields();
// Build a field name -> colour lookup from the resolved fields. Multiple capture-group ids
// can share a field name (e.g. same field referenced from two patterns); first one wins.
const fieldColourMap = new Map<string, string>();
for (const [, fieldDef] of fields) {
if (!fieldColourMap.has(fieldDef.name)) {
fieldColourMap.set(fieldDef.name, fieldDef.colour);
}
}
const text = model.getValue();
const decorations: monaco.editor.IModelDeltaDecoration[] = [];
GROK_FIELD_PATTERN_REGEX.lastIndex = 0;
let match: RegExpExecArray | null;
while ((match = GROK_FIELD_PATTERN_REGEX.exec(text)) !== null) {
const fieldName = match[1];
const colour = fieldColourMap.get(fieldName);
if (!colour) continue;
const startPos = model.getPositionAt(match.index);
const endPos = model.getPositionAt(match.index + match[0].length);
decorations.push({
range: {
startLineNumber: startPos.lineNumber,
startColumn: startPos.column,
endLineNumber: endPos.lineNumber,
endColumn: endPos.column,
},
options: {
inlineClassName: colourToClassName(colour),
},
});
}
decorationsCollection.clear();
decorationsCollection.set(decorations);
};