widgetBuilder.tsx 48 KB

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