widgetBuilder.tsx 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210
  1. import {useEffect, useMemo, useState} from 'react';
  2. import {RouteComponentProps} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import cloneDeep from 'lodash/cloneDeep';
  5. import isEmpty from 'lodash/isEmpty';
  6. import omit from 'lodash/omit';
  7. import set from 'lodash/set';
  8. import {validateWidget} from 'sentry/actionCreators/dashboards';
  9. import {addErrorMessage, addSuccessMessage} from 'sentry/actionCreators/indicator';
  10. import {fetchOrgMembers} from 'sentry/actionCreators/members';
  11. import {loadOrganizationTags} from 'sentry/actionCreators/tags';
  12. import * as Layout from 'sentry/components/layouts/thirds';
  13. import List from 'sentry/components/list';
  14. import ListItem from 'sentry/components/list/listItem';
  15. import LoadingError from 'sentry/components/loadingError';
  16. import PageFiltersContainer from 'sentry/components/organizations/pageFilters/container';
  17. import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle';
  18. import {t} from 'sentry/locale';
  19. import {space} from 'sentry/styles/space';
  20. import {DateString, Organization, PageFilters, TagCollection} from 'sentry/types';
  21. import {defined, objectIsEmpty} from 'sentry/utils';
  22. import trackAdvancedAnalyticsEvent from 'sentry/utils/analytics/trackAdvancedAnalyticsEvent';
  23. import {CustomMeasurementsProvider} from 'sentry/utils/customMeasurements/customMeasurementsProvider';
  24. import EventView from 'sentry/utils/discover/eventView';
  25. import {
  26. explodeField,
  27. generateFieldAsString,
  28. getColumnsAndAggregates,
  29. getColumnsAndAggregatesAsStrings,
  30. QueryFieldValue,
  31. } from 'sentry/utils/discover/fields';
  32. import {MetricsCardinalityProvider} from 'sentry/utils/performance/contexts/metricsCardinality';
  33. import {MEPSettingProvider} from 'sentry/utils/performance/contexts/metricsEnhancedSetting';
  34. import useApi from 'sentry/utils/useApi';
  35. import {normalizeUrl} from 'sentry/utils/withDomainRequired';
  36. import withPageFilters from 'sentry/utils/withPageFilters';
  37. import withTags from 'sentry/utils/withTags';
  38. import {
  39. assignTempId,
  40. enforceWidgetHeightValues,
  41. generateWidgetsAfterCompaction,
  42. getDefaultWidgetHeight,
  43. } from 'sentry/views/dashboards/layoutUtils';
  44. import {
  45. DashboardDetails,
  46. DashboardWidgetSource,
  47. DisplayType,
  48. Widget,
  49. WidgetQuery,
  50. WidgetType,
  51. } from 'sentry/views/dashboards/types';
  52. import {MetricsDataSwitcher} from 'sentry/views/performance/landing/metricsDataSwitcher';
  53. import {DEFAULT_STATS_PERIOD} from '../data';
  54. import {getDatasetConfig} from '../datasetConfig/base';
  55. import {
  56. DashboardsMEPConsumer,
  57. DashboardsMEPProvider,
  58. } from '../widgetCard/dashboardsMEPContext';
  59. import {ColumnsStep} from './buildSteps/columnsStep';
  60. import {DataSetStep} from './buildSteps/dataSetStep';
  61. import {FilterResultsStep} from './buildSteps/filterResultsStep';
  62. import {GroupByStep} from './buildSteps/groupByStep';
  63. import {SortByStep} from './buildSteps/sortByStep';
  64. import {VisualizationStep} from './buildSteps/visualizationStep';
  65. import {YAxisStep} from './buildSteps/yAxisStep';
  66. import {Footer} from './footer';
  67. import {Header} from './header';
  68. import {
  69. DataSet,
  70. DEFAULT_RESULTS_LIMIT,
  71. generateOrderOptions,
  72. getIsTimeseriesChart,
  73. getParsedDefaultWidgetQuery,
  74. getResultsLimit,
  75. mapErrors,
  76. NEW_DASHBOARD_ID,
  77. normalizeQueries,
  78. } from './utils';
  79. import {WidgetLibrary} from './widgetLibrary';
  80. const WIDGET_TYPE_TO_DATA_SET = {
  81. [WidgetType.DISCOVER]: DataSet.EVENTS,
  82. [WidgetType.ISSUE]: DataSet.ISSUES,
  83. [WidgetType.RELEASE]: DataSet.RELEASES,
  84. };
  85. export const DATA_SET_TO_WIDGET_TYPE = {
  86. [DataSet.EVENTS]: WidgetType.DISCOVER,
  87. [DataSet.ISSUES]: WidgetType.ISSUE,
  88. [DataSet.RELEASES]: WidgetType.RELEASE,
  89. };
  90. interface RouteParams {
  91. dashboardId: string;
  92. orgId: string;
  93. widgetIndex?: string;
  94. }
  95. interface QueryData {
  96. queryConditions: string[];
  97. queryFields: string[];
  98. queryNames: string[];
  99. queryOrderby: string;
  100. }
  101. interface Props extends RouteComponentProps<RouteParams, {}> {
  102. dashboard: DashboardDetails;
  103. onSave: (widgets: Widget[]) => void;
  104. organization: Organization;
  105. selection: PageFilters;
  106. tags: TagCollection;
  107. displayType?: DisplayType;
  108. end?: DateString;
  109. start?: DateString;
  110. statsPeriod?: string | null;
  111. }
  112. interface State {
  113. dataSet: DataSet;
  114. displayType: Widget['displayType'];
  115. interval: Widget['interval'];
  116. limit: Widget['limit'];
  117. loading: boolean;
  118. prebuiltWidgetId: null | string;
  119. queries: Widget['queries'];
  120. queryConditionsValid: boolean;
  121. title: string;
  122. userHasModified: boolean;
  123. errors?: Record<string, any>;
  124. selectedDashboard?: DashboardDetails['id'];
  125. widgetToBeUpdated?: Widget;
  126. }
  127. function WidgetBuilder({
  128. dashboard,
  129. params,
  130. location,
  131. organization,
  132. selection,
  133. start,
  134. end,
  135. statsPeriod,
  136. onSave,
  137. route,
  138. router,
  139. tags,
  140. }: Props) {
  141. const {widgetIndex, orgId, dashboardId} = params;
  142. const {source, displayType, defaultTitle, limit} = location.query;
  143. const defaultWidgetQuery = getParsedDefaultWidgetQuery(
  144. location.query.defaultWidgetQuery
  145. );
  146. // defaultTableColumns can be a single string if location.query only contains
  147. // 1 value for this key. Ensure it is a string[]
  148. let {defaultTableColumns}: {defaultTableColumns: string[]} = location.query;
  149. if (typeof defaultTableColumns === 'string') {
  150. defaultTableColumns = [defaultTableColumns];
  151. }
  152. const hasReleaseHealthFeature = organization.features.includes('dashboards-rh-widget');
  153. const filteredDashboardWidgets = dashboard.widgets.filter(({widgetType}) => {
  154. if (widgetType === WidgetType.RELEASE) {
  155. return hasReleaseHealthFeature;
  156. }
  157. return true;
  158. });
  159. const isEditing = defined(widgetIndex);
  160. const widgetIndexNum = Number(widgetIndex);
  161. const isValidWidgetIndex =
  162. widgetIndexNum >= 0 &&
  163. widgetIndexNum < filteredDashboardWidgets.length &&
  164. Number.isInteger(widgetIndexNum);
  165. const orgSlug = organization.slug;
  166. // Construct PageFilters object using statsPeriod/start/end props so we can
  167. // render widget graph using saved timeframe from Saved/Prebuilt Query
  168. const pageFilters: PageFilters = statsPeriod
  169. ? {...selection, datetime: {start: null, end: null, period: statsPeriod, utc: null}}
  170. : start && end
  171. ? {...selection, datetime: {start, end, period: null, utc: null}}
  172. : selection;
  173. // when opening from discover or issues page, the user selects the dashboard in the widget UI
  174. const notDashboardsOrigin = [
  175. DashboardWidgetSource.DISCOVERV2,
  176. DashboardWidgetSource.ISSUE_DETAILS,
  177. ].includes(source);
  178. const api = useApi();
  179. const [isSubmitting, setIsSubmitting] = useState(false);
  180. const [datasetConfig, setDataSetConfig] = useState<ReturnType<typeof getDatasetConfig>>(
  181. getDatasetConfig(WidgetType.DISCOVER)
  182. );
  183. const [state, setState] = useState<State>(() => {
  184. const defaultState: State = {
  185. title: defaultTitle ?? t('Custom Widget'),
  186. displayType:
  187. (displayType === DisplayType.TOP_N ? DisplayType.AREA : displayType) ??
  188. DisplayType.TABLE,
  189. interval: '5m',
  190. queries: [],
  191. limit: limit ? Number(limit) : undefined,
  192. errors: undefined,
  193. loading: !!notDashboardsOrigin,
  194. userHasModified: false,
  195. prebuiltWidgetId: null,
  196. dataSet: DataSet.EVENTS,
  197. queryConditionsValid: true,
  198. selectedDashboard: dashboard.id || NEW_DASHBOARD_ID,
  199. };
  200. if (defaultWidgetQuery) {
  201. defaultState.queries = [
  202. {
  203. ...defaultWidgetQuery,
  204. orderby:
  205. defaultWidgetQuery.orderby ||
  206. (datasetConfig.getTableSortOptions
  207. ? datasetConfig.getTableSortOptions(organization, defaultWidgetQuery)[0]
  208. .value
  209. : ''),
  210. },
  211. ];
  212. if (
  213. ![DisplayType.TABLE, DisplayType.TOP_N].includes(defaultState.displayType) &&
  214. !(
  215. getIsTimeseriesChart(defaultState.displayType) &&
  216. defaultState.queries[0].columns.length
  217. )
  218. ) {
  219. defaultState.queries[0].orderby = '';
  220. }
  221. } else {
  222. defaultState.queries = [{...datasetConfig.defaultWidgetQuery}];
  223. }
  224. return defaultState;
  225. });
  226. const [widgetToBeUpdated, setWidgetToBeUpdated] = useState<Widget | null>(null);
  227. // For analytics around widget library selection
  228. const [latestLibrarySelectionTitle, setLatestLibrarySelectionTitle] = useState<
  229. string | null
  230. >(null);
  231. useEffect(() => {
  232. trackAdvancedAnalyticsEvent('dashboards_views.widget_builder.opened', {
  233. organization,
  234. new_widget: !isEditing,
  235. });
  236. if (objectIsEmpty(tags)) {
  237. loadOrganizationTags(api, organization.slug, {
  238. ...selection,
  239. // Pin the request to 14d to avoid timeouts, see DD-967 for
  240. // more information
  241. datetime: {period: '14d', start: null, end: null, utc: null},
  242. });
  243. }
  244. if (isEditing && isValidWidgetIndex) {
  245. const widgetFromDashboard = filteredDashboardWidgets[widgetIndexNum];
  246. let queries;
  247. let newDisplayType = widgetFromDashboard.displayType;
  248. let newLimit = widgetFromDashboard.limit;
  249. if (widgetFromDashboard.displayType === DisplayType.TOP_N) {
  250. newLimit = DEFAULT_RESULTS_LIMIT;
  251. newDisplayType = DisplayType.AREA;
  252. queries = normalizeQueries({
  253. displayType: newDisplayType,
  254. queries: widgetFromDashboard.queries,
  255. widgetType: widgetFromDashboard.widgetType ?? WidgetType.DISCOVER,
  256. }).map(query => ({
  257. ...query,
  258. // Use the last aggregate because that's where the y-axis is stored
  259. aggregates: query.aggregates.length
  260. ? [query.aggregates[query.aggregates.length - 1]]
  261. : [],
  262. }));
  263. } else {
  264. queries = normalizeQueries({
  265. displayType: newDisplayType,
  266. queries: widgetFromDashboard.queries,
  267. widgetType: widgetFromDashboard.widgetType ?? WidgetType.DISCOVER,
  268. });
  269. }
  270. setState({
  271. title: widgetFromDashboard.title,
  272. displayType: newDisplayType,
  273. interval: widgetFromDashboard.interval,
  274. queries,
  275. errors: undefined,
  276. loading: false,
  277. userHasModified: false,
  278. dataSet: widgetFromDashboard.widgetType
  279. ? WIDGET_TYPE_TO_DATA_SET[widgetFromDashboard.widgetType]
  280. : DataSet.EVENTS,
  281. limit: newLimit,
  282. prebuiltWidgetId: null,
  283. queryConditionsValid: true,
  284. });
  285. setDataSetConfig(getDatasetConfig(widgetFromDashboard.widgetType));
  286. setWidgetToBeUpdated(widgetFromDashboard);
  287. }
  288. // This should only run once on mount
  289. // eslint-disable-next-line react-hooks/exhaustive-deps
  290. }, []);
  291. useEffect(() => {
  292. fetchOrgMembers(api, organization.slug, selection.projects?.map(String));
  293. }, [selection.projects, api, organization.slug]);
  294. useEffect(() => {
  295. const onUnload = () => {
  296. if (!isSubmitting && state.userHasModified) {
  297. return t('You have unsaved changes, are you sure you want to leave?');
  298. }
  299. return undefined;
  300. };
  301. router.setRouteLeaveHook(route, onUnload);
  302. }, [isSubmitting, state.userHasModified, route, router]);
  303. const widgetType =
  304. state.dataSet === DataSet.EVENTS
  305. ? WidgetType.DISCOVER
  306. : state.dataSet === DataSet.ISSUES
  307. ? WidgetType.ISSUE
  308. : WidgetType.RELEASE;
  309. const currentWidget = {
  310. title: state.title,
  311. displayType: state.displayType,
  312. interval: state.interval,
  313. queries: state.queries,
  314. limit: state.limit,
  315. widgetType,
  316. };
  317. const currentDashboardId = state.selectedDashboard ?? dashboardId;
  318. const queryParamsWithoutSource = omit(location.query, 'source');
  319. const previousLocation = {
  320. pathname:
  321. defined(currentDashboardId) && currentDashboardId !== NEW_DASHBOARD_ID
  322. ? `/organizations/${orgId}/dashboard/${currentDashboardId}/`
  323. : `/organizations/${orgId}/dashboards/${NEW_DASHBOARD_ID}/`,
  324. query: isEmpty(queryParamsWithoutSource) ? undefined : queryParamsWithoutSource,
  325. };
  326. const isTimeseriesChart = getIsTimeseriesChart(state.displayType);
  327. const isTabularChart = [DisplayType.TABLE, DisplayType.TOP_N].includes(
  328. state.displayType
  329. );
  330. function updateFieldsAccordingToDisplayType(newDisplayType: DisplayType) {
  331. setState(prevState => {
  332. const newState = cloneDeep(prevState);
  333. if (!datasetConfig.supportedDisplayTypes.includes(newDisplayType)) {
  334. // Set to Events dataset if Display Type is not supported by
  335. // current dataset
  336. set(
  337. newState,
  338. 'queries',
  339. normalizeQueries({
  340. displayType: newDisplayType,
  341. queries: [{...getDatasetConfig(WidgetType.DISCOVER).defaultWidgetQuery}],
  342. widgetType: WidgetType.DISCOVER,
  343. })
  344. );
  345. set(newState, 'dataSet', DataSet.EVENTS);
  346. setDataSetConfig(getDatasetConfig(WidgetType.DISCOVER));
  347. return {...newState, errors: undefined};
  348. }
  349. const normalized = normalizeQueries({
  350. displayType: newDisplayType,
  351. queries: prevState.queries,
  352. widgetType: DATA_SET_TO_WIDGET_TYPE[prevState.dataSet],
  353. });
  354. if (newDisplayType === DisplayType.TOP_N) {
  355. // TOP N display should only allow a single query
  356. normalized.splice(1);
  357. }
  358. if (!prevState.userHasModified) {
  359. // Default widget provided by Add to Dashboard from Discover
  360. if (defaultWidgetQuery && defaultTableColumns) {
  361. // If switching to Table visualization, use saved query fields for Y-Axis if user has not made query changes
  362. // This is so the widget can reflect the same columns as the table in Discover without requiring additional user input
  363. if (newDisplayType === DisplayType.TABLE) {
  364. normalized.forEach(query => {
  365. const tableQuery = getColumnsAndAggregates(defaultTableColumns);
  366. query.columns = [...tableQuery.columns];
  367. query.aggregates = [...tableQuery.aggregates];
  368. query.fields = [...defaultTableColumns];
  369. query.orderby =
  370. defaultWidgetQuery.orderby ??
  371. (query.fields.length ? `${query.fields[0]}` : '-');
  372. });
  373. } else if (newDisplayType === displayType) {
  374. // When switching back to original display type, default fields back to the fields provided from the discover query
  375. normalized.forEach(query => {
  376. query.fields = [
  377. ...defaultWidgetQuery.columns,
  378. ...defaultWidgetQuery.aggregates,
  379. ];
  380. query.aggregates = [...defaultWidgetQuery.aggregates];
  381. query.columns = [...defaultWidgetQuery.columns];
  382. if (
  383. !!defaultWidgetQuery.orderby &&
  384. (displayType === DisplayType.TOP_N || defaultWidgetQuery.columns.length)
  385. ) {
  386. query.orderby = defaultWidgetQuery.orderby;
  387. }
  388. });
  389. }
  390. }
  391. }
  392. set(newState, 'queries', normalized);
  393. if (
  394. getIsTimeseriesChart(newDisplayType) &&
  395. normalized[0].columns.filter(column => !!column).length
  396. ) {
  397. // If a limit already exists (i.e. going between timeseries) then keep it,
  398. // otherwise calculate a limit
  399. newState.limit =
  400. prevState.limit ??
  401. Math.min(
  402. getResultsLimit(normalized.length, normalized[0].columns.length),
  403. DEFAULT_RESULTS_LIMIT
  404. );
  405. } else {
  406. newState.limit = undefined;
  407. }
  408. set(newState, 'userHasModified', true);
  409. return {...newState, errors: undefined};
  410. });
  411. }
  412. function getUpdateWidgetIndex() {
  413. if (!widgetToBeUpdated) {
  414. return -1;
  415. }
  416. return dashboard.widgets.findIndex(widget => {
  417. if (defined(widget.id)) {
  418. return widget.id === widgetToBeUpdated.id;
  419. }
  420. if (defined(widget.tempId)) {
  421. return widget.tempId === widgetToBeUpdated.tempId;
  422. }
  423. return false;
  424. });
  425. }
  426. function handleDisplayTypeOrTitleChange<
  427. F extends keyof Pick<State, 'displayType' | 'title'>
  428. >(field: F, value: State[F]) {
  429. trackAdvancedAnalyticsEvent('dashboards_views.widget_builder.change', {
  430. from: source,
  431. field,
  432. value,
  433. widget_type: widgetType,
  434. organization,
  435. new_widget: !isEditing,
  436. });
  437. setState(prevState => {
  438. const newState = cloneDeep(prevState);
  439. set(newState, field, value);
  440. if (field === 'title') {
  441. set(newState, 'userHasModified', true);
  442. }
  443. return {...newState, errors: undefined};
  444. });
  445. if (field === 'displayType' && value !== state.displayType) {
  446. updateFieldsAccordingToDisplayType(value as DisplayType);
  447. }
  448. }
  449. function handleDataSetChange(newDataSet: string) {
  450. trackAdvancedAnalyticsEvent('dashboards_views.widget_builder.change', {
  451. from: source,
  452. field: 'dataSet',
  453. value: newDataSet,
  454. widget_type: widgetType,
  455. organization,
  456. new_widget: !isEditing,
  457. });
  458. setState(prevState => {
  459. const newState = cloneDeep(prevState);
  460. newState.queries.splice(0, newState.queries.length);
  461. set(newState, 'dataSet', newDataSet);
  462. if (newDataSet === DataSet.ISSUES) {
  463. set(newState, 'displayType', DisplayType.TABLE);
  464. }
  465. const config = getDatasetConfig(DATA_SET_TO_WIDGET_TYPE[newDataSet]);
  466. setDataSetConfig(config);
  467. newState.queries.push(
  468. ...(widgetToBeUpdated?.widgetType &&
  469. WIDGET_TYPE_TO_DATA_SET[widgetToBeUpdated.widgetType] === newDataSet
  470. ? widgetToBeUpdated.queries
  471. : [{...config.defaultWidgetQuery}])
  472. );
  473. set(newState, 'userHasModified', true);
  474. return {...newState, errors: undefined};
  475. });
  476. }
  477. function handleAddSearchConditions() {
  478. setState(prevState => {
  479. const newState = cloneDeep(prevState);
  480. const config = getDatasetConfig(DATA_SET_TO_WIDGET_TYPE[prevState.dataSet]);
  481. const query = cloneDeep(config.defaultWidgetQuery);
  482. query.fields = prevState.queries[0].fields;
  483. query.aggregates = prevState.queries[0].aggregates;
  484. query.columns = prevState.queries[0].columns;
  485. query.orderby = prevState.queries[0].orderby;
  486. newState.queries.push(query);
  487. return newState;
  488. });
  489. }
  490. function handleQueryRemove(index: number) {
  491. setState(prevState => {
  492. const newState = cloneDeep(prevState);
  493. newState.queries.splice(index, 1);
  494. return {...newState, errors: undefined};
  495. });
  496. }
  497. function handleQueryChange(queryIndex: number, newQuery: WidgetQuery) {
  498. setState(prevState => {
  499. const newState = cloneDeep(prevState);
  500. set(newState, `queries.${queryIndex}`, newQuery);
  501. set(newState, 'userHasModified', true);
  502. return {...newState, errors: undefined};
  503. });
  504. }
  505. function getHandleColumnFieldChange(isMetricsData?: boolean) {
  506. function handleColumnFieldChange(newFields: QueryFieldValue[]) {
  507. const fieldStrings = newFields.map(generateFieldAsString);
  508. const splitFields = getColumnsAndAggregatesAsStrings(newFields);
  509. const newState = cloneDeep(state);
  510. let newQuery = cloneDeep(newState.queries[0]);
  511. newQuery.fields = fieldStrings;
  512. newQuery.aggregates = splitFields.aggregates;
  513. newQuery.columns = splitFields.columns;
  514. newQuery.fieldAliases = splitFields.fieldAliases;
  515. if (datasetConfig.handleColumnFieldChangeOverride) {
  516. newQuery = datasetConfig.handleColumnFieldChangeOverride(newQuery);
  517. }
  518. if (datasetConfig.handleOrderByReset) {
  519. // If widget is metric backed, don't default to sorting by transaction unless its the only column
  520. // Sorting by transaction is not supported in metrics
  521. if (
  522. isMetricsData &&
  523. fieldStrings.some(
  524. fieldString => !['transaction', 'title'].includes(fieldString)
  525. )
  526. ) {
  527. newQuery = datasetConfig.handleOrderByReset(
  528. newQuery,
  529. fieldStrings.filter(
  530. fieldString => !['transaction', 'title'].includes(fieldString)
  531. )
  532. );
  533. } else {
  534. newQuery = datasetConfig.handleOrderByReset(newQuery, fieldStrings);
  535. }
  536. }
  537. set(newState, 'queries', [newQuery]);
  538. set(newState, 'userHasModified', true);
  539. setState(newState);
  540. }
  541. return handleColumnFieldChange;
  542. }
  543. function handleYAxisChange(newFields: QueryFieldValue[]) {
  544. const fieldStrings = newFields.map(generateFieldAsString);
  545. const newState = cloneDeep(state);
  546. const newQueries = state.queries.map(query => {
  547. let newQuery = cloneDeep(query);
  548. if (state.displayType === DisplayType.TOP_N) {
  549. // Top N queries use n-1 fields for columns and the nth field for y-axis
  550. newQuery.fields = [
  551. ...(newQuery.fields?.slice(0, newQuery.fields.length - 1) ?? []),
  552. ...fieldStrings,
  553. ];
  554. newQuery.aggregates = [
  555. ...newQuery.aggregates.slice(0, newQuery.aggregates.length - 1),
  556. ...fieldStrings,
  557. ];
  558. } else {
  559. newQuery.fields = [...newQuery.columns, ...fieldStrings];
  560. newQuery.aggregates = fieldStrings;
  561. }
  562. if (datasetConfig.handleOrderByReset) {
  563. newQuery = datasetConfig.handleOrderByReset(newQuery, fieldStrings);
  564. }
  565. return newQuery;
  566. });
  567. set(newState, 'queries', newQueries);
  568. set(newState, 'userHasModified', true);
  569. const groupByFields = newState.queries[0].columns.filter(
  570. field => !(field === 'equation|')
  571. );
  572. if (groupByFields.length === 0) {
  573. set(newState, 'limit', undefined);
  574. } else {
  575. set(
  576. newState,
  577. 'limit',
  578. Math.min(
  579. newState.limit ?? DEFAULT_RESULTS_LIMIT,
  580. getResultsLimit(newQueries.length, newQueries[0].aggregates.length)
  581. )
  582. );
  583. }
  584. setState(newState);
  585. }
  586. function handleGroupByChange(newFields: QueryFieldValue[]) {
  587. const fieldStrings = newFields.map(generateFieldAsString);
  588. const newState = cloneDeep(state);
  589. const newQueries = state.queries.map(query => {
  590. const newQuery = cloneDeep(query);
  591. newQuery.columns = fieldStrings;
  592. if (!fieldStrings.length) {
  593. // The grouping was cleared, so clear the orderby
  594. newQuery.orderby = '';
  595. } else if (!newQuery.orderby) {
  596. const orderOptions = generateOrderOptions({
  597. widgetType: widgetType ?? WidgetType.DISCOVER,
  598. columns: query.columns,
  599. aggregates: query.aggregates,
  600. });
  601. let orderOption: string;
  602. // If no orderby options are available because of DISABLED_SORTS
  603. if (!orderOptions.length) {
  604. newQuery.orderby = '';
  605. } else {
  606. orderOption = orderOptions[0].value;
  607. newQuery.orderby = `-${orderOption}`;
  608. }
  609. }
  610. return newQuery;
  611. });
  612. set(newState, 'userHasModified', true);
  613. set(newState, 'queries', newQueries);
  614. const groupByFields = newState.queries[0].columns.filter(
  615. field => !(field === 'equation|')
  616. );
  617. if (groupByFields.length === 0) {
  618. set(newState, 'limit', undefined);
  619. } else {
  620. set(
  621. newState,
  622. 'limit',
  623. Math.min(
  624. newState.limit ?? DEFAULT_RESULTS_LIMIT,
  625. getResultsLimit(newQueries.length, newQueries[0].aggregates.length)
  626. )
  627. );
  628. }
  629. setState(newState);
  630. }
  631. function handleLimitChange(newLimit: number) {
  632. setState(prevState => ({...prevState, limit: newLimit}));
  633. }
  634. function handleSortByChange(newSortBy: string) {
  635. const newState = cloneDeep(state);
  636. state.queries.forEach((query, index) => {
  637. const newQuery = cloneDeep(query);
  638. newQuery.orderby = newSortBy;
  639. set(newState, `queries.${index}`, newQuery);
  640. });
  641. set(newState, 'userHasModified', true);
  642. setState(newState);
  643. }
  644. function handleDelete() {
  645. if (!isEditing) {
  646. return;
  647. }
  648. setIsSubmitting(true);
  649. let nextWidgetList = [...dashboard.widgets];
  650. const updateWidgetIndex = getUpdateWidgetIndex();
  651. nextWidgetList.splice(updateWidgetIndex, 1);
  652. nextWidgetList = generateWidgetsAfterCompaction(nextWidgetList);
  653. onSave(nextWidgetList);
  654. router.push(normalizeUrl(previousLocation));
  655. }
  656. async function handleSave() {
  657. const widgetData: Widget = assignTempId(currentWidget);
  658. if (widgetToBeUpdated) {
  659. widgetData.layout = widgetToBeUpdated?.layout;
  660. }
  661. // Only Time Series charts shall have a limit
  662. if (!isTimeseriesChart) {
  663. widgetData.limit = undefined;
  664. }
  665. if (!(await dataIsValid(widgetData))) {
  666. return;
  667. }
  668. if (latestLibrarySelectionTitle) {
  669. // User has selected a widget library in this session
  670. trackAdvancedAnalyticsEvent('dashboards_views.widget_library.add_widget', {
  671. organization,
  672. title: latestLibrarySelectionTitle,
  673. });
  674. }
  675. setIsSubmitting(true);
  676. if (notDashboardsOrigin) {
  677. submitFromSelectedDashboard(widgetData);
  678. return;
  679. }
  680. if (widgetToBeUpdated) {
  681. let nextWidgetList = [...dashboard.widgets];
  682. const updateWidgetIndex = getUpdateWidgetIndex();
  683. const nextWidgetData = {...widgetData, id: widgetToBeUpdated.id};
  684. // Only modify and re-compact if the default height has changed
  685. if (
  686. getDefaultWidgetHeight(widgetToBeUpdated.displayType) !==
  687. getDefaultWidgetHeight(widgetData.displayType)
  688. ) {
  689. nextWidgetList[updateWidgetIndex] = enforceWidgetHeightValues(nextWidgetData);
  690. nextWidgetList = generateWidgetsAfterCompaction(nextWidgetList);
  691. } else {
  692. nextWidgetList[updateWidgetIndex] = nextWidgetData;
  693. }
  694. onSave(nextWidgetList);
  695. addSuccessMessage(t('Updated widget.'));
  696. goToDashboards(dashboardId ?? NEW_DASHBOARD_ID);
  697. trackAdvancedAnalyticsEvent('dashboards_views.widget_builder.save', {
  698. organization,
  699. data_set: widgetData.widgetType ?? WidgetType.DISCOVER,
  700. new_widget: false,
  701. });
  702. return;
  703. }
  704. onSave([...dashboard.widgets, widgetData]);
  705. addSuccessMessage(t('Added widget.'));
  706. goToDashboards(dashboardId ?? NEW_DASHBOARD_ID);
  707. trackAdvancedAnalyticsEvent('dashboards_views.widget_builder.save', {
  708. organization,
  709. data_set: widgetData.widgetType ?? WidgetType.DISCOVER,
  710. new_widget: true,
  711. });
  712. }
  713. async function dataIsValid(widgetData: Widget): Promise<boolean> {
  714. setState({...state, loading: true});
  715. try {
  716. await validateWidget(api, organization.slug, widgetData);
  717. return true;
  718. } catch (error) {
  719. setState({
  720. ...state,
  721. loading: false,
  722. errors: {...state.errors, ...mapErrors(error?.responseJSON ?? {}, {})},
  723. });
  724. addErrorMessage(t('Unable to save widget'));
  725. return false;
  726. }
  727. }
  728. function submitFromSelectedDashboard(widgetData: Widget) {
  729. if (!state.selectedDashboard) {
  730. return;
  731. }
  732. const queryData: QueryData = {
  733. queryNames: [],
  734. queryConditions: [],
  735. queryFields: [
  736. ...widgetData.queries[0].columns,
  737. ...widgetData.queries[0].aggregates,
  738. ],
  739. queryOrderby: widgetData.queries[0].orderby,
  740. };
  741. widgetData.queries.forEach(query => {
  742. queryData.queryNames.push(query.name);
  743. queryData.queryConditions.push(query.conditions);
  744. });
  745. const pathQuery = {
  746. displayType: widgetData.displayType,
  747. interval: widgetData.interval,
  748. title: widgetData.title,
  749. ...queryData,
  750. // Propagate page filters
  751. project: pageFilters.projects,
  752. environment: pageFilters.environments,
  753. ...omit(pageFilters.datetime, 'period'),
  754. statsPeriod: pageFilters.datetime?.period,
  755. };
  756. addSuccessMessage(t('Added widget.'));
  757. goToDashboards(state.selectedDashboard, pathQuery);
  758. }
  759. function goToDashboards(id: string, query?: Record<string, any>) {
  760. const pathQuery =
  761. !isEmpty(queryParamsWithoutSource) || query
  762. ? {
  763. ...queryParamsWithoutSource,
  764. ...query,
  765. }
  766. : undefined;
  767. if (id === NEW_DASHBOARD_ID) {
  768. router.push(
  769. normalizeUrl({
  770. pathname: `/organizations/${organization.slug}/dashboards/new/`,
  771. query: pathQuery,
  772. })
  773. );
  774. return;
  775. }
  776. router.push(
  777. normalizeUrl({
  778. pathname: `/organizations/${organization.slug}/dashboard/${id}/`,
  779. query: pathQuery,
  780. })
  781. );
  782. }
  783. function isFormInvalid() {
  784. if (
  785. (notDashboardsOrigin && !state.selectedDashboard) ||
  786. !state.queryConditionsValid
  787. ) {
  788. return true;
  789. }
  790. return false;
  791. }
  792. function setQueryConditionsValid(validSearch: boolean) {
  793. setState({...state, queryConditionsValid: validSearch});
  794. }
  795. const canAddSearchConditions =
  796. [DisplayType.LINE, DisplayType.AREA, DisplayType.BAR].includes(state.displayType) &&
  797. state.queries.length < 3;
  798. const hideLegendAlias = [
  799. DisplayType.TABLE,
  800. DisplayType.WORLD_MAP,
  801. DisplayType.BIG_NUMBER,
  802. ].includes(state.displayType);
  803. // Tabular visualizations will always have only one query and that query cannot be deleted,
  804. // so we will always have the first query available to get data from.
  805. const {columns, aggregates, fields, fieldAliases = []} = state.queries[0];
  806. const explodedColumns = useMemo(() => {
  807. return columns.map((field, index) =>
  808. explodeField({field, alias: fieldAliases[index]})
  809. );
  810. }, [columns, fieldAliases]);
  811. const explodedAggregates = useMemo(() => {
  812. return aggregates.map((field, index) =>
  813. explodeField({field, alias: fieldAliases[index]})
  814. );
  815. }, [aggregates, fieldAliases]);
  816. const explodedFields = defined(fields)
  817. ? fields.map((field, index) => explodeField({field, alias: fieldAliases[index]}))
  818. : [...explodedColumns, ...explodedAggregates];
  819. const groupByValueSelected = currentWidget.queries.some(query => {
  820. const noEmptyColumns = query.columns.filter(column => !!column);
  821. return noEmptyColumns.length > 0;
  822. });
  823. // The SortBy field shall only be displayed in tabular visualizations or
  824. // on time-series visualizations when at least one groupBy value is selected
  825. const displaySortByStep = (isTimeseriesChart && groupByValueSelected) || isTabularChart;
  826. if (isEditing && !isValidWidgetIndex) {
  827. return (
  828. <SentryDocumentTitle title={dashboard.title} orgSlug={orgSlug}>
  829. <Layout.Page withPadding>
  830. <LoadingError message={t('The widget you want to edit was not found.')} />
  831. </Layout.Page>
  832. </SentryDocumentTitle>
  833. );
  834. }
  835. return (
  836. <SentryDocumentTitle title={dashboard.title} orgSlug={orgSlug}>
  837. <PageFiltersContainer
  838. defaultSelection={{
  839. datetime: {start: null, end: null, utc: null, period: DEFAULT_STATS_PERIOD},
  840. }}
  841. >
  842. <CustomMeasurementsProvider organization={organization} selection={selection}>
  843. <DashboardsMEPProvider>
  844. <MetricsCardinalityProvider organization={organization} location={location}>
  845. <MetricsDataSwitcher
  846. organization={organization}
  847. eventView={EventView.fromLocation(location)}
  848. location={location}
  849. hideLoadingIndicator
  850. >
  851. {metricsDataSide => (
  852. <MEPSettingProvider
  853. location={location}
  854. forceTransactions={metricsDataSide.forceTransactionsOnly}
  855. >
  856. <Layout.Page>
  857. <Header
  858. orgSlug={orgSlug}
  859. title={state.title}
  860. dashboardTitle={dashboard.title}
  861. goBackLocation={previousLocation}
  862. onChangeTitle={newTitle => {
  863. handleDisplayTypeOrTitleChange('title', newTitle);
  864. }}
  865. />
  866. <Body>
  867. <MainWrapper>
  868. <Main>
  869. <BuildSteps symbol="colored-numeric">
  870. <VisualizationStep
  871. location={location}
  872. widget={currentWidget}
  873. dashboardFilters={dashboard.filters}
  874. organization={organization}
  875. pageFilters={pageFilters}
  876. displayType={state.displayType}
  877. error={state.errors?.displayType}
  878. onChange={newDisplayType => {
  879. handleDisplayTypeOrTitleChange(
  880. 'displayType',
  881. newDisplayType
  882. );
  883. }}
  884. noDashboardsMEPProvider
  885. isWidgetInvalid={!state.queryConditionsValid}
  886. />
  887. <DataSetStep
  888. dataSet={state.dataSet}
  889. displayType={state.displayType}
  890. onChange={handleDataSetChange}
  891. hasReleaseHealthFeature={hasReleaseHealthFeature}
  892. />
  893. {isTabularChart && (
  894. <DashboardsMEPConsumer>
  895. {({isMetricsData}) => (
  896. <ColumnsStep
  897. dataSet={state.dataSet}
  898. queries={state.queries}
  899. displayType={state.displayType}
  900. widgetType={widgetType}
  901. queryErrors={state.errors?.queries}
  902. onQueryChange={handleQueryChange}
  903. handleColumnFieldChange={getHandleColumnFieldChange(
  904. isMetricsData
  905. )}
  906. explodedFields={explodedFields}
  907. tags={tags}
  908. organization={organization}
  909. />
  910. )}
  911. </DashboardsMEPConsumer>
  912. )}
  913. {![DisplayType.TABLE].includes(state.displayType) && (
  914. <YAxisStep
  915. dataSet={state.dataSet}
  916. displayType={state.displayType}
  917. widgetType={widgetType}
  918. queryErrors={state.errors?.queries}
  919. onYAxisChange={newFields => {
  920. handleYAxisChange(newFields);
  921. }}
  922. aggregates={explodedAggregates}
  923. tags={tags}
  924. organization={organization}
  925. />
  926. )}
  927. <FilterResultsStep
  928. queries={state.queries}
  929. hideLegendAlias={hideLegendAlias}
  930. canAddSearchConditions={canAddSearchConditions}
  931. organization={organization}
  932. queryErrors={state.errors?.queries}
  933. onAddSearchConditions={handleAddSearchConditions}
  934. onQueryChange={handleQueryChange}
  935. onQueryRemove={handleQueryRemove}
  936. selection={pageFilters}
  937. widgetType={widgetType}
  938. dashboardFilters={dashboard.filters}
  939. location={location}
  940. onQueryConditionChange={setQueryConditionsValid}
  941. />
  942. {isTimeseriesChart && (
  943. <GroupByStep
  944. columns={columns
  945. .filter(field => !(field === 'equation|'))
  946. .map((field, index) =>
  947. explodeField({field, alias: fieldAliases[index]})
  948. )}
  949. onGroupByChange={handleGroupByChange}
  950. organization={organization}
  951. tags={tags}
  952. dataSet={state.dataSet}
  953. />
  954. )}
  955. {displaySortByStep && (
  956. <SortByStep
  957. limit={state.limit}
  958. displayType={state.displayType}
  959. queries={state.queries}
  960. dataSet={state.dataSet}
  961. error={state.errors?.orderby}
  962. onSortByChange={handleSortByChange}
  963. onLimitChange={handleLimitChange}
  964. organization={organization}
  965. widgetType={widgetType}
  966. tags={tags}
  967. />
  968. )}
  969. </BuildSteps>
  970. </Main>
  971. <Footer
  972. goBackLocation={previousLocation}
  973. isEditing={isEditing}
  974. onSave={handleSave}
  975. onDelete={handleDelete}
  976. invalidForm={isFormInvalid()}
  977. />
  978. </MainWrapper>
  979. <Side>
  980. <WidgetLibrary
  981. organization={organization}
  982. selectedWidgetId={
  983. state.userHasModified ? null : state.prebuiltWidgetId
  984. }
  985. onWidgetSelect={prebuiltWidget => {
  986. setLatestLibrarySelectionTitle(prebuiltWidget.title);
  987. setDataSetConfig(
  988. getDatasetConfig(
  989. prebuiltWidget.widgetType || WidgetType.DISCOVER
  990. )
  991. );
  992. const {id, ...prebuiltWidgetProps} = prebuiltWidget;
  993. setState({
  994. ...state,
  995. ...prebuiltWidgetProps,
  996. dataSet: prebuiltWidget.widgetType
  997. ? WIDGET_TYPE_TO_DATA_SET[prebuiltWidget.widgetType]
  998. : DataSet.EVENTS,
  999. userHasModified: false,
  1000. prebuiltWidgetId: id || null,
  1001. });
  1002. }}
  1003. bypassOverwriteModal={!state.userHasModified}
  1004. />
  1005. </Side>
  1006. </Body>
  1007. </Layout.Page>
  1008. </MEPSettingProvider>
  1009. )}
  1010. </MetricsDataSwitcher>
  1011. </MetricsCardinalityProvider>
  1012. </DashboardsMEPProvider>
  1013. </CustomMeasurementsProvider>
  1014. </PageFiltersContainer>
  1015. </SentryDocumentTitle>
  1016. );
  1017. }
  1018. export default withPageFilters(withTags(WidgetBuilder));
  1019. const BuildSteps = styled(List)`
  1020. gap: ${space(4)};
  1021. max-width: 100%;
  1022. `;
  1023. const Body = styled(Layout.Body)`
  1024. && {
  1025. gap: 0;
  1026. padding: 0;
  1027. }
  1028. grid-template-rows: 1fr;
  1029. @media (min-width: ${p => p.theme.breakpoints.large}) {
  1030. grid-template-columns: minmax(100px, auto) 400px;
  1031. }
  1032. @media (min-width: ${p => p.theme.breakpoints.xlarge}) {
  1033. grid-template-columns: 1fr;
  1034. }
  1035. `;
  1036. // HACK: Since we add 30px of padding to the ListItems
  1037. // there is 30px of overlap when the screen is just above 1200px.
  1038. // When we're up to 1230px (1200 + 30 to account for the padding)
  1039. // we decrease the width of ListItems by 30px
  1040. const Main = styled(Layout.Main)`
  1041. max-width: 1000px;
  1042. flex: 1;
  1043. padding: ${space(4)} ${space(2)};
  1044. @media (min-width: ${p => p.theme.breakpoints.medium}) {
  1045. padding: ${space(4)};
  1046. }
  1047. @media (max-width: calc(${p => p.theme.breakpoints.large} + ${space(4)})) {
  1048. ${ListItem} {
  1049. width: calc(100% - ${space(4)});
  1050. }
  1051. }
  1052. `;
  1053. const Side = styled(Layout.Side)`
  1054. padding: ${space(4)} ${space(2)};
  1055. @media (max-width: ${p => p.theme.breakpoints.large}) {
  1056. border-top: 1px solid ${p => p.theme.gray200};
  1057. grid-row: 2/2;
  1058. grid-column: 1/-1;
  1059. max-width: 100%;
  1060. }
  1061. @media (min-width: ${p => p.theme.breakpoints.large}) {
  1062. border-left: 1px solid ${p => p.theme.gray200};
  1063. /* to be consistent with Layout.Body in other verticals */
  1064. padding-right: ${space(4)};
  1065. max-width: 400px;
  1066. }
  1067. `;
  1068. const MainWrapper = styled('div')`
  1069. display: flex;
  1070. flex-direction: column;
  1071. @media (max-width: ${p => p.theme.breakpoints.large}) {
  1072. grid-column: 1/-1;
  1073. }
  1074. `;