utils.tsx 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781
  1. import {browserHistory, InjectedRouter} from 'react-router';
  2. import {urlEncode} from '@sentry/utils';
  3. import {Location, Query} from 'history';
  4. import * as Papa from 'papaparse';
  5. import {
  6. openAddDashboardWidgetModal,
  7. openAddToDashboardModal,
  8. } from 'sentry/actionCreators/modal';
  9. import {COL_WIDTH_UNDEFINED} from 'sentry/components/gridEditable';
  10. import {URL_PARAM} from 'sentry/constants/pageFilters';
  11. import {t} from 'sentry/locale';
  12. import {NewQuery, Organization, OrganizationSummary, SelectValue} from 'sentry/types';
  13. import {Event} from 'sentry/types/event';
  14. import trackAdvancedAnalyticsEvent from 'sentry/utils/analytics/trackAdvancedAnalyticsEvent';
  15. import {getUtcDateString} from 'sentry/utils/dates';
  16. import {TableDataRow} from 'sentry/utils/discover/discoverQuery';
  17. import EventView from 'sentry/utils/discover/eventView';
  18. import {
  19. aggregateFunctionOutputType,
  20. Aggregation,
  21. AGGREGATIONS,
  22. Column,
  23. ColumnType,
  24. ColumnValueType,
  25. explodeFieldString,
  26. Field,
  27. getAggregateAlias,
  28. getColumnsAndAggregates,
  29. getEquation,
  30. isAggregateEquation,
  31. isEquation,
  32. isMeasurement,
  33. isSpanOperationBreakdownField,
  34. measurementType,
  35. TRACING_FIELDS,
  36. } from 'sentry/utils/discover/fields';
  37. import {DisplayModes, TOP_N} from 'sentry/utils/discover/types';
  38. import {getTitle} from 'sentry/utils/events';
  39. import {DISCOVER_FIELDS, FieldValueType, getFieldDefinition} from 'sentry/utils/fields';
  40. import localStorage from 'sentry/utils/localStorage';
  41. import {MutableSearch} from 'sentry/utils/tokenizeSearch';
  42. import {DashboardWidgetSource, DisplayType, WidgetQuery} from '../dashboardsV2/types';
  43. import {displayModeToDisplayType} from './savedQuery/utils';
  44. import {FieldValue, FieldValueKind, TableColumn} from './table/types';
  45. import {ALL_VIEWS, TRANSACTION_VIEWS, WEB_VITALS_VIEWS} from './data';
  46. export type QueryWithColumnState =
  47. | Query
  48. | {
  49. field: string | string[] | null | undefined;
  50. sort: string | string[] | null | undefined;
  51. };
  52. const TEMPLATE_TABLE_COLUMN: TableColumn<string> = {
  53. key: '',
  54. name: '',
  55. type: 'never',
  56. isSortable: false,
  57. column: Object.freeze({kind: 'field', field: ''}),
  58. width: COL_WIDTH_UNDEFINED,
  59. };
  60. // TODO(mark) these types are coupled to the gridEditable component types and
  61. // I'd prefer the types to be more general purpose but that will require a second pass.
  62. export function decodeColumnOrder(
  63. fields: Readonly<Field[]>,
  64. useFullEquationAsKey?: boolean
  65. ): TableColumn<string>[] {
  66. let equations = 0;
  67. return fields.map((f: Field) => {
  68. const column: TableColumn<string> = {...TEMPLATE_TABLE_COLUMN};
  69. const col = explodeFieldString(f.field, f.alias);
  70. const columnName = f.field;
  71. if (isEquation(f.field)) {
  72. column.key = useFullEquationAsKey ? f.field : `equation[${equations}]`;
  73. column.name = getEquation(columnName);
  74. equations += 1;
  75. } else {
  76. column.key = columnName;
  77. column.name = columnName;
  78. }
  79. column.width = f.width || COL_WIDTH_UNDEFINED;
  80. if (col.kind === 'function') {
  81. // Aggregations can have a strict outputType or they can inherit from their field.
  82. // Otherwise use the FIELDS data to infer types.
  83. const outputType = aggregateFunctionOutputType(col.function[0], col.function[1]);
  84. if (outputType !== null) {
  85. column.type = outputType;
  86. }
  87. const aggregate = AGGREGATIONS[col.function[0]];
  88. column.isSortable = aggregate && aggregate.isSortable;
  89. } else if (col.kind === 'field') {
  90. if (getFieldDefinition(col.field) !== null) {
  91. column.type = getFieldDefinition(col.field)?.valueType as ColumnValueType;
  92. } else if (isMeasurement(col.field)) {
  93. column.type = measurementType(col.field);
  94. } else if (isSpanOperationBreakdownField(col.field)) {
  95. column.type = 'duration';
  96. }
  97. }
  98. column.column = col;
  99. return column;
  100. });
  101. }
  102. export function pushEventViewToLocation(props: {
  103. location: Location;
  104. nextEventView: EventView;
  105. extraQuery?: Query;
  106. }) {
  107. const {location, nextEventView} = props;
  108. const extraQuery = props.extraQuery || {};
  109. const queryStringObject = nextEventView.generateQueryStringObject();
  110. browserHistory.push({
  111. ...location,
  112. query: {
  113. ...extraQuery,
  114. ...queryStringObject,
  115. },
  116. });
  117. }
  118. export function generateTitle({
  119. eventView,
  120. event,
  121. organization,
  122. }: {
  123. eventView: EventView;
  124. event?: Event;
  125. organization?: Organization;
  126. }) {
  127. const titles = [t('Discover')];
  128. const eventViewName = eventView.name;
  129. if (typeof eventViewName === 'string' && String(eventViewName).trim().length > 0) {
  130. titles.push(String(eventViewName).trim());
  131. }
  132. const eventTitle = event ? getTitle(event, organization?.features).title : undefined;
  133. if (eventTitle) {
  134. titles.push(eventTitle);
  135. }
  136. titles.reverse();
  137. return titles.join(' - ');
  138. }
  139. export function getPrebuiltQueries(organization: Organization) {
  140. const views = [...ALL_VIEWS];
  141. if (organization.features.includes('performance-view')) {
  142. // insert transactions queries at index 2
  143. views.splice(2, 0, ...TRANSACTION_VIEWS);
  144. views.push(...WEB_VITALS_VIEWS);
  145. }
  146. return views;
  147. }
  148. function disableMacros(value: string | null | boolean | number) {
  149. const unsafeCharacterRegex = /^[\=\+\-\@]/;
  150. if (typeof value === 'string' && `${value}`.match(unsafeCharacterRegex)) {
  151. return `'${value}`;
  152. }
  153. return value;
  154. }
  155. export function downloadAsCsv(tableData, columnOrder, filename) {
  156. const {data} = tableData;
  157. const headings = columnOrder.map(column => column.name);
  158. const keys = columnOrder.map(column => column.key);
  159. const csvContent = Papa.unparse({
  160. fields: headings,
  161. data: data.map(row =>
  162. keys.map(key => {
  163. return disableMacros(row[key]);
  164. })
  165. ),
  166. });
  167. // Need to also manually replace # since encodeURI skips them
  168. const encodedDataUrl = `data:text/csv;charset=utf8,${encodeURIComponent(csvContent)}`;
  169. // Create a download link then click it, this is so we can get a filename
  170. const link = document.createElement('a');
  171. const now = new Date();
  172. link.setAttribute('href', encodedDataUrl);
  173. link.setAttribute('download', `${filename} ${getUtcDateString(now)}.csv`);
  174. link.click();
  175. link.remove();
  176. // Make testing easier
  177. return encodedDataUrl;
  178. }
  179. const ALIASED_AGGREGATES_COLUMN = {
  180. last_seen: 'timestamp',
  181. failure_count: 'transaction.status',
  182. };
  183. /**
  184. * Convert an aggregate into the resulting column from a drilldown action.
  185. * The result is null if the drilldown results in the aggregate being removed.
  186. */
  187. function drilldownAggregate(
  188. func: Extract<Column, {kind: 'function'}>
  189. ): Extract<Column, {kind: 'field'}> | null {
  190. const key = func.function[0];
  191. const aggregation = AGGREGATIONS[key];
  192. let column = func.function[1];
  193. if (ALIASED_AGGREGATES_COLUMN.hasOwnProperty(key)) {
  194. // Some aggregates are just shortcuts to other aggregates with
  195. // predefined arguments so we can directly map them to the result.
  196. column = ALIASED_AGGREGATES_COLUMN[key];
  197. } else if (aggregation?.parameters?.[0]) {
  198. const parameter = aggregation.parameters[0];
  199. if (parameter.kind !== 'column') {
  200. // The aggregation does not accept a column as a parameter,
  201. // so we clear the column.
  202. column = '';
  203. } else if (!column && parameter.required === false) {
  204. // The parameter was not given for a non-required parameter,
  205. // so we fall back to the default.
  206. column = parameter.defaultValue;
  207. }
  208. } else {
  209. // The aggregation does not exist or does not have any parameters,
  210. // so we clear the column.
  211. column = '';
  212. }
  213. return column ? {kind: 'field', field: column} : null;
  214. }
  215. /**
  216. * Convert an aggregated query into one that does not have aggregates.
  217. * Will also apply additions conditions defined in `additionalConditions`
  218. * and generate conditions based on the `dataRow` parameter and the current fields
  219. * in the `eventView`.
  220. */
  221. export function getExpandedResults(
  222. eventView: EventView,
  223. additionalConditions: Record<string, string>,
  224. dataRow?: TableDataRow | Event
  225. ): EventView {
  226. const fieldSet = new Set();
  227. // Expand any functions in the resulting column, and dedupe the result.
  228. // Mark any column as null to remove it.
  229. const expandedColumns: (Column | null)[] = eventView.fields.map((field: Field) => {
  230. const exploded = explodeFieldString(field.field, field.alias);
  231. const column = exploded.kind === 'function' ? drilldownAggregate(exploded) : exploded;
  232. if (
  233. // if expanding the function failed
  234. column === null ||
  235. // the new column is already present
  236. fieldSet.has(column.field) ||
  237. // Skip aggregate equations, their functions will already be added so we just want to remove it
  238. isAggregateEquation(field.field)
  239. ) {
  240. return null;
  241. }
  242. fieldSet.add(column.field);
  243. return column;
  244. });
  245. // id should be default column when expanded results in no columns; but only if
  246. // the Discover query's columns is non-empty.
  247. // This typically occurs in Discover drilldowns.
  248. if (fieldSet.size === 0 && expandedColumns.length) {
  249. expandedColumns[0] = {kind: 'field', field: 'id'};
  250. }
  251. // update the columns according the the expansion above
  252. const nextView = expandedColumns.reduceRight(
  253. (newView, column, index) =>
  254. column === null
  255. ? newView.withDeletedColumn(index, undefined)
  256. : newView.withUpdatedColumn(index, column, undefined),
  257. eventView.clone()
  258. );
  259. nextView.query = generateExpandedConditions(nextView, additionalConditions, dataRow);
  260. return nextView;
  261. }
  262. /**
  263. * Create additional conditions based on the fields in an EventView
  264. * and a datarow/event
  265. */
  266. function generateAdditionalConditions(
  267. eventView: EventView,
  268. dataRow?: TableDataRow | Event
  269. ): Record<string, string | string[]> {
  270. const specialKeys = Object.values(URL_PARAM);
  271. const conditions: Record<string, string | string[]> = {};
  272. if (!dataRow) {
  273. return conditions;
  274. }
  275. eventView.fields.forEach((field: Field) => {
  276. const column = explodeFieldString(field.field, field.alias);
  277. // Skip aggregate fields
  278. if (column.kind === 'function') {
  279. return;
  280. }
  281. const dataKey = getAggregateAlias(field.field);
  282. // Append the current field as a condition if it exists in the dataRow
  283. // Or is a simple key in the event. More complex deeply nested fields are
  284. // more challenging to get at as their location in the structure does not
  285. // match their name.
  286. if (dataRow.hasOwnProperty(dataKey)) {
  287. let value = dataRow[dataKey];
  288. if (Array.isArray(value)) {
  289. if (value.length > 1) {
  290. conditions[column.field] = value;
  291. return;
  292. }
  293. // An array with only one value is equivalent to the value itself.
  294. value = value[0];
  295. }
  296. // if the value will be quoted, then do not trim it as the whitespaces
  297. // may be important to the query and should not be trimmed
  298. const shouldQuote =
  299. value === null || value === undefined
  300. ? false
  301. : /[\s\(\)\\"]/g.test(String(value).trim());
  302. const nextValue =
  303. value === null || value === undefined
  304. ? ''
  305. : shouldQuote
  306. ? String(value)
  307. : String(value).trim();
  308. if (isMeasurement(column.field) && !nextValue) {
  309. // Do not add measurement conditions if nextValue is falsey.
  310. // It's expected that nextValue is a numeric value.
  311. return;
  312. }
  313. switch (column.field) {
  314. case 'timestamp':
  315. // normalize the "timestamp" field to ensure the payload works
  316. conditions[column.field] = getUtcDateString(nextValue);
  317. break;
  318. default:
  319. conditions[column.field] = nextValue;
  320. }
  321. }
  322. // If we have an event, check tags as well.
  323. if (dataRow.tags && Array.isArray(dataRow.tags)) {
  324. const tagIndex = dataRow.tags.findIndex(item => item.key === dataKey);
  325. if (tagIndex > -1) {
  326. const key = specialKeys.includes(column.field)
  327. ? `tags[${column.field}]`
  328. : column.field;
  329. const tagValue = dataRow.tags[tagIndex].value;
  330. conditions[key] = tagValue;
  331. }
  332. }
  333. });
  334. return conditions;
  335. }
  336. function generateExpandedConditions(
  337. eventView: EventView,
  338. additionalConditions: Record<string, string>,
  339. dataRow?: TableDataRow | Event
  340. ): string {
  341. const parsedQuery = new MutableSearch(eventView.query);
  342. // Remove any aggregates from the search conditions.
  343. // otherwise, it'll lead to an invalid query result.
  344. for (const key in parsedQuery.filters) {
  345. const column = explodeFieldString(key);
  346. if (column.kind === 'function') {
  347. parsedQuery.removeFilter(key);
  348. }
  349. }
  350. const conditions: Record<string, string | string[]> = Object.assign(
  351. {},
  352. additionalConditions,
  353. generateAdditionalConditions(eventView, dataRow)
  354. );
  355. // Add additional conditions provided and generated.
  356. for (const key in conditions) {
  357. const value = conditions[key];
  358. if (Array.isArray(value)) {
  359. parsedQuery.setFilterValues(key, value);
  360. continue;
  361. }
  362. if (key === 'project.id') {
  363. eventView.project = [...eventView.project, parseInt(value, 10)];
  364. continue;
  365. }
  366. if (key === 'environment') {
  367. if (!eventView.environment.includes(value)) {
  368. eventView.environment = [...eventView.environment, value];
  369. }
  370. continue;
  371. }
  372. const column = explodeFieldString(key);
  373. // Skip aggregates as they will be invalid.
  374. if (column.kind === 'function') {
  375. continue;
  376. }
  377. parsedQuery.setFilterValues(key, [value]);
  378. }
  379. return parsedQuery.formatString();
  380. }
  381. type FieldGeneratorOpts = {
  382. organization: OrganizationSummary;
  383. aggregations?: Record<string, Aggregation>;
  384. customMeasurements?: {functions: string[]; key: string}[] | null;
  385. fieldKeys?: string[];
  386. measurementKeys?: string[] | null;
  387. spanOperationBreakdownKeys?: string[];
  388. tagKeys?: string[] | null;
  389. };
  390. export function generateFieldOptions({
  391. organization,
  392. tagKeys,
  393. measurementKeys,
  394. spanOperationBreakdownKeys,
  395. customMeasurements,
  396. aggregations = AGGREGATIONS,
  397. fieldKeys = DISCOVER_FIELDS,
  398. }: FieldGeneratorOpts) {
  399. let functions = Object.keys(aggregations);
  400. // Strip tracing features if the org doesn't have access.
  401. if (!organization.features.includes('performance-view')) {
  402. fieldKeys = fieldKeys.filter(item => !TRACING_FIELDS.includes(item));
  403. functions = functions.filter(item => !TRACING_FIELDS.includes(item));
  404. }
  405. const fieldOptions: Record<string, SelectValue<FieldValue>> = {};
  406. // Index items by prefixed keys as custom tags can overlap both fields and
  407. // function names. Having a mapping makes finding the value objects easier
  408. // later as well.
  409. functions.forEach(func => {
  410. const ellipsis = aggregations[func].parameters.length ? '\u2026' : '';
  411. const parameters = aggregations[func].parameters.map(param => {
  412. const overrides = AGGREGATIONS[func].getFieldOverrides;
  413. if (typeof overrides === 'undefined') {
  414. return param;
  415. }
  416. return {
  417. ...param,
  418. ...overrides({parameter: param}),
  419. };
  420. });
  421. fieldOptions[`function:${func}`] = {
  422. label: `${func}(${ellipsis})`,
  423. value: {
  424. kind: FieldValueKind.FUNCTION,
  425. meta: {
  426. name: func,
  427. parameters,
  428. },
  429. },
  430. };
  431. });
  432. fieldKeys.forEach(field => {
  433. fieldOptions[`field:${field}`] = {
  434. label: field,
  435. value: {
  436. kind: FieldValueKind.FIELD,
  437. meta: {
  438. name: field,
  439. dataType: (getFieldDefinition(field)?.valueType ??
  440. FieldValueType.STRING) as ColumnType,
  441. },
  442. },
  443. };
  444. });
  445. if (measurementKeys !== undefined && measurementKeys !== null) {
  446. measurementKeys.sort();
  447. measurementKeys.forEach(measurement => {
  448. fieldOptions[`measurement:${measurement}`] = {
  449. label: measurement,
  450. value: {
  451. kind: FieldValueKind.MEASUREMENT,
  452. meta: {name: measurement, dataType: measurementType(measurement)},
  453. },
  454. };
  455. });
  456. }
  457. if (customMeasurements !== undefined && customMeasurements !== null) {
  458. customMeasurements.sort(({key: currentKey}, {key: nextKey}) =>
  459. currentKey > nextKey ? 1 : currentKey === nextKey ? 0 : -1
  460. );
  461. customMeasurements.forEach(({key, functions: supportedFunctions}) => {
  462. fieldOptions[`measurement:${key}`] = {
  463. label: key,
  464. value: {
  465. kind: FieldValueKind.CUSTOM_MEASUREMENT,
  466. meta: {
  467. name: key,
  468. dataType: measurementType(key),
  469. functions: supportedFunctions,
  470. },
  471. },
  472. };
  473. });
  474. }
  475. if (Array.isArray(spanOperationBreakdownKeys)) {
  476. spanOperationBreakdownKeys.sort();
  477. spanOperationBreakdownKeys.forEach(breakdownField => {
  478. fieldOptions[`span_op_breakdown:${breakdownField}`] = {
  479. label: breakdownField,
  480. value: {
  481. kind: FieldValueKind.BREAKDOWN,
  482. meta: {name: breakdownField, dataType: 'duration'},
  483. },
  484. };
  485. });
  486. }
  487. if (tagKeys !== undefined && tagKeys !== null) {
  488. tagKeys.sort();
  489. tagKeys.forEach(tag => {
  490. const tagValue =
  491. fieldKeys.includes(tag) || AGGREGATIONS.hasOwnProperty(tag)
  492. ? `tags[${tag}]`
  493. : tag;
  494. fieldOptions[`tag:${tag}`] = {
  495. label: tag,
  496. value: {
  497. kind: FieldValueKind.TAG,
  498. meta: {name: tagValue, dataType: 'string'},
  499. },
  500. };
  501. });
  502. }
  503. return fieldOptions;
  504. }
  505. const RENDER_PREBUILT_KEY = 'discover-render-prebuilt';
  506. export function shouldRenderPrebuilt(): boolean {
  507. const shouldRender = localStorage.getItem(RENDER_PREBUILT_KEY);
  508. return shouldRender === 'true' || shouldRender === null;
  509. }
  510. export function setRenderPrebuilt(value: boolean) {
  511. localStorage.setItem(RENDER_PREBUILT_KEY, value ? 'true' : 'false');
  512. }
  513. export function eventViewToWidgetQuery({
  514. eventView,
  515. yAxis,
  516. displayType,
  517. widgetBuilderNewDesign,
  518. }: {
  519. displayType: DisplayType;
  520. eventView: EventView;
  521. widgetBuilderNewDesign?: boolean;
  522. yAxis?: string | string[];
  523. }) {
  524. const fields = eventView.fields.map(({field}) => field);
  525. const {columns, aggregates} = getColumnsAndAggregates(fields);
  526. const sort = eventView.sorts[0];
  527. const queryYAxis = typeof yAxis === 'string' ? [yAxis] : yAxis ?? ['count()'];
  528. let orderby = '';
  529. // The orderby should only be set to sort.field if it is a Top N query
  530. // since the query uses all of the fields, or if the ordering is used in the y-axis
  531. if (sort && displayType !== DisplayType.WORLD_MAP) {
  532. let orderbyFunction = '';
  533. const aggregateFields = [...queryYAxis, ...aggregates];
  534. for (let i = 0; i < aggregateFields.length; i++) {
  535. if (sort.field === getAggregateAlias(aggregateFields[i])) {
  536. orderbyFunction = aggregateFields[i];
  537. break;
  538. }
  539. }
  540. const bareOrderby = orderbyFunction === '' ? sort.field : orderbyFunction;
  541. if (displayType === DisplayType.TOP_N || bareOrderby) {
  542. orderby = `${sort.kind === 'desc' ? '-' : ''}${bareOrderby}`;
  543. }
  544. }
  545. let newAggregates = aggregates;
  546. if (widgetBuilderNewDesign && displayType !== DisplayType.TABLE) {
  547. newAggregates = queryYAxis;
  548. } else if (!widgetBuilderNewDesign) {
  549. newAggregates = [
  550. ...(displayType === DisplayType.TOP_N ? aggregates : []),
  551. ...queryYAxis,
  552. ];
  553. }
  554. const widgetQuery: WidgetQuery = {
  555. name: '',
  556. aggregates: newAggregates,
  557. columns: [...(displayType === DisplayType.TOP_N ? columns : [])],
  558. fields: [...(displayType === DisplayType.TOP_N ? fields : []), ...queryYAxis],
  559. conditions: eventView.query,
  560. orderby,
  561. };
  562. return widgetQuery;
  563. }
  564. export function handleAddQueryToDashboard({
  565. eventView,
  566. location,
  567. query,
  568. organization,
  569. router,
  570. yAxis,
  571. }: {
  572. eventView: EventView;
  573. location: Location;
  574. organization: Organization;
  575. router: InjectedRouter;
  576. query?: NewQuery;
  577. yAxis?: string | string[];
  578. }) {
  579. const displayType = displayModeToDisplayType(eventView.display as DisplayModes);
  580. const defaultTableFields = eventView.fields.map(({field}) => field);
  581. const defaultWidgetQuery = eventViewToWidgetQuery({
  582. eventView,
  583. displayType,
  584. yAxis,
  585. widgetBuilderNewDesign: organization.features.includes(
  586. 'new-widget-builder-experience-design'
  587. ),
  588. });
  589. if (organization.features.includes('new-widget-builder-experience-design')) {
  590. const {query: widgetAsQueryParams} = constructAddQueryToDashboardLink({
  591. eventView,
  592. query,
  593. organization,
  594. yAxis,
  595. location,
  596. });
  597. openAddToDashboardModal({
  598. organization,
  599. selection: {
  600. projects: eventView.project,
  601. environments: eventView.environment,
  602. datetime: {
  603. start: eventView.start,
  604. end: eventView.end,
  605. period: eventView.statsPeriod,
  606. utc: eventView.utc,
  607. },
  608. },
  609. widget: {
  610. title: query?.name ?? eventView.name,
  611. displayType:
  612. organization.features.includes('new-widget-builder-experience-design') &&
  613. displayType === DisplayType.TOP_N
  614. ? DisplayType.AREA
  615. : displayType,
  616. queries: [
  617. {
  618. ...defaultWidgetQuery,
  619. aggregates: [...(typeof yAxis === 'string' ? [yAxis] : yAxis ?? ['count()'])],
  620. },
  621. ],
  622. interval: eventView.interval,
  623. limit:
  624. organization.features.includes('new-widget-builder-experience-design') &&
  625. displayType === DisplayType.TOP_N
  626. ? Number(eventView.topEvents) || TOP_N
  627. : undefined,
  628. },
  629. router,
  630. widgetAsQueryParams,
  631. location,
  632. });
  633. return;
  634. }
  635. openAddDashboardWidgetModal({
  636. organization,
  637. start: eventView.start,
  638. end: eventView.end,
  639. statsPeriod: eventView.statsPeriod,
  640. source: DashboardWidgetSource.DISCOVERV2,
  641. defaultWidgetQuery,
  642. defaultTableColumns: defaultTableFields,
  643. defaultTitle:
  644. query?.name ?? (eventView.name !== 'All Events' ? eventView.name : undefined),
  645. displayType,
  646. });
  647. trackAdvancedAnalyticsEvent('discover_views.add_to_dashboard.modal_open', {
  648. organization,
  649. saved_query: !!query,
  650. });
  651. }
  652. export function constructAddQueryToDashboardLink({
  653. eventView,
  654. query,
  655. organization,
  656. yAxis,
  657. location,
  658. }: {
  659. eventView: EventView;
  660. organization: Organization;
  661. location?: Location;
  662. query?: NewQuery;
  663. yAxis?: string | string[];
  664. }) {
  665. const displayType = displayModeToDisplayType(eventView.display as DisplayModes);
  666. const defaultTableFields = eventView.fields.map(({field}) => field);
  667. const defaultWidgetQuery = eventViewToWidgetQuery({
  668. eventView,
  669. displayType,
  670. yAxis,
  671. widgetBuilderNewDesign: organization.features.includes(
  672. 'new-widget-builder-experience-design'
  673. ),
  674. });
  675. const defaultTitle =
  676. query?.name ?? (eventView.name !== 'All Events' ? eventView.name : undefined);
  677. return {
  678. pathname: `/organizations/${organization.slug}/dashboards/new/widget/new/`,
  679. query: {
  680. ...location?.query,
  681. source: DashboardWidgetSource.DISCOVERV2,
  682. start: eventView.start,
  683. end: eventView.end,
  684. statsPeriod: eventView.statsPeriod,
  685. defaultWidgetQuery: urlEncode(defaultWidgetQuery),
  686. defaultTableColumns: defaultTableFields,
  687. defaultTitle,
  688. displayType:
  689. organization.features.includes('new-widget-builder-experience-design') &&
  690. displayType === DisplayType.TOP_N
  691. ? DisplayType.AREA
  692. : displayType,
  693. limit:
  694. organization.features.includes('new-widget-builder-experience-design') &&
  695. displayType === DisplayType.TOP_N
  696. ? Number(eventView.topEvents) || TOP_N
  697. : undefined,
  698. },
  699. };
  700. }