widgetBuilder.tsx 52 KB

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