widgetBuilder.tsx 41 KB

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