queryField.tsx 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  1. import {CSSProperties} from 'react';
  2. import * as React from 'react';
  3. import {components, OptionProps, SingleValueProps} from 'react-select';
  4. import styled from '@emotion/styled';
  5. import cloneDeep from 'lodash/cloneDeep';
  6. import SelectControl, {ControlProps} from 'app/components/forms/selectControl';
  7. import Tag from 'app/components/tag';
  8. import {t} from 'app/locale';
  9. import space from 'app/styles/space';
  10. import {SelectValue} from 'app/types';
  11. import {
  12. AggregateParameter,
  13. AggregationKey,
  14. ColumnType,
  15. QueryFieldValue,
  16. ValidateColumnTypes,
  17. } from 'app/utils/discover/fields';
  18. import Input from 'app/views/settings/components/forms/controls/input';
  19. import {FieldValue, FieldValueColumns, FieldValueKind} from './types';
  20. type FieldValueOption = SelectValue<FieldValue>;
  21. type FieldOptions = Record<string, FieldValueOption>;
  22. // Intermediate type that combines the current column
  23. // data with the AggregateParameter type.
  24. type ParameterDescription =
  25. | {
  26. kind: 'value';
  27. value: string;
  28. dataType: ColumnType;
  29. required: boolean;
  30. }
  31. | {
  32. kind: 'column';
  33. value: FieldValue | null;
  34. options: FieldValueOption[];
  35. required: boolean;
  36. };
  37. type Props = {
  38. className?: string;
  39. takeFocus?: boolean;
  40. fieldValue: QueryFieldValue;
  41. fieldOptions: FieldOptions;
  42. /**
  43. * The number of columns to render. Columns that do not have a parameter will
  44. * render an empty parameter placeholder. Leave blank to avoid adding spacers.
  45. */
  46. gridColumns?: number;
  47. /**
  48. * Filter the options in the primary selector. Useful if you only want to
  49. * show a subset of selectable items.
  50. *
  51. * NOTE: This is different from passing an already filtered fieldOptions
  52. * list, as tag items in the list may be used as parameters to functions.
  53. */
  54. filterPrimaryOptions?: (option: FieldValueOption) => boolean;
  55. /**
  56. * Function to filter the options that are used as parameters for function/aggregate.
  57. */
  58. filterAggregateParameters?: (option: FieldValueOption) => boolean;
  59. /**
  60. * Whether or not to add labels inside of the input fields, currently only
  61. * used for the metric alert builder.
  62. */
  63. inFieldLabels?: boolean;
  64. /**
  65. * Whether or not to add the tag explaining the FieldValueKind of each field
  66. */
  67. shouldRenderTag?: boolean;
  68. onChange: (fieldValue: QueryFieldValue) => void;
  69. disabled?: boolean;
  70. hidePrimarySelector?: boolean;
  71. hideParameterSelector?: boolean;
  72. };
  73. // Type for completing generics in react-select
  74. type OptionType = {
  75. label: string;
  76. value: FieldValue;
  77. };
  78. class QueryField extends React.Component<Props> {
  79. handleFieldChange = (selected?: FieldValueOption | null) => {
  80. if (!selected) {
  81. return;
  82. }
  83. const {value} = selected;
  84. const current = this.props.fieldValue;
  85. let fieldValue: QueryFieldValue = cloneDeep(this.props.fieldValue);
  86. switch (value.kind) {
  87. case FieldValueKind.TAG:
  88. case FieldValueKind.MEASUREMENT:
  89. case FieldValueKind.BREAKDOWN:
  90. case FieldValueKind.FIELD:
  91. fieldValue = {kind: 'field', field: value.meta.name};
  92. break;
  93. case FieldValueKind.FUNCTION:
  94. if (current.kind === 'field') {
  95. fieldValue = {
  96. kind: 'function',
  97. function: [value.meta.name as AggregationKey, '', undefined],
  98. };
  99. } else if (current.kind === 'function') {
  100. fieldValue = {
  101. kind: 'function',
  102. function: [
  103. value.meta.name as AggregationKey,
  104. current.function[1],
  105. current.function[2],
  106. ],
  107. };
  108. }
  109. break;
  110. default:
  111. throw new Error('Invalid field type found in column picker');
  112. }
  113. if (value.kind === FieldValueKind.FUNCTION) {
  114. value.meta.parameters.forEach((param: AggregateParameter, i: number) => {
  115. if (fieldValue.kind !== 'function') {
  116. return;
  117. }
  118. if (param.kind === 'column') {
  119. const field = this.getFieldOrTagOrMeasurementValue(fieldValue.function[i + 1]);
  120. if (field === null) {
  121. fieldValue.function[i + 1] = param.defaultValue || '';
  122. } else if (
  123. (field.kind === FieldValueKind.FIELD ||
  124. field.kind === FieldValueKind.TAG ||
  125. field.kind === FieldValueKind.MEASUREMENT ||
  126. field.kind === FieldValueKind.BREAKDOWN) &&
  127. validateColumnTypes(param.columnTypes as ValidateColumnTypes, field)
  128. ) {
  129. // New function accepts current field.
  130. fieldValue.function[i + 1] = field.meta.name;
  131. } else {
  132. // field does not fit within new function requirements, use the default.
  133. fieldValue.function[i + 1] = param.defaultValue || '';
  134. fieldValue.function[i + 2] = undefined;
  135. }
  136. } else if (param.kind === 'value') {
  137. fieldValue.function[i + 1] = param.defaultValue || '';
  138. }
  139. });
  140. if (fieldValue.kind === 'function') {
  141. if (value.meta.parameters.length === 0) {
  142. fieldValue.function = [fieldValue.function[0], '', undefined];
  143. } else if (value.meta.parameters.length === 1) {
  144. fieldValue.function[2] = undefined;
  145. }
  146. }
  147. }
  148. this.triggerChange(fieldValue);
  149. };
  150. handleFieldParameterChange = ({value}) => {
  151. const newColumn = cloneDeep(this.props.fieldValue);
  152. if (newColumn.kind === 'function') {
  153. newColumn.function[1] = value.meta.name;
  154. }
  155. this.triggerChange(newColumn);
  156. };
  157. handleScalarParameterChange = (value: string) => {
  158. const newColumn = cloneDeep(this.props.fieldValue);
  159. if (newColumn.kind === 'function') {
  160. newColumn.function[1] = value;
  161. }
  162. this.triggerChange(newColumn);
  163. };
  164. handleRefinementChange = (value: string) => {
  165. const newColumn = cloneDeep(this.props.fieldValue);
  166. if (newColumn.kind === 'function') {
  167. newColumn.function[2] = value;
  168. }
  169. this.triggerChange(newColumn);
  170. };
  171. triggerChange(fieldValue: QueryFieldValue) {
  172. this.props.onChange(fieldValue);
  173. }
  174. getFieldOrTagOrMeasurementValue(name: string | undefined): FieldValue | null {
  175. const {fieldOptions} = this.props;
  176. if (name === undefined) {
  177. return null;
  178. }
  179. const fieldName = `field:${name}`;
  180. if (fieldOptions[fieldName]) {
  181. return fieldOptions[fieldName].value;
  182. }
  183. const measurementName = `measurement:${name}`;
  184. if (fieldOptions[measurementName]) {
  185. return fieldOptions[measurementName].value;
  186. }
  187. const spanOperationBreakdownName = `span_op_breakdown:${name}`;
  188. if (fieldOptions[spanOperationBreakdownName]) {
  189. return fieldOptions[spanOperationBreakdownName].value;
  190. }
  191. const tagName =
  192. name.indexOf('tags[') === 0
  193. ? `tag:${name.replace(/tags\[(.*?)\]/, '$1')}`
  194. : `tag:${name}`;
  195. if (fieldOptions[tagName]) {
  196. return fieldOptions[tagName].value;
  197. }
  198. // Likely a tag that was deleted but left behind in a saved query
  199. // Cook up a tag option so select control works.
  200. if (name.length > 0) {
  201. return {
  202. kind: FieldValueKind.TAG,
  203. meta: {
  204. name,
  205. dataType: 'string',
  206. unknown: true,
  207. },
  208. };
  209. }
  210. return null;
  211. }
  212. getFieldData() {
  213. let field: FieldValue | null = null;
  214. const {fieldValue} = this.props;
  215. let {fieldOptions} = this.props;
  216. if (fieldValue.kind === 'function') {
  217. const funcName = `function:${fieldValue.function[0]}`;
  218. if (fieldOptions[funcName] !== undefined) {
  219. field = fieldOptions[funcName].value;
  220. }
  221. }
  222. if (fieldValue.kind === 'field') {
  223. field = this.getFieldOrTagOrMeasurementValue(fieldValue.field);
  224. fieldOptions = this.appendFieldIfUnknown(fieldOptions, field);
  225. }
  226. let parameterDescriptions: ParameterDescription[] = [];
  227. // Generate options and values for each parameter.
  228. if (
  229. field &&
  230. field.kind === FieldValueKind.FUNCTION &&
  231. field.meta.parameters.length > 0 &&
  232. fieldValue.kind === FieldValueKind.FUNCTION
  233. ) {
  234. parameterDescriptions = field.meta.parameters.map(
  235. (param, index: number): ParameterDescription => {
  236. if (param.kind === 'column') {
  237. const fieldParameter = this.getFieldOrTagOrMeasurementValue(
  238. fieldValue.function[1]
  239. );
  240. fieldOptions = this.appendFieldIfUnknown(fieldOptions, fieldParameter);
  241. return {
  242. kind: 'column',
  243. value: fieldParameter,
  244. required: param.required,
  245. options: Object.values(fieldOptions).filter(
  246. ({value}) =>
  247. (value.kind === FieldValueKind.FIELD ||
  248. value.kind === FieldValueKind.TAG ||
  249. value.kind === FieldValueKind.MEASUREMENT ||
  250. value.kind === FieldValueKind.BREAKDOWN) &&
  251. validateColumnTypes(param.columnTypes as ValidateColumnTypes, value)
  252. ),
  253. };
  254. }
  255. return {
  256. kind: 'value',
  257. value:
  258. (fieldValue.kind === 'function' && fieldValue.function[index + 1]) ||
  259. param.defaultValue ||
  260. '',
  261. dataType: param.dataType,
  262. required: param.required,
  263. };
  264. }
  265. );
  266. }
  267. return {field, fieldOptions, parameterDescriptions};
  268. }
  269. appendFieldIfUnknown(
  270. fieldOptions: FieldOptions,
  271. field: FieldValue | null
  272. ): FieldOptions {
  273. if (!field) {
  274. return fieldOptions;
  275. }
  276. if (field && field.kind === FieldValueKind.TAG && field.meta.unknown) {
  277. // Clone the options so we don't mutate other rows.
  278. fieldOptions = Object.assign({}, fieldOptions);
  279. fieldOptions[field.meta.name] = {label: field.meta.name, value: field};
  280. }
  281. return fieldOptions;
  282. }
  283. renderParameterInputs(parameters: ParameterDescription[]): React.ReactNode[] {
  284. const {
  285. disabled,
  286. inFieldLabels,
  287. filterAggregateParameters,
  288. hideParameterSelector,
  289. } = this.props;
  290. const inputs = parameters.map((descriptor: ParameterDescription, index: number) => {
  291. if (descriptor.kind === 'column' && descriptor.options.length > 0) {
  292. if (hideParameterSelector) {
  293. return null;
  294. }
  295. const aggregateParameters = filterAggregateParameters
  296. ? descriptor.options.filter(filterAggregateParameters)
  297. : descriptor.options;
  298. return (
  299. <SelectControl
  300. key="select"
  301. name="parameter"
  302. placeholder={t('Select value')}
  303. options={aggregateParameters}
  304. value={descriptor.value}
  305. required={descriptor.required}
  306. onChange={this.handleFieldParameterChange}
  307. inFieldLabel={inFieldLabels ? t('Parameter: ') : undefined}
  308. disabled={disabled}
  309. />
  310. );
  311. }
  312. if (descriptor.kind === 'value') {
  313. const handler =
  314. index === 0 ? this.handleScalarParameterChange : this.handleRefinementChange;
  315. const inputProps = {
  316. required: descriptor.required,
  317. value: descriptor.value,
  318. onUpdate: handler,
  319. disabled,
  320. };
  321. switch (descriptor.dataType) {
  322. case 'number':
  323. return (
  324. <BufferedInput
  325. name="refinement"
  326. key="parameter:number"
  327. type="text"
  328. inputMode="numeric"
  329. pattern="[0-9]*(\.[0-9]*)?"
  330. {...inputProps}
  331. />
  332. );
  333. case 'integer':
  334. return (
  335. <BufferedInput
  336. name="refinement"
  337. key="parameter:integer"
  338. type="text"
  339. inputMode="numeric"
  340. pattern="[0-9]*"
  341. {...inputProps}
  342. />
  343. );
  344. default:
  345. return (
  346. <BufferedInput
  347. name="refinement"
  348. key="parameter:text"
  349. type="text"
  350. {...inputProps}
  351. />
  352. );
  353. }
  354. }
  355. throw new Error(`Unknown parameter type encountered for ${this.props.fieldValue}`);
  356. });
  357. // Add enough disabled inputs to fill the grid up.
  358. // We always have 1 input.
  359. const {gridColumns} = this.props;
  360. const requiredInputs = (gridColumns ?? inputs.length + 1) - inputs.length - 1;
  361. if (gridColumns !== undefined && requiredInputs > 0) {
  362. for (let i = 0; i < requiredInputs; i++) {
  363. inputs.push(<BlankSpace key={i} />);
  364. }
  365. }
  366. return inputs;
  367. }
  368. renderTag(kind) {
  369. const {shouldRenderTag} = this.props;
  370. if (shouldRenderTag === false) {
  371. return null;
  372. }
  373. let text, tagType;
  374. switch (kind) {
  375. case FieldValueKind.FUNCTION:
  376. text = 'f(x)';
  377. tagType = 'success';
  378. break;
  379. case FieldValueKind.MEASUREMENT:
  380. text = 'measure';
  381. tagType = 'info';
  382. break;
  383. case FieldValueKind.BREAKDOWN:
  384. text = 'breakdown';
  385. tagType = 'error';
  386. break;
  387. case FieldValueKind.TAG:
  388. text = kind;
  389. tagType = 'warning';
  390. break;
  391. case FieldValueKind.FIELD:
  392. text = kind;
  393. tagType = 'highlight';
  394. break;
  395. default:
  396. text = kind;
  397. }
  398. return <Tag type={tagType}>{text}</Tag>;
  399. }
  400. render() {
  401. const {
  402. className,
  403. takeFocus,
  404. filterPrimaryOptions,
  405. inFieldLabels,
  406. disabled,
  407. hidePrimarySelector,
  408. gridColumns,
  409. } = this.props;
  410. const {field, fieldOptions, parameterDescriptions} = this.getFieldData();
  411. const allFieldOptions = filterPrimaryOptions
  412. ? Object.values(fieldOptions).filter(filterPrimaryOptions)
  413. : Object.values(fieldOptions);
  414. const selectProps: ControlProps<FieldValueOption> = {
  415. name: 'field',
  416. options: Object.values(allFieldOptions),
  417. placeholder: t('(Required)'),
  418. value: field,
  419. onChange: this.handleFieldChange,
  420. inFieldLabel: inFieldLabels ? t('Function: ') : undefined,
  421. disabled,
  422. };
  423. if (takeFocus && field === null) {
  424. selectProps.autoFocus = true;
  425. }
  426. const styles = {
  427. singleValue(provided: CSSProperties) {
  428. const custom = {
  429. display: 'flex',
  430. justifyContent: 'space-between',
  431. alignItems: 'center',
  432. width: 'calc(100% - 10px)',
  433. };
  434. return {...provided, ...custom};
  435. },
  436. option(provided: CSSProperties) {
  437. const custom = {
  438. display: 'flex',
  439. justifyContent: 'space-between',
  440. alignItems: 'center',
  441. width: '100%',
  442. };
  443. return {...provided, ...custom};
  444. },
  445. };
  446. const parameters = this.renderParameterInputs(parameterDescriptions);
  447. return (
  448. <Container
  449. className={className}
  450. gridColumns={gridColumns ? gridColumns : parameters.length + 1}
  451. >
  452. {!hidePrimarySelector && (
  453. <SelectControl
  454. {...selectProps}
  455. styles={!inFieldLabels ? styles : undefined}
  456. components={{
  457. Option: ({label, data, ...props}: OptionProps<OptionType>) => (
  458. <components.Option label={label} data={data} {...props}>
  459. <span data-test-id="label">{label}</span>
  460. {this.renderTag(data.value.kind)}
  461. </components.Option>
  462. ),
  463. SingleValue: ({data, ...props}: SingleValueProps<OptionType>) => (
  464. <components.SingleValue data={data} {...props}>
  465. <span data-test-id="label">{data.label}</span>
  466. {this.renderTag(data.value.kind)}
  467. </components.SingleValue>
  468. ),
  469. }}
  470. />
  471. )}
  472. {parameters}
  473. </Container>
  474. );
  475. }
  476. }
  477. function validateColumnTypes(
  478. columnTypes: ValidateColumnTypes,
  479. input: FieldValueColumns
  480. ): boolean {
  481. if (typeof columnTypes === 'function') {
  482. return columnTypes({name: input.meta.name, dataType: input.meta.dataType});
  483. }
  484. return columnTypes.includes(input.meta.dataType);
  485. }
  486. const Container = styled('div')<{gridColumns: number}>`
  487. display: grid;
  488. grid-template-columns: repeat(${p => p.gridColumns}, 1fr);
  489. grid-column-gap: ${space(1)};
  490. align-items: center;
  491. flex-grow: 1;
  492. `;
  493. type InputProps = React.HTMLProps<HTMLInputElement> & {
  494. onUpdate: (value: string) => void;
  495. value: string;
  496. };
  497. type InputState = {value: string};
  498. /**
  499. * Because controlled inputs fire onChange on every key stroke,
  500. * we can't update the QueryField that often as it would re-render
  501. * the input elements causing focus to be lost.
  502. *
  503. * Using a buffered input lets us throttle rendering and enforce data
  504. * constraints better.
  505. */
  506. class BufferedInput extends React.Component<InputProps, InputState> {
  507. constructor(props: InputProps) {
  508. super(props);
  509. this.input = React.createRef();
  510. }
  511. state: InputState = {
  512. value: this.props.value,
  513. };
  514. private input: React.RefObject<HTMLInputElement>;
  515. get isValid() {
  516. if (!this.input.current) {
  517. return true;
  518. }
  519. return this.input.current.validity.valid;
  520. }
  521. handleBlur = () => {
  522. if (this.isValid) {
  523. this.props.onUpdate(this.state.value);
  524. } else {
  525. this.setState({value: this.props.value});
  526. }
  527. };
  528. handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
  529. if (this.isValid) {
  530. this.setState({value: event.target.value});
  531. }
  532. };
  533. render() {
  534. const {onUpdate: _, ...props} = this.props;
  535. return (
  536. <StyledInput
  537. {...props}
  538. ref={this.input}
  539. className="form-control"
  540. value={this.state.value}
  541. onChange={this.handleChange}
  542. onBlur={this.handleBlur}
  543. />
  544. );
  545. }
  546. }
  547. // Set a min-width to allow shrinkage in grid.
  548. const StyledInput = styled(Input)`
  549. /* Match the height of the select boxes */
  550. height: 41px;
  551. min-width: 50px;
  552. `;
  553. const BlankSpace = styled('div')`
  554. /* Match the height of the select boxes */
  555. height: 41px;
  556. min-width: 50px;
  557. background: ${p => p.theme.backgroundSecondary};
  558. border-radius: ${p => p.theme.borderRadius};
  559. display: flex;
  560. align-items: center;
  561. justify-content: center;
  562. &:after {
  563. font-size: ${p => p.theme.fontSizeMedium};
  564. content: '${t('No parameter')}';
  565. color: ${p => p.theme.gray300};
  566. }
  567. `;
  568. export {QueryField};