widgetBuilder.tsx 48 KB

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