columnEditCollection.tsx 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847
  1. import {Component, createRef, Fragment, useMemo} from 'react';
  2. import {createPortal} from 'react-dom';
  3. import {css} from '@emotion/react';
  4. import styled from '@emotion/styled';
  5. import {parseArithmetic} from 'sentry/components/arithmeticInput/parser';
  6. import {Button} from 'sentry/components/button';
  7. import ButtonBar from 'sentry/components/buttonBar';
  8. import {SectionHeading} from 'sentry/components/charts/styles';
  9. import Input from 'sentry/components/input';
  10. import {getOffsetOfElement} from 'sentry/components/performance/waterfall/utils';
  11. import {Tooltip} from 'sentry/components/tooltip';
  12. import {IconAdd, IconDelete, IconGrabbable, IconWarning} from 'sentry/icons';
  13. import {t} from 'sentry/locale';
  14. import {space} from 'sentry/styles/space';
  15. import type {MRI, Organization} from 'sentry/types';
  16. import {trackAnalytics} from 'sentry/utils/analytics';
  17. import type {Column} from 'sentry/utils/discover/fields';
  18. import {
  19. AGGREGATIONS,
  20. generateFieldAsString,
  21. hasDuplicate,
  22. isLegalEquationColumn,
  23. } from 'sentry/utils/discover/fields';
  24. import {useMetricsTags} from 'sentry/utils/metrics/useMetricsTags';
  25. import theme from 'sentry/utils/theme';
  26. import {getPointerPosition} from 'sentry/utils/touch';
  27. import usePageFilters from 'sentry/utils/usePageFilters';
  28. import type {UserSelectValues} from 'sentry/utils/userselect';
  29. import {setBodyUserSelect} from 'sentry/utils/userselect';
  30. import {WidgetType} from 'sentry/views/dashboards/types';
  31. import {FieldKey} from 'sentry/views/dashboards/widgetBuilder/issueWidget/fields';
  32. import {SESSIONS_OPERATIONS} from 'sentry/views/dashboards/widgetBuilder/releaseWidget/fields';
  33. import type {generateFieldOptions} from '../utils';
  34. import type {FieldValueOption} from './queryField';
  35. import {QueryField} from './queryField';
  36. import {FieldValueKind} from './types';
  37. type Sources = WidgetType;
  38. type Props = {
  39. // Input columns
  40. columns: Column[];
  41. fieldOptions: ReturnType<typeof generateFieldOptions>;
  42. // Fired when columns are added/removed/modified
  43. onChange: (columns: Column[]) => void;
  44. organization: Organization;
  45. className?: string;
  46. filterAggregateParameters?: (option: FieldValueOption) => boolean;
  47. filterPrimaryOptions?: (option: FieldValueOption) => boolean;
  48. isOnDemandWidget?: boolean;
  49. noFieldsMessage?: string;
  50. showAliasField?: boolean;
  51. source?: Sources;
  52. };
  53. type State = {
  54. draggingGrabbedOffset: undefined | {x: number; y: number};
  55. draggingIndex: undefined | number;
  56. draggingTargetIndex: undefined | number;
  57. error: Map<number, string | undefined>;
  58. isDragging: boolean;
  59. left: undefined | number;
  60. top: undefined | number;
  61. };
  62. const DRAG_CLASS = 'draggable-item';
  63. const GHOST_PADDING = 4;
  64. const MAX_COL_COUNT = 20;
  65. enum PlaceholderPosition {
  66. TOP,
  67. BOTTOM,
  68. }
  69. class ColumnEditCollection extends Component<Props, State> {
  70. state: State = {
  71. isDragging: false,
  72. draggingIndex: void 0,
  73. draggingTargetIndex: void 0,
  74. draggingGrabbedOffset: void 0,
  75. error: new Map(),
  76. left: void 0,
  77. top: void 0,
  78. };
  79. componentDidMount() {
  80. if (!this.portal) {
  81. const portal = document.createElement('div');
  82. portal.style.position = 'absolute';
  83. portal.style.top = '0';
  84. portal.style.left = '0';
  85. portal.style.zIndex = String(theme.zIndex.modal);
  86. this.portal = portal;
  87. document.body.appendChild(this.portal);
  88. }
  89. this.checkColumnErrors(this.props.columns);
  90. }
  91. componentWillUnmount() {
  92. if (this.portal) {
  93. document.body.removeChild(this.portal);
  94. }
  95. this.cleanUpListeners();
  96. }
  97. checkColumnErrors(columns: Column[]) {
  98. const error = new Map();
  99. for (let i = 0; i < columns.length; i += 1) {
  100. const column = columns[i];
  101. if (column.kind === 'equation') {
  102. const result = parseArithmetic(column.field);
  103. if (result.error) {
  104. error.set(i, result.error);
  105. }
  106. }
  107. }
  108. this.setState({error});
  109. }
  110. previousUserSelect: UserSelectValues | null = null;
  111. portal: HTMLElement | null = null;
  112. dragGhostRef = createRef<HTMLDivElement>();
  113. keyForColumn(column: Column, isGhost: boolean): string {
  114. if (column.kind === 'function') {
  115. return [...column.function, isGhost].join(':');
  116. }
  117. return [...column.field, isGhost].join(':');
  118. }
  119. cleanUpListeners() {
  120. if (this.state.isDragging) {
  121. window.removeEventListener('mousemove', this.onDragMove);
  122. window.removeEventListener('touchmove', this.onDragMove);
  123. window.removeEventListener('mouseup', this.onDragEnd);
  124. window.removeEventListener('touchend', this.onDragEnd);
  125. }
  126. }
  127. // Signal to the parent that a new column has been added.
  128. handleAddColumn = () => {
  129. const newColumn: Column = {kind: 'field', field: ''};
  130. this.props.onChange([...this.props.columns, newColumn]);
  131. };
  132. handleAddEquation = () => {
  133. const {organization} = this.props;
  134. const newColumn: Column = {kind: FieldValueKind.EQUATION, field: ''};
  135. trackAnalytics('discover_v2.add_equation', {organization});
  136. this.props.onChange([...this.props.columns, newColumn]);
  137. };
  138. handleUpdateColumn = (index: number, updatedColumn: Column) => {
  139. const newColumns = [...this.props.columns];
  140. if (updatedColumn.kind === 'equation') {
  141. this.setState(prevState => {
  142. const error = new Map(prevState.error);
  143. error.set(index, parseArithmetic(updatedColumn.field).error);
  144. return {
  145. ...prevState,
  146. error,
  147. };
  148. });
  149. } else {
  150. // Update any equations that contain the existing column
  151. this.updateEquationFields(newColumns, index, updatedColumn);
  152. }
  153. newColumns.splice(index, 1, updatedColumn);
  154. this.props.onChange(newColumns);
  155. };
  156. updateEquationFields = (newColumns: Column[], index: number, updatedColumn: Column) => {
  157. const oldColumn = newColumns[index];
  158. const existingColumn = generateFieldAsString(newColumns[index]);
  159. const updatedColumnString = generateFieldAsString(updatedColumn);
  160. if (!isLegalEquationColumn(updatedColumn) || hasDuplicate(newColumns, oldColumn)) {
  161. return;
  162. }
  163. // Find the equations in the list of columns
  164. for (let i = 0; i < newColumns.length; i++) {
  165. const newColumn = newColumns[i];
  166. if (newColumn.kind === 'equation') {
  167. const result = parseArithmetic(newColumn.field);
  168. let newEquation = '';
  169. // Track where to continue from, not reconstructing from result so we don't have to worry
  170. // about spacing
  171. let lastIndex = 0;
  172. // the parser separates fields & functions, so we only need to check one
  173. const fields =
  174. oldColumn.kind === 'function' ? result.tc.functions : result.tc.fields;
  175. // for each field, add the text before it, then the new function and update index
  176. // to be where we want to start again
  177. for (const field of fields) {
  178. if (field.term === existingColumn && lastIndex !== field.location.end.offset) {
  179. newEquation +=
  180. newColumn.field.substring(lastIndex, field.location.start.offset) +
  181. updatedColumnString;
  182. lastIndex = field.location.end.offset;
  183. }
  184. }
  185. // Add whatever remains to be added from the equation, if existing field wasn't found
  186. // add the entire equation
  187. newEquation += newColumn.field.substring(lastIndex);
  188. newColumns[i] = {
  189. kind: 'equation',
  190. field: newEquation,
  191. alias: newColumns[i].alias,
  192. };
  193. }
  194. }
  195. };
  196. removeColumn(index: number) {
  197. const newColumns = [...this.props.columns];
  198. newColumns.splice(index, 1);
  199. this.checkColumnErrors(newColumns);
  200. this.props.onChange(newColumns);
  201. }
  202. startDrag(
  203. event: React.MouseEvent<HTMLElement> | React.TouchEvent<HTMLElement>,
  204. index: number
  205. ) {
  206. const isDragging = this.state.isDragging;
  207. if (isDragging || !['mousedown', 'touchstart'].includes(event.type)) {
  208. return;
  209. }
  210. event.preventDefault();
  211. event.stopPropagation();
  212. const top = getPointerPosition(event, 'pageY');
  213. const left = getPointerPosition(event, 'pageX');
  214. // Compute where the user clicked on the drag handle. Avoids the element
  215. // jumping from the cursor on mousedown.
  216. const draggingElement = Array.from(document.querySelectorAll(`.${DRAG_CLASS}`)).find(
  217. n => n.contains(event.currentTarget)
  218. )!;
  219. const {x, y} = getOffsetOfElement(draggingElement);
  220. const draggingGrabbedOffset = {
  221. x: left - x + GHOST_PADDING,
  222. y: top - y + GHOST_PADDING,
  223. };
  224. // prevent the user from selecting things when dragging a column.
  225. this.previousUserSelect = setBodyUserSelect({
  226. userSelect: 'none',
  227. MozUserSelect: 'none',
  228. msUserSelect: 'none',
  229. webkitUserSelect: 'none',
  230. });
  231. // attach event listeners so that the mouse cursor can drag anywhere
  232. window.addEventListener('mousemove', this.onDragMove);
  233. window.addEventListener('touchmove', this.onDragMove);
  234. window.addEventListener('mouseup', this.onDragEnd);
  235. window.addEventListener('touchend', this.onDragEnd);
  236. this.setState({
  237. isDragging: true,
  238. draggingIndex: index,
  239. draggingTargetIndex: index,
  240. draggingGrabbedOffset,
  241. top,
  242. left,
  243. });
  244. }
  245. onDragMove = (event: MouseEvent | TouchEvent) => {
  246. const {isDragging, draggingTargetIndex, draggingGrabbedOffset} = this.state;
  247. if (!isDragging || !['mousemove', 'touchmove'].includes(event.type)) {
  248. return;
  249. }
  250. event.preventDefault();
  251. event.stopPropagation();
  252. const pointerX = getPointerPosition(event, 'pageX');
  253. const pointerY = getPointerPosition(event, 'pageY');
  254. const dragOffsetX = draggingGrabbedOffset?.x ?? 0;
  255. const dragOffsetY = draggingGrabbedOffset?.y ?? 0;
  256. if (this.dragGhostRef.current) {
  257. // move the ghost box
  258. const ghostDOM = this.dragGhostRef.current;
  259. // Adjust so cursor is over the grab handle.
  260. ghostDOM.style.left = `${pointerX - dragOffsetX}px`;
  261. ghostDOM.style.top = `${pointerY - dragOffsetY}px`;
  262. }
  263. const dragItems = document.querySelectorAll(`.${DRAG_CLASS}`);
  264. // Find the item that the ghost is currently over.
  265. const targetIndex = Array.from(dragItems).findIndex(dragItem => {
  266. const rects = dragItem.getBoundingClientRect();
  267. const top = pointerY;
  268. const thresholdStart = window.scrollY + rects.top;
  269. const thresholdEnd = window.scrollY + rects.top + rects.height;
  270. return top >= thresholdStart && top <= thresholdEnd;
  271. });
  272. // Issue column in Issue widgets are fixed (cannot be moved or deleted)
  273. if (
  274. targetIndex >= 0 &&
  275. targetIndex !== draggingTargetIndex &&
  276. !this.isFixedMetricsColumn(targetIndex)
  277. ) {
  278. this.setState({draggingTargetIndex: targetIndex});
  279. }
  280. };
  281. isFixedIssueColumn = (columnIndex: number) => {
  282. const {source, columns} = this.props;
  283. const column = columns[columnIndex];
  284. const issueFieldColumnCount = columns.filter(
  285. col => col.kind === 'field' && col.field === FieldKey.ISSUE
  286. ).length;
  287. return (
  288. issueFieldColumnCount <= 1 &&
  289. source === WidgetType.ISSUE &&
  290. column.kind === 'field' &&
  291. column.field === FieldKey.ISSUE
  292. );
  293. };
  294. isFixedMetricsColumn = (columnIndex: number) => {
  295. const {source} = this.props;
  296. return source === WidgetType.METRICS && columnIndex === 0;
  297. };
  298. isRemainingReleaseHealthAggregate = (columnIndex: number) => {
  299. const {source, columns} = this.props;
  300. const column = columns[columnIndex];
  301. const aggregateCount = columns.filter(
  302. col => col.kind === FieldValueKind.FUNCTION
  303. ).length;
  304. return (
  305. aggregateCount <= 1 &&
  306. source === WidgetType.RELEASE &&
  307. column.kind === FieldValueKind.FUNCTION
  308. );
  309. };
  310. onDragEnd = (event: MouseEvent | TouchEvent) => {
  311. if (!this.state.isDragging || !['mouseup', 'touchend'].includes(event.type)) {
  312. return;
  313. }
  314. const sourceIndex = this.state.draggingIndex;
  315. const targetIndex = this.state.draggingTargetIndex;
  316. if (typeof sourceIndex !== 'number' || typeof targetIndex !== 'number') {
  317. return;
  318. }
  319. // remove listeners that were attached in startColumnDrag
  320. this.cleanUpListeners();
  321. // restore body user-select values
  322. if (this.previousUserSelect) {
  323. setBodyUserSelect(this.previousUserSelect);
  324. this.previousUserSelect = null;
  325. }
  326. // Reorder columns and trigger change.
  327. const newColumns = [...this.props.columns];
  328. const removed = newColumns.splice(sourceIndex, 1);
  329. newColumns.splice(targetIndex, 0, removed[0]);
  330. this.checkColumnErrors(newColumns);
  331. this.props.onChange(newColumns);
  332. this.setState({
  333. isDragging: false,
  334. left: undefined,
  335. top: undefined,
  336. draggingIndex: undefined,
  337. draggingTargetIndex: undefined,
  338. draggingGrabbedOffset: undefined,
  339. });
  340. };
  341. renderGhost({gridColumns, singleColumn}: {gridColumns: number; singleColumn: boolean}) {
  342. const {isDragging, draggingIndex, draggingGrabbedOffset} = this.state;
  343. const index = draggingIndex;
  344. if (typeof index !== 'number' || !isDragging || !this.portal) {
  345. return null;
  346. }
  347. const dragOffsetX = draggingGrabbedOffset?.x ?? 0;
  348. const dragOffsetY = draggingGrabbedOffset?.y ?? 0;
  349. const top = Number(this.state.top) - dragOffsetY;
  350. const left = Number(this.state.left) - dragOffsetX;
  351. const col = this.props.columns[index];
  352. const style = {
  353. top: `${top}px`,
  354. left: `${left}px`,
  355. };
  356. const ghost = (
  357. <Ghost ref={this.dragGhostRef} style={style}>
  358. {this.renderItem(col, index, {
  359. singleColumn,
  360. isGhost: true,
  361. gridColumns,
  362. })}
  363. </Ghost>
  364. );
  365. return createPortal(ghost, this.portal);
  366. }
  367. renderItem(
  368. col: Column,
  369. i: number,
  370. {
  371. singleColumn = false,
  372. canDelete = true,
  373. canDrag = true,
  374. isGhost = false,
  375. gridColumns = 2,
  376. disabled = false,
  377. }: {
  378. gridColumns: number;
  379. singleColumn: boolean;
  380. canDelete?: boolean;
  381. canDrag?: boolean;
  382. disabled?: boolean;
  383. isGhost?: boolean;
  384. }
  385. ) {
  386. const {
  387. columns,
  388. fieldOptions,
  389. filterAggregateParameters,
  390. filterPrimaryOptions,
  391. noFieldsMessage,
  392. showAliasField,
  393. source,
  394. isOnDemandWidget,
  395. } = this.props;
  396. const {isDragging, draggingTargetIndex, draggingIndex} = this.state;
  397. let placeholder: React.ReactNode = null;
  398. // Add a placeholder above the target row.
  399. if (isDragging && isGhost === false && draggingTargetIndex === i) {
  400. placeholder = (
  401. <DragPlaceholder
  402. key={`placeholder:${this.keyForColumn(col, isGhost)}`}
  403. className={DRAG_CLASS}
  404. />
  405. );
  406. }
  407. // If the current row is the row in the drag ghost return the placeholder
  408. // or a hole if the placeholder is elsewhere.
  409. if (isDragging && isGhost === false && draggingIndex === i) {
  410. return placeholder;
  411. }
  412. const position =
  413. Number(draggingTargetIndex) <= Number(draggingIndex)
  414. ? PlaceholderPosition.TOP
  415. : PlaceholderPosition.BOTTOM;
  416. return (
  417. <Fragment key={`${i}:${this.keyForColumn(col, isGhost)}`}>
  418. {position === PlaceholderPosition.TOP && placeholder}
  419. <RowContainer
  420. showAliasField={showAliasField}
  421. singleColumn={singleColumn}
  422. className={isGhost ? '' : DRAG_CLASS}
  423. >
  424. {canDrag ? (
  425. <DragAndReorderButton
  426. aria-label={t('Drag to reorder')}
  427. onMouseDown={event => this.startDrag(event, i)}
  428. onTouchStart={event => this.startDrag(event, i)}
  429. icon={<IconGrabbable size="xs" />}
  430. size="zero"
  431. borderless
  432. />
  433. ) : singleColumn && showAliasField ? null : (
  434. <span />
  435. )}
  436. {source === WidgetType.METRICS && !this.isFixedMetricsColumn(i) ? (
  437. <MetricTagQueryField
  438. mri={
  439. columns[0].kind === FieldValueKind.FUNCTION
  440. ? columns[0].function[1]
  441. : // We should never get here because the first column should always be function for metrics
  442. undefined
  443. }
  444. gridColumns={gridColumns}
  445. fieldValue={col}
  446. onChange={value => this.handleUpdateColumn(i, value)}
  447. error={this.state.error.get(i)}
  448. takeFocus={i === this.props.columns.length - 1}
  449. otherColumns={columns}
  450. shouldRenderTag
  451. disabled={disabled}
  452. noFieldsMessage={noFieldsMessage}
  453. skipParameterPlaceholder={showAliasField}
  454. />
  455. ) : (
  456. <QueryField
  457. fieldOptions={fieldOptions}
  458. gridColumns={gridColumns}
  459. fieldValue={col}
  460. onChange={value => this.handleUpdateColumn(i, value)}
  461. error={this.state.error.get(i)}
  462. takeFocus={i === this.props.columns.length - 1}
  463. otherColumns={columns}
  464. shouldRenderTag
  465. disabled={disabled}
  466. filterPrimaryOptions={filterPrimaryOptions}
  467. filterAggregateParameters={filterAggregateParameters}
  468. noFieldsMessage={noFieldsMessage}
  469. skipParameterPlaceholder={showAliasField}
  470. />
  471. )}
  472. {showAliasField && (
  473. <AliasField singleColumn={singleColumn}>
  474. <AliasInput
  475. name="alias"
  476. placeholder={t('Alias')}
  477. value={col.alias ?? ''}
  478. onChange={value => {
  479. this.handleUpdateColumn(i, {
  480. ...col,
  481. alias: value.target.value,
  482. });
  483. }}
  484. />
  485. </AliasField>
  486. )}
  487. {canDelete || col.kind === 'equation' ? (
  488. showAliasField ? (
  489. <RemoveButton
  490. data-test-id={`remove-column-${i}`}
  491. aria-label={t('Remove column')}
  492. title={t('Remove column')}
  493. onClick={() => this.removeColumn(i)}
  494. icon={<IconDelete />}
  495. borderless
  496. />
  497. ) : (
  498. <RemoveButton
  499. data-test-id={`remove-column-${i}`}
  500. aria-label={t('Remove column')}
  501. onClick={() => this.removeColumn(i)}
  502. icon={<IconDelete />}
  503. borderless
  504. />
  505. )
  506. ) : singleColumn && showAliasField ? null : (
  507. <span />
  508. )}
  509. {isOnDemandWidget && col.kind === 'equation' ? (
  510. <OnDemandEquationsWarning />
  511. ) : null}
  512. </RowContainer>
  513. {position === PlaceholderPosition.BOTTOM && placeholder}
  514. </Fragment>
  515. );
  516. }
  517. render() {
  518. const {className, columns, showAliasField, source} = this.props;
  519. const canDelete = columns.filter(field => field.kind !== 'equation').length > 1;
  520. const canDrag = columns.length > 1;
  521. const canAdd = columns.length < MAX_COL_COUNT;
  522. const title = canAdd
  523. ? undefined
  524. : t(
  525. `Sorry, you've reached the maximum number of columns (%d). Delete columns to add more.`,
  526. MAX_COL_COUNT
  527. );
  528. const singleColumn = columns.length === 1;
  529. // Get the longest number of columns so we can layout the rows.
  530. // We always want at least 2 columns.
  531. const gridColumns =
  532. source === WidgetType.ISSUE
  533. ? 1
  534. : Math.max(
  535. ...columns.map(col => {
  536. if (col.kind !== 'function') {
  537. return 2;
  538. }
  539. const operation =
  540. AGGREGATIONS[col.function[0]] ?? SESSIONS_OPERATIONS[col.function[0]];
  541. if (!operation || !operation.parameters) {
  542. // Operation should be in the look-up table, but not all operations are (eg. private). This should be changed at some point.
  543. return 3;
  544. }
  545. return operation.parameters.length === 2 ? 3 : 2;
  546. })
  547. );
  548. return (
  549. <div className={className}>
  550. {this.renderGhost({gridColumns, singleColumn})}
  551. {!showAliasField && source !== WidgetType.ISSUE && (
  552. <RowContainer showAliasField={showAliasField} singleColumn={singleColumn}>
  553. <Heading gridColumns={gridColumns}>
  554. <StyledSectionHeading>{t('Tag / Field / Function')}</StyledSectionHeading>
  555. <StyledSectionHeading>{t('Field Parameter')}</StyledSectionHeading>
  556. </Heading>
  557. </RowContainer>
  558. )}
  559. {columns.map((col: Column, i: number) => {
  560. // Issue column in Issue widgets are fixed (cannot be changed or deleted)
  561. if (this.isFixedIssueColumn(i)) {
  562. return this.renderItem(col, i, {
  563. singleColumn,
  564. canDelete: false,
  565. canDrag,
  566. gridColumns,
  567. disabled: true,
  568. });
  569. }
  570. if (this.isRemainingReleaseHealthAggregate(i)) {
  571. return this.renderItem(col, i, {
  572. singleColumn,
  573. canDelete: false,
  574. canDrag,
  575. gridColumns,
  576. });
  577. }
  578. if (this.isFixedMetricsColumn(i)) {
  579. return this.renderItem(col, i, {
  580. singleColumn,
  581. canDelete: false,
  582. canDrag: false,
  583. gridColumns,
  584. });
  585. }
  586. return this.renderItem(col, i, {
  587. singleColumn,
  588. canDelete,
  589. canDrag,
  590. gridColumns,
  591. });
  592. })}
  593. <RowContainer showAliasField={showAliasField} singleColumn={singleColumn}>
  594. <Actions gap={1} showAliasField={showAliasField}>
  595. <Button
  596. size="sm"
  597. aria-label={t('Add a Column')}
  598. onClick={this.handleAddColumn}
  599. title={title}
  600. disabled={!canAdd}
  601. icon={<IconAdd isCircled />}
  602. >
  603. {t('Add a Column')}
  604. </Button>
  605. {WidgetType.ISSUE &&
  606. source !== WidgetType.RELEASE &&
  607. source !== WidgetType.METRICS && (
  608. <Button
  609. size="sm"
  610. aria-label={t('Add an Equation')}
  611. onClick={this.handleAddEquation}
  612. title={title}
  613. disabled={!canAdd}
  614. icon={<IconAdd isCircled />}
  615. >
  616. {t('Add an Equation')}
  617. </Button>
  618. )}
  619. </Actions>
  620. </RowContainer>
  621. </div>
  622. );
  623. }
  624. }
  625. interface MetricTagQueryFieldProps
  626. extends Omit<React.ComponentProps<typeof QueryField>, 'fieldOptions'> {
  627. mri?: string;
  628. }
  629. const EMPTY_ARRAY = [];
  630. function MetricTagQueryField({mri, ...props}: MetricTagQueryFieldProps) {
  631. const {projects} = usePageFilters().selection;
  632. const {data = EMPTY_ARRAY} = useMetricsTags(mri as MRI | undefined, {projects});
  633. const fieldOptions = useMemo(() => {
  634. return data.reduce(
  635. (acc, tag) => {
  636. acc[`tag:${tag.key}`] = {
  637. label: tag.key,
  638. value: {
  639. kind: FieldValueKind.TAG,
  640. meta: {
  641. dataType: 'string',
  642. name: tag.key,
  643. },
  644. },
  645. };
  646. return acc;
  647. },
  648. {} as Record<string, FieldValueOption>
  649. );
  650. }, [data]);
  651. return <QueryField fieldOptions={fieldOptions} {...props} />;
  652. }
  653. function OnDemandEquationsWarning() {
  654. return (
  655. <OnDemandContainer>
  656. <Tooltip
  657. containerDisplayMode="inline-flex"
  658. title={t(
  659. `This is using indexed data because we don't routinely collect metrics for equations.`
  660. )}
  661. >
  662. <IconWarning color="warningText" />
  663. </Tooltip>
  664. </OnDemandContainer>
  665. );
  666. }
  667. const Actions = styled(ButtonBar)<{showAliasField?: boolean}>`
  668. grid-column: ${p => (p.showAliasField ? '1/-1' : ' 2/3')};
  669. justify-content: flex-start;
  670. `;
  671. const RowContainer = styled('div')<{
  672. singleColumn: boolean;
  673. showAliasField?: boolean;
  674. }>`
  675. display: grid;
  676. grid-template-columns: ${space(3)} 1fr 40px 40px;
  677. justify-content: center;
  678. align-items: center;
  679. width: 100%;
  680. touch-action: none;
  681. padding-bottom: ${space(1)};
  682. ${p =>
  683. p.showAliasField &&
  684. css`
  685. align-items: flex-start;
  686. grid-template-columns: ${p.singleColumn ? `1fr` : `${space(3)} 1fr 40px 40px`};
  687. @media (min-width: ${p.theme.breakpoints.small}) {
  688. grid-template-columns: ${p.singleColumn
  689. ? `1fr calc(200px + ${space(1)})`
  690. : `${space(3)} 1fr calc(200px + ${space(1)}) 40px 40px`};
  691. }
  692. `};
  693. `;
  694. const Ghost = styled('div')`
  695. background: ${p => p.theme.background};
  696. display: block;
  697. position: absolute;
  698. padding: ${GHOST_PADDING}px;
  699. border-radius: ${p => p.theme.borderRadius};
  700. box-shadow: 0 0 15px rgba(0, 0, 0, 0.15);
  701. width: 710px;
  702. opacity: 0.8;
  703. cursor: grabbing;
  704. padding-right: ${space(2)};
  705. & > ${RowContainer} {
  706. padding-bottom: 0;
  707. }
  708. & svg {
  709. cursor: grabbing;
  710. }
  711. `;
  712. const OnDemandContainer = styled('div')`
  713. display: flex;
  714. align-items: center;
  715. justify-content: center;
  716. height: 100%;
  717. `;
  718. const DragPlaceholder = styled('div')`
  719. margin: 0 ${space(3)} ${space(1)} ${space(3)};
  720. border: 2px dashed ${p => p.theme.border};
  721. border-radius: ${p => p.theme.borderRadius};
  722. height: ${p => p.theme.form.md.height}px;
  723. `;
  724. const Heading = styled('div')<{gridColumns: number}>`
  725. grid-column: 2 / 3;
  726. /* Emulate the grid used in the column editor rows */
  727. display: grid;
  728. grid-template-columns: repeat(${p => p.gridColumns}, 1fr);
  729. grid-column-gap: ${space(1)};
  730. `;
  731. const StyledSectionHeading = styled(SectionHeading)`
  732. margin: 0;
  733. `;
  734. const AliasInput = styled(Input)`
  735. min-width: 50px;
  736. `;
  737. const AliasField = styled('div')<{singleColumn: boolean}>`
  738. margin-top: ${space(1)};
  739. @media (min-width: ${p => p.theme.breakpoints.small}) {
  740. margin-top: 0;
  741. margin-left: ${space(1)};
  742. }
  743. @media (max-width: ${p => p.theme.breakpoints.small}) {
  744. grid-row: 2/2;
  745. grid-column: ${p => (p.singleColumn ? '1/-1' : '2/2')};
  746. }
  747. `;
  748. const RemoveButton = styled(Button)`
  749. margin-left: ${space(1)};
  750. height: ${p => p.theme.form.md.height}px;
  751. `;
  752. const DragAndReorderButton = styled(Button)`
  753. height: ${p => p.theme.form.md.height}px;
  754. `;
  755. export default ColumnEditCollection;