widgetBuilder.tsx 52 KB

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