widgetBuilder.tsx 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484
  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.dataSet !== DataSet.SPANS &&
  960. state.queries.length < 3;
  961. const hideLegendAlias = [DisplayType.TABLE, DisplayType.BIG_NUMBER].includes(
  962. state.displayType
  963. );
  964. // Tabular visualizations will always have only one query and that query cannot be deleted,
  965. // so we will always have the first query available to get data from.
  966. const {columns, aggregates, fields, fieldAliases = []} = state.queries[0];
  967. const explodedColumns = useMemo(() => {
  968. return columns.map((field, index) =>
  969. explodeField({field, alias: fieldAliases[index]})
  970. );
  971. }, [columns, fieldAliases]);
  972. const explodedAggregates = useMemo(() => {
  973. return aggregates.map((field, index) =>
  974. explodeField({field, alias: fieldAliases[index]})
  975. );
  976. }, [aggregates, fieldAliases]);
  977. const explodedFields = defined(fields)
  978. ? fields.map((field, index) => explodeField({field, alias: fieldAliases[index]}))
  979. : [...explodedColumns, ...explodedAggregates];
  980. const groupByValueSelected = currentWidget.queries.some(query => {
  981. const noEmptyColumns = query.columns.filter(column => !!column);
  982. return noEmptyColumns.length > 0;
  983. });
  984. // The SortBy field shall only be displayed in tabular visualizations or
  985. // on time-series visualizations when at least one groupBy value is selected
  986. const displaySortByStep = (isTimeseriesChart && groupByValueSelected) || isTabularChart;
  987. if (isEditing && !isValidWidgetIndex) {
  988. return (
  989. <SentryDocumentTitle title={dashboard.title} orgSlug={orgSlug}>
  990. <Layout.Page withPadding>
  991. <LoadingError message={t('The widget you want to edit was not found.')} />
  992. </Layout.Page>
  993. </SentryDocumentTitle>
  994. );
  995. }
  996. const widgetDiscoverSplitSource = isValidWidgetIndex
  997. ? dashboard.widgets[widgetIndexNum].datasetSource
  998. : undefined;
  999. const originalWidgetType = isValidWidgetIndex
  1000. ? dashboard.widgets[widgetIndexNum].widgetType
  1001. : undefined;
  1002. return (
  1003. <SentryDocumentTitle title={dashboard.title} orgSlug={orgSlug}>
  1004. <PageFiltersContainer
  1005. defaultSelection={{
  1006. datetime: {start: null, end: null, utc: null, period: DEFAULT_STATS_PERIOD},
  1007. }}
  1008. >
  1009. <OnRouteLeave message={UNSAVED_CHANGES_MESSAGE} when={onRouteLeave} />
  1010. <CustomMeasurementsProvider organization={organization} selection={selection}>
  1011. <OnDemandControlProvider location={location}>
  1012. <MetricsResultsMetaProvider>
  1013. <DashboardsMEPProvider>
  1014. <MetricsCardinalityProvider
  1015. organization={organization}
  1016. location={location}
  1017. >
  1018. <MetricsDataSwitcher
  1019. organization={organization}
  1020. eventView={EventView.fromLocation(location)}
  1021. location={location}
  1022. hideLoadingIndicator
  1023. >
  1024. {metricsDataSide => (
  1025. <MEPSettingProvider
  1026. location={location}
  1027. forceTransactions={metricsDataSide.forceTransactionsOnly}
  1028. >
  1029. <Layout.Page>
  1030. <Header
  1031. orgSlug={orgSlug}
  1032. dashboardTitle={dashboard.title}
  1033. goBackLocation={previousLocation}
  1034. />
  1035. <Body>
  1036. <MainWrapper>
  1037. <Main>
  1038. <BuildSteps symbol="colored-numeric">
  1039. <NameWidgetStep title={t('Name your widget')}>
  1040. <TitleInput
  1041. name="title"
  1042. inline={false}
  1043. aria-label={t('Widget title')}
  1044. placeholder={t('Enter title')}
  1045. error={state.errors?.title}
  1046. data-test-id="widget-builder-title-input"
  1047. onChange={newTitle => {
  1048. handleDisplayTypeOrAnnotationChange(
  1049. 'title',
  1050. newTitle
  1051. );
  1052. }}
  1053. value={state.title}
  1054. />
  1055. <StyledTextAreaField
  1056. name="description"
  1057. rows={4}
  1058. autosize
  1059. inline={false}
  1060. aria-label={t('Widget Description')}
  1061. placeholder={t('Enter description (Optional)')}
  1062. error={state.errors?.description}
  1063. onChange={newDescription => {
  1064. handleDisplayTypeOrAnnotationChange(
  1065. 'description',
  1066. newDescription
  1067. );
  1068. }}
  1069. value={state.description}
  1070. />
  1071. </NameWidgetStep>
  1072. <VisualizationStep
  1073. location={location}
  1074. onDataFetched={handleWidgetDataFetched}
  1075. widget={currentWidget}
  1076. dashboardFilters={dashboard.filters}
  1077. organization={organization}
  1078. pageFilters={pageFilters}
  1079. displayType={state.displayType}
  1080. error={state.errors?.displayType}
  1081. onChange={newDisplayType => {
  1082. handleDisplayTypeOrAnnotationChange(
  1083. 'displayType',
  1084. newDisplayType
  1085. );
  1086. }}
  1087. isWidgetInvalid={!state.queryConditionsValid}
  1088. onWidgetSplitDecision={
  1089. handleUpdateWidgetSplitDecision
  1090. }
  1091. widgetLegendState={widgetLegendState}
  1092. />
  1093. <DataSetStep
  1094. dataSet={state.dataSet}
  1095. displayType={state.displayType}
  1096. onChange={handleDataSetChange}
  1097. splitDecision={
  1098. splitDecision ??
  1099. // The original widget type is used for a forced split decision
  1100. (widgetDiscoverSplitSource === DatasetSource.FORCED
  1101. ? originalWidgetType
  1102. : undefined)
  1103. }
  1104. source={widgetDiscoverSplitSource}
  1105. />
  1106. {isTabularChart && (
  1107. <DashboardsMEPConsumer>
  1108. {({isMetricsData}) => (
  1109. <ColumnsStep
  1110. dataSet={state.dataSet}
  1111. displayType={state.displayType}
  1112. widgetType={widgetType}
  1113. queryErrors={state.errors?.queries}
  1114. onQueryChange={handleQueryChange}
  1115. handleColumnFieldChange={getHandleColumnFieldChange(
  1116. isMetricsData
  1117. )}
  1118. explodedFields={explodedFields}
  1119. tags={tags}
  1120. organization={organization}
  1121. isOnDemandWidget={isOnDemandWidget}
  1122. />
  1123. )}
  1124. </DashboardsMEPConsumer>
  1125. )}
  1126. {![DisplayType.TABLE].includes(state.displayType) && (
  1127. <YAxisStep
  1128. dataSet={state.dataSet}
  1129. displayType={state.displayType}
  1130. widgetType={widgetType}
  1131. queryErrors={state.errors?.queries}
  1132. onYAxisChange={(newFields, newSelectedField) => {
  1133. handleYAxisChange(newFields, newSelectedField);
  1134. }}
  1135. aggregates={explodedAggregates}
  1136. selectedAggregate={
  1137. state.queries[0].selectedAggregate
  1138. }
  1139. tags={tags}
  1140. organization={organization}
  1141. />
  1142. )}
  1143. <FilterResultsStep
  1144. queries={state.queries}
  1145. hideLegendAlias={hideLegendAlias}
  1146. canAddSearchConditions={canAddSearchConditions}
  1147. organization={organization}
  1148. queryErrors={state.errors?.queries}
  1149. onAddSearchConditions={handleAddSearchConditions}
  1150. onQueryChange={handleQueryChange}
  1151. onQueryRemove={handleQueryRemove}
  1152. selection={pageFilters}
  1153. widgetType={widgetType}
  1154. dashboardFilters={dashboard.filters}
  1155. location={location}
  1156. onQueryConditionChange={setQueryConditionsValid}
  1157. validatedWidgetResponse={validatedWidgetResponse}
  1158. />
  1159. {isTimeseriesChart && (
  1160. <GroupByStep
  1161. columns={columns
  1162. .filter(field => !(field === 'equation|'))
  1163. .map((field, index) =>
  1164. explodeField({
  1165. field,
  1166. alias: fieldAliases[index],
  1167. })
  1168. )}
  1169. onGroupByChange={handleGroupByChange}
  1170. organization={organization}
  1171. validatedWidgetResponse={validatedWidgetResponse}
  1172. tags={tags}
  1173. dataSet={state.dataSet}
  1174. />
  1175. )}
  1176. {displaySortByStep && (
  1177. <SortByStep
  1178. limit={state.limit}
  1179. displayType={state.displayType}
  1180. queries={state.queries}
  1181. dataSet={state.dataSet}
  1182. error={state.errors?.orderby}
  1183. onSortByChange={handleSortByChange}
  1184. onLimitChange={handleLimitChange}
  1185. organization={organization}
  1186. widgetType={widgetType}
  1187. tags={tags}
  1188. />
  1189. )}
  1190. {state.displayType === 'big_number' &&
  1191. state.dataType !== 'date' && (
  1192. <ThresholdsStep
  1193. onThresholdChange={handleThresholdChange}
  1194. onUnitChange={handleThresholdUnitChange}
  1195. thresholdsConfig={state.thresholds ?? null}
  1196. dataType={state.dataType}
  1197. dataUnit={state.dataUnit}
  1198. errors={state.errors?.thresholds}
  1199. />
  1200. )}
  1201. </BuildSteps>
  1202. </Main>
  1203. <Footer
  1204. goBackLocation={previousLocation}
  1205. isEditing={isEditing}
  1206. onSave={handleSave}
  1207. onDelete={handleDelete}
  1208. invalidForm={isFormInvalid()}
  1209. />
  1210. </MainWrapper>
  1211. <Side>
  1212. <WidgetLibrary
  1213. organization={organization}
  1214. selectedWidgetId={
  1215. state.userHasModified ? null : state.prebuiltWidgetId
  1216. }
  1217. onWidgetSelect={prebuiltWidget => {
  1218. setLatestLibrarySelectionTitle(prebuiltWidget.title);
  1219. setDataSetConfig(
  1220. getDatasetConfig(
  1221. prebuiltWidget.widgetType || defaultWidgetType
  1222. )
  1223. );
  1224. const {id, ...prebuiltWidgetProps} = prebuiltWidget;
  1225. setState({
  1226. ...state,
  1227. ...prebuiltWidgetProps,
  1228. dataSet: prebuiltWidget.widgetType
  1229. ? WIDGET_TYPE_TO_DATA_SET[prebuiltWidget.widgetType]
  1230. : defaultDataset,
  1231. userHasModified: false,
  1232. prebuiltWidgetId: id || null,
  1233. });
  1234. }}
  1235. bypassOverwriteModal={!state.userHasModified}
  1236. />
  1237. </Side>
  1238. </Body>
  1239. </Layout.Page>
  1240. </MEPSettingProvider>
  1241. )}
  1242. </MetricsDataSwitcher>
  1243. </MetricsCardinalityProvider>
  1244. </DashboardsMEPProvider>
  1245. </MetricsResultsMetaProvider>
  1246. </OnDemandControlProvider>
  1247. </CustomMeasurementsProvider>
  1248. </PageFiltersContainer>
  1249. </SentryDocumentTitle>
  1250. );
  1251. }
  1252. export default withPageFilters(WidgetBuilder);
  1253. const TitleInput = styled(TextField)`
  1254. padding: 0 ${space(2)} 0 0;
  1255. `;
  1256. const BuildSteps = styled(List)`
  1257. gap: ${space(4)};
  1258. max-width: 100%;
  1259. `;
  1260. const Body = styled(Layout.Body)`
  1261. && {
  1262. gap: 0;
  1263. padding: 0;
  1264. }
  1265. grid-template-rows: 1fr;
  1266. @media (min-width: ${p => p.theme.breakpoints.large}) {
  1267. grid-template-columns: minmax(100px, auto) 400px;
  1268. }
  1269. @media (min-width: ${p => p.theme.breakpoints.xlarge}) {
  1270. grid-template-columns: 1fr;
  1271. }
  1272. `;
  1273. // HACK: Since we add 30px of padding to the ListItems
  1274. // there is 30px of overlap when the screen is just above 1200px.
  1275. // When we're up to 1230px (1200 + 30 to account for the padding)
  1276. // we decrease the width of ListItems by 30px
  1277. const Main = styled(Layout.Main)`
  1278. max-width: 1000px;
  1279. flex: 1;
  1280. padding: ${space(4)} ${space(2)};
  1281. @media (min-width: ${p => p.theme.breakpoints.medium}) {
  1282. padding: ${space(4)};
  1283. }
  1284. @media (max-width: calc(${p => p.theme.breakpoints.large} + ${space(4)})) {
  1285. ${ListItem} {
  1286. width: calc(100% - ${space(4)});
  1287. }
  1288. }
  1289. `;
  1290. const Side = styled(Layout.Side)`
  1291. padding: ${space(4)} ${space(2)};
  1292. @media (max-width: ${p => p.theme.breakpoints.large}) {
  1293. border-top: 1px solid ${p => p.theme.gray200};
  1294. grid-row: 2/2;
  1295. grid-column: 1/-1;
  1296. max-width: 100%;
  1297. }
  1298. @media (min-width: ${p => p.theme.breakpoints.large}) {
  1299. border-left: 1px solid ${p => p.theme.gray200};
  1300. /* to be consistent with Layout.Body in other verticals */
  1301. padding-right: ${space(4)};
  1302. max-width: 400px;
  1303. }
  1304. `;
  1305. const MainWrapper = styled('div')`
  1306. display: flex;
  1307. flex-direction: column;
  1308. @media (max-width: ${p => p.theme.breakpoints.large}) {
  1309. grid-column: 1/-1;
  1310. }
  1311. `;
  1312. const NameWidgetStep = styled(BuildStep)`
  1313. ${FieldWrapper} {
  1314. padding: 0 ${space(2)} 0 0;
  1315. border-bottom: none;
  1316. }
  1317. `;
  1318. const StyledTextAreaField = styled(TextareaField)`
  1319. margin-top: ${space(1.5)};
  1320. `;