widgetBuilder.tsx 41 KB

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