widgetBuilder.tsx 50 KB

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