widgetBuilder.tsx 46 KB

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