widgetBuilder.tsx 48 KB

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