widgetBuilder.tsx 43 KB

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