widgetBuilder.tsx 48 KB

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