widgetBuilder.tsx 48 KB

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