widgetBuilder.tsx 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368
  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 {MetricsCardinalityProvider} from 'sentry/utils/performance/contexts/metricsCardinality';
  36. import {MetricsResultsMetaProvider} from 'sentry/utils/performance/contexts/metricsEnhancedPerformanceDataContext';
  37. import {MEPSettingProvider} from 'sentry/utils/performance/contexts/metricsEnhancedSetting';
  38. import {OnDemandControlProvider} from 'sentry/utils/performance/contexts/onDemandControl';
  39. import useApi from 'sentry/utils/useApi';
  40. import {normalizeUrl} from 'sentry/utils/withDomainRequired';
  41. import withPageFilters from 'sentry/utils/withPageFilters';
  42. import withTags from 'sentry/utils/withTags';
  43. import {
  44. assignTempId,
  45. enforceWidgetHeightValues,
  46. generateWidgetsAfterCompaction,
  47. getDefaultWidgetHeight,
  48. } from 'sentry/views/dashboards/layoutUtils';
  49. import type {DashboardDetails, Widget, WidgetQuery} from 'sentry/views/dashboards/types';
  50. import {
  51. DashboardWidgetSource,
  52. DisplayType,
  53. WidgetType,
  54. } from 'sentry/views/dashboards/types';
  55. import {MetricsDataSwitcher} from 'sentry/views/performance/landing/metricsDataSwitcher';
  56. import {DEFAULT_STATS_PERIOD} from '../data';
  57. import {getDatasetConfig} from '../datasetConfig/base';
  58. import {hasThresholdMaxValue} from '../utils';
  59. import {
  60. DashboardsMEPConsumer,
  61. DashboardsMEPProvider,
  62. } from '../widgetCard/dashboardsMEPContext';
  63. import {BuildStep} from './buildSteps/buildStep';
  64. import {ColumnsStep} from './buildSteps/columnsStep';
  65. import {DataSetStep} from './buildSteps/dataSetStep';
  66. import {FilterResultsStep} from './buildSteps/filterResultsStep';
  67. import {GroupByStep} from './buildSteps/groupByStep';
  68. import {SortByStep} from './buildSteps/sortByStep';
  69. import type {
  70. ThresholdMaxKeys,
  71. ThresholdsConfig,
  72. } from './buildSteps/thresholdsStep/thresholdsStep';
  73. import ThresholdsStep from './buildSteps/thresholdsStep/thresholdsStep';
  74. import {VisualizationStep} from './buildSteps/visualizationStep';
  75. import {YAxisStep} from './buildSteps/yAxisStep';
  76. import {Footer} from './footer';
  77. import {Header} from './header';
  78. import {
  79. DataSet,
  80. DEFAULT_RESULTS_LIMIT,
  81. generateOrderOptions,
  82. getIsTimeseriesChart,
  83. getParsedDefaultWidgetQuery,
  84. getResultsLimit,
  85. mapErrors,
  86. NEW_DASHBOARD_ID,
  87. normalizeQueries,
  88. } from './utils';
  89. import {WidgetLibrary} from './widgetLibrary';
  90. const WIDGET_TYPE_TO_DATA_SET = {
  91. [WidgetType.DISCOVER]: DataSet.EVENTS,
  92. [WidgetType.ISSUE]: DataSet.ISSUES,
  93. [WidgetType.RELEASE]: DataSet.RELEASES,
  94. [WidgetType.METRICS]: DataSet.METRICS,
  95. };
  96. export const DATA_SET_TO_WIDGET_TYPE = {
  97. [DataSet.EVENTS]: WidgetType.DISCOVER,
  98. [DataSet.ISSUES]: WidgetType.ISSUE,
  99. [DataSet.RELEASES]: WidgetType.RELEASE,
  100. [DataSet.METRICS]: WidgetType.METRICS,
  101. };
  102. interface RouteParams {
  103. dashboardId: string;
  104. orgId: string;
  105. widgetIndex?: string;
  106. }
  107. interface QueryData {
  108. queryConditions: string[];
  109. queryFields: string[];
  110. queryNames: string[];
  111. queryOrderby: string;
  112. }
  113. interface Props extends RouteComponentProps<RouteParams, {}> {
  114. dashboard: DashboardDetails;
  115. onSave: (widgets: Widget[]) => void;
  116. organization: Organization;
  117. selection: PageFilters;
  118. tags: TagCollection;
  119. displayType?: DisplayType;
  120. end?: DateString;
  121. start?: DateString;
  122. statsPeriod?: string | null;
  123. }
  124. interface State {
  125. dataSet: DataSet;
  126. displayType: Widget['displayType'];
  127. interval: Widget['interval'];
  128. limit: Widget['limit'];
  129. loading: boolean;
  130. prebuiltWidgetId: null | string;
  131. queries: Widget['queries'];
  132. queryConditionsValid: boolean;
  133. title: string;
  134. userHasModified: boolean;
  135. dataType?: string;
  136. dataUnit?: string;
  137. description?: string;
  138. errors?: Record<string, any>;
  139. selectedDashboard?: DashboardDetails['id'];
  140. thresholds?: ThresholdsConfig | null;
  141. widgetToBeUpdated?: Widget;
  142. }
  143. function WidgetBuilder({
  144. dashboard,
  145. params,
  146. location,
  147. organization,
  148. selection,
  149. start,
  150. end,
  151. statsPeriod,
  152. onSave,
  153. route,
  154. router,
  155. tags,
  156. }: Props) {
  157. const {widgetIndex, orgId, dashboardId} = params;
  158. const {source, displayType, defaultTitle, limit, dataset} = location.query;
  159. const defaultWidgetQuery = getParsedDefaultWidgetQuery(
  160. location.query.defaultWidgetQuery
  161. );
  162. // defaultTableColumns can be a single string if location.query only contains
  163. // 1 value for this key. Ensure it is a string[]
  164. let {defaultTableColumns}: {defaultTableColumns: string[]} = location.query;
  165. if (typeof defaultTableColumns === 'string') {
  166. defaultTableColumns = [defaultTableColumns];
  167. }
  168. const hasReleaseHealthFeature = organization.features.includes('dashboards-rh-widget');
  169. const filteredDashboardWidgets = dashboard.widgets.filter(({widgetType}) => {
  170. if (widgetType === WidgetType.RELEASE) {
  171. return hasReleaseHealthFeature;
  172. }
  173. return true;
  174. });
  175. const isEditing = defined(widgetIndex);
  176. const widgetIndexNum = Number(widgetIndex);
  177. const isValidWidgetIndex =
  178. widgetIndexNum >= 0 &&
  179. widgetIndexNum < filteredDashboardWidgets.length &&
  180. Number.isInteger(widgetIndexNum);
  181. const orgSlug = organization.slug;
  182. // Construct PageFilters object using statsPeriod/start/end props so we can
  183. // render widget graph using saved timeframe from Saved/Prebuilt Query
  184. const pageFilters: PageFilters = statsPeriod
  185. ? {...selection, datetime: {start: null, end: null, period: statsPeriod, utc: null}}
  186. : start && end
  187. ? {...selection, datetime: {start, end, period: null, utc: null}}
  188. : selection;
  189. // when opening from discover or issues page, the user selects the dashboard in the widget UI
  190. const notDashboardsOrigin = [
  191. DashboardWidgetSource.DISCOVERV2,
  192. DashboardWidgetSource.ISSUE_DETAILS,
  193. ].includes(source);
  194. const dataSet = dataset ? dataset : DataSet.EVENTS;
  195. const api = useApi();
  196. const [isSubmitting, setIsSubmitting] = useState(false);
  197. const [datasetConfig, setDataSetConfig] = useState<ReturnType<typeof getDatasetConfig>>(
  198. getDatasetConfig(DATA_SET_TO_WIDGET_TYPE[dataSet])
  199. );
  200. const defaultThresholds: ThresholdsConfig = {max_values: {}, unit: null};
  201. const [state, setState] = useState<State>(() => {
  202. const defaultState: State = {
  203. title: defaultTitle ?? t('Custom Widget'),
  204. displayType:
  205. (displayType === DisplayType.TOP_N ? DisplayType.AREA : displayType) ??
  206. DisplayType.TABLE,
  207. interval: '5m',
  208. queries: [],
  209. thresholds: defaultThresholds,
  210. limit: limit ? Number(limit) : undefined,
  211. errors: undefined,
  212. description: undefined,
  213. dataType: undefined,
  214. dataUnit: undefined,
  215. loading: !!notDashboardsOrigin,
  216. userHasModified: false,
  217. prebuiltWidgetId: null,
  218. dataSet,
  219. queryConditionsValid: true,
  220. selectedDashboard: dashboard.id || NEW_DASHBOARD_ID,
  221. };
  222. if (defaultWidgetQuery) {
  223. defaultState.queries = [
  224. {
  225. ...defaultWidgetQuery,
  226. orderby:
  227. defaultWidgetQuery.orderby ||
  228. (datasetConfig.getTableSortOptions
  229. ? datasetConfig.getTableSortOptions(organization, defaultWidgetQuery)[0]
  230. .value
  231. : ''),
  232. },
  233. ];
  234. if (
  235. ![DisplayType.TABLE, DisplayType.TOP_N].includes(defaultState.displayType) &&
  236. !(
  237. getIsTimeseriesChart(defaultState.displayType) &&
  238. defaultState.queries[0].columns.length
  239. )
  240. ) {
  241. defaultState.queries[0].orderby = '';
  242. }
  243. } else {
  244. defaultState.queries = [{...datasetConfig.defaultWidgetQuery}];
  245. }
  246. return defaultState;
  247. });
  248. const [widgetToBeUpdated, setWidgetToBeUpdated] = useState<Widget | null>(null);
  249. // For analytics around widget library selection
  250. const [latestLibrarySelectionTitle, setLatestLibrarySelectionTitle] = useState<
  251. string | null
  252. >(null);
  253. useEffect(() => {
  254. trackAnalytics('dashboards_views.widget_builder.opened', {
  255. organization,
  256. new_widget: !isEditing,
  257. });
  258. if (objectIsEmpty(tags)) {
  259. loadOrganizationTags(api, organization.slug, {
  260. ...selection,
  261. // Pin the request to 14d to avoid timeouts, see DD-967 for
  262. // more information
  263. datetime: {period: '14d', start: null, end: null, utc: null},
  264. });
  265. }
  266. if (isEditing && isValidWidgetIndex) {
  267. const widgetFromDashboard = filteredDashboardWidgets[widgetIndexNum];
  268. let queries;
  269. let newDisplayType = widgetFromDashboard.displayType;
  270. let newLimit = widgetFromDashboard.limit;
  271. if (widgetFromDashboard.displayType === DisplayType.TOP_N) {
  272. newLimit = DEFAULT_RESULTS_LIMIT;
  273. newDisplayType = DisplayType.AREA;
  274. queries = normalizeQueries({
  275. displayType: newDisplayType,
  276. queries: widgetFromDashboard.queries,
  277. widgetType: widgetFromDashboard.widgetType ?? WidgetType.DISCOVER,
  278. }).map(query => ({
  279. ...query,
  280. // Use the last aggregate because that's where the y-axis is stored
  281. aggregates: query.aggregates.length
  282. ? [query.aggregates[query.aggregates.length - 1]]
  283. : [],
  284. }));
  285. } else {
  286. queries = normalizeQueries({
  287. displayType: newDisplayType,
  288. queries: widgetFromDashboard.queries,
  289. widgetType: widgetFromDashboard.widgetType ?? WidgetType.DISCOVER,
  290. });
  291. }
  292. setState({
  293. title: widgetFromDashboard.title,
  294. description: widgetFromDashboard.description,
  295. displayType: newDisplayType,
  296. interval: widgetFromDashboard.interval,
  297. queries,
  298. errors: undefined,
  299. loading: false,
  300. userHasModified: false,
  301. thresholds: widgetFromDashboard.thresholds ?? defaultThresholds,
  302. dataSet: widgetFromDashboard.widgetType
  303. ? WIDGET_TYPE_TO_DATA_SET[widgetFromDashboard.widgetType]
  304. : DataSet.EVENTS,
  305. limit: newLimit,
  306. prebuiltWidgetId: null,
  307. queryConditionsValid: true,
  308. });
  309. setDataSetConfig(getDatasetConfig(widgetFromDashboard.widgetType));
  310. setWidgetToBeUpdated(widgetFromDashboard);
  311. }
  312. // This should only run once on mount
  313. // eslint-disable-next-line react-hooks/exhaustive-deps
  314. }, []);
  315. useEffect(() => {
  316. fetchOrgMembers(api, organization.slug, selection.projects?.map(String));
  317. }, [selection.projects, api, organization.slug]);
  318. useEffect(() => {
  319. const onUnload = () => {
  320. if (!isSubmitting && state.userHasModified) {
  321. return t('You have unsaved changes, are you sure you want to leave?');
  322. }
  323. return undefined;
  324. };
  325. router.setRouteLeaveHook(route, onUnload);
  326. }, [isSubmitting, state.userHasModified, route, router]);
  327. const widgetType = DATA_SET_TO_WIDGET_TYPE[state.dataSet];
  328. const currentWidget = {
  329. title: state.title,
  330. description: state.description,
  331. displayType: state.displayType,
  332. thresholds: state.thresholds,
  333. interval: state.interval,
  334. queries: state.queries,
  335. limit: state.limit,
  336. widgetType,
  337. };
  338. const currentDashboardId = state.selectedDashboard ?? dashboardId;
  339. const queryParamsWithoutSource = omit(location.query, 'source');
  340. const previousLocation = {
  341. pathname:
  342. defined(currentDashboardId) && currentDashboardId !== NEW_DASHBOARD_ID
  343. ? `/organizations/${orgId}/dashboard/${currentDashboardId}/`
  344. : `/organizations/${orgId}/dashboards/${NEW_DASHBOARD_ID}/`,
  345. query:
  346. Object.keys(queryParamsWithoutSource).length === 0
  347. ? undefined
  348. : 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. Object.keys(queryParamsWithoutSource).length > 0 || 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. />
  998. {isTabularChart && (
  999. <DashboardsMEPConsumer>
  1000. {({isMetricsData}) => (
  1001. <ColumnsStep
  1002. dataSet={state.dataSet}
  1003. displayType={state.displayType}
  1004. widgetType={widgetType}
  1005. queryErrors={state.errors?.queries}
  1006. onQueryChange={handleQueryChange}
  1007. handleColumnFieldChange={getHandleColumnFieldChange(
  1008. isMetricsData
  1009. )}
  1010. explodedFields={explodedFields}
  1011. tags={tags}
  1012. organization={organization}
  1013. />
  1014. )}
  1015. </DashboardsMEPConsumer>
  1016. )}
  1017. {![DisplayType.TABLE].includes(state.displayType) && (
  1018. <YAxisStep
  1019. dataSet={state.dataSet}
  1020. displayType={state.displayType}
  1021. widgetType={widgetType}
  1022. queryErrors={state.errors?.queries}
  1023. onYAxisChange={newFields => {
  1024. handleYAxisChange(newFields);
  1025. }}
  1026. aggregates={explodedAggregates}
  1027. tags={tags}
  1028. organization={organization}
  1029. />
  1030. )}
  1031. <FilterResultsStep
  1032. queries={state.queries}
  1033. hideLegendAlias={hideLegendAlias}
  1034. canAddSearchConditions={canAddSearchConditions}
  1035. organization={organization}
  1036. queryErrors={state.errors?.queries}
  1037. onAddSearchConditions={handleAddSearchConditions}
  1038. onQueryChange={handleQueryChange}
  1039. onQueryRemove={handleQueryRemove}
  1040. selection={pageFilters}
  1041. widgetType={widgetType}
  1042. dashboardFilters={dashboard.filters}
  1043. location={location}
  1044. onQueryConditionChange={setQueryConditionsValid}
  1045. />
  1046. {isTimeseriesChart && (
  1047. <GroupByStep
  1048. columns={columns
  1049. .filter(field => !(field === 'equation|'))
  1050. .map((field, index) =>
  1051. explodeField({
  1052. field,
  1053. alias: fieldAliases[index],
  1054. })
  1055. )}
  1056. onGroupByChange={handleGroupByChange}
  1057. organization={organization}
  1058. tags={tags}
  1059. dataSet={state.dataSet}
  1060. queries={state.queries}
  1061. />
  1062. )}
  1063. {displaySortByStep && (
  1064. <SortByStep
  1065. limit={state.limit}
  1066. displayType={state.displayType}
  1067. queries={state.queries}
  1068. dataSet={state.dataSet}
  1069. error={state.errors?.orderby}
  1070. onSortByChange={handleSortByChange}
  1071. onLimitChange={handleLimitChange}
  1072. organization={organization}
  1073. widgetType={widgetType}
  1074. tags={tags}
  1075. />
  1076. )}
  1077. {state.displayType === 'big_number' &&
  1078. state.dataType !== 'date' &&
  1079. organization.features.includes(
  1080. 'dashboard-widget-indicators'
  1081. ) && (
  1082. <ThresholdsStep
  1083. onThresholdChange={handleThresholdChange}
  1084. onUnitChange={handleThresholdUnitChange}
  1085. thresholdsConfig={state.thresholds ?? null}
  1086. dataType={state.dataType}
  1087. dataUnit={state.dataUnit}
  1088. errors={state.errors?.thresholds}
  1089. />
  1090. )}
  1091. </BuildSteps>
  1092. </Main>
  1093. <Footer
  1094. goBackLocation={previousLocation}
  1095. isEditing={isEditing}
  1096. onSave={handleSave}
  1097. onDelete={handleDelete}
  1098. invalidForm={isFormInvalid()}
  1099. />
  1100. </MainWrapper>
  1101. <Side>
  1102. <WidgetLibrary
  1103. organization={organization}
  1104. selectedWidgetId={
  1105. state.userHasModified ? null : state.prebuiltWidgetId
  1106. }
  1107. onWidgetSelect={prebuiltWidget => {
  1108. setLatestLibrarySelectionTitle(prebuiltWidget.title);
  1109. setDataSetConfig(
  1110. getDatasetConfig(
  1111. prebuiltWidget.widgetType || WidgetType.DISCOVER
  1112. )
  1113. );
  1114. const {id, ...prebuiltWidgetProps} = prebuiltWidget;
  1115. setState({
  1116. ...state,
  1117. ...prebuiltWidgetProps,
  1118. dataSet: prebuiltWidget.widgetType
  1119. ? WIDGET_TYPE_TO_DATA_SET[prebuiltWidget.widgetType]
  1120. : DataSet.EVENTS,
  1121. userHasModified: false,
  1122. prebuiltWidgetId: id || null,
  1123. });
  1124. }}
  1125. bypassOverwriteModal={!state.userHasModified}
  1126. />
  1127. </Side>
  1128. </Body>
  1129. </Layout.Page>
  1130. </MEPSettingProvider>
  1131. )}
  1132. </MetricsDataSwitcher>
  1133. </MetricsCardinalityProvider>
  1134. </DashboardsMEPProvider>
  1135. </MetricsResultsMetaProvider>
  1136. </OnDemandControlProvider>
  1137. </CustomMeasurementsProvider>
  1138. </PageFiltersContainer>
  1139. </SentryDocumentTitle>
  1140. );
  1141. }
  1142. export default withPageFilters(withTags(WidgetBuilder));
  1143. const TitleInput = styled(InputField)`
  1144. padding: 0 ${space(2)} 0 0;
  1145. `;
  1146. const BuildSteps = styled(List)`
  1147. gap: ${space(4)};
  1148. max-width: 100%;
  1149. `;
  1150. const Body = styled(Layout.Body)`
  1151. && {
  1152. gap: 0;
  1153. padding: 0;
  1154. }
  1155. grid-template-rows: 1fr;
  1156. @media (min-width: ${p => p.theme.breakpoints.large}) {
  1157. grid-template-columns: minmax(100px, auto) 400px;
  1158. }
  1159. @media (min-width: ${p => p.theme.breakpoints.xlarge}) {
  1160. grid-template-columns: 1fr;
  1161. }
  1162. `;
  1163. // HACK: Since we add 30px of padding to the ListItems
  1164. // there is 30px of overlap when the screen is just above 1200px.
  1165. // When we're up to 1230px (1200 + 30 to account for the padding)
  1166. // we decrease the width of ListItems by 30px
  1167. const Main = styled(Layout.Main)`
  1168. max-width: 1000px;
  1169. flex: 1;
  1170. padding: ${space(4)} ${space(2)};
  1171. @media (min-width: ${p => p.theme.breakpoints.medium}) {
  1172. padding: ${space(4)};
  1173. }
  1174. @media (max-width: calc(${p => p.theme.breakpoints.large} + ${space(4)})) {
  1175. ${ListItem} {
  1176. width: calc(100% - ${space(4)});
  1177. }
  1178. }
  1179. `;
  1180. const Side = styled(Layout.Side)`
  1181. padding: ${space(4)} ${space(2)};
  1182. @media (max-width: ${p => p.theme.breakpoints.large}) {
  1183. border-top: 1px solid ${p => p.theme.gray200};
  1184. grid-row: 2/2;
  1185. grid-column: 1/-1;
  1186. max-width: 100%;
  1187. }
  1188. @media (min-width: ${p => p.theme.breakpoints.large}) {
  1189. border-left: 1px solid ${p => p.theme.gray200};
  1190. /* to be consistent with Layout.Body in other verticals */
  1191. padding-right: ${space(4)};
  1192. max-width: 400px;
  1193. }
  1194. `;
  1195. const MainWrapper = styled('div')`
  1196. display: flex;
  1197. flex-direction: column;
  1198. @media (max-width: ${p => p.theme.breakpoints.large}) {
  1199. grid-column: 1/-1;
  1200. }
  1201. `;
  1202. const NameWidgetStep = styled(BuildStep)`
  1203. ${FieldWrapper} {
  1204. padding: 0 ${space(2)} 0 0;
  1205. border-bottom: none;
  1206. }
  1207. `;
  1208. const StyledTextAreaField = styled(TextareaField)`
  1209. margin-top: ${space(1.5)};
  1210. `;