widgetBuilder.tsx 50 KB

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