utils.tsx 22 KB

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