widgetBuilder.tsx 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262
  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 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 = [DisplayType.TABLE, DisplayType.BIG_NUMBER].includes(
  808. state.displayType
  809. );
  810. // Tabular visualizations will always have only one query and that query cannot be deleted,
  811. // so we will always have the first query available to get data from.
  812. const {columns, aggregates, fields, fieldAliases = []} = state.queries[0];
  813. const explodedColumns = useMemo(() => {
  814. return columns.map((field, index) =>
  815. explodeField({field, alias: fieldAliases[index]})
  816. );
  817. }, [columns, fieldAliases]);
  818. const explodedAggregates = useMemo(() => {
  819. return aggregates.map((field, index) =>
  820. explodeField({field, alias: fieldAliases[index]})
  821. );
  822. }, [aggregates, fieldAliases]);
  823. const explodedFields = defined(fields)
  824. ? fields.map((field, index) => explodeField({field, alias: fieldAliases[index]}))
  825. : [...explodedColumns, ...explodedAggregates];
  826. const groupByValueSelected = currentWidget.queries.some(query => {
  827. const noEmptyColumns = query.columns.filter(column => !!column);
  828. return noEmptyColumns.length > 0;
  829. });
  830. // The SortBy field shall only be displayed in tabular visualizations or
  831. // on time-series visualizations when at least one groupBy value is selected
  832. const displaySortByStep = (isTimeseriesChart && groupByValueSelected) || isTabularChart;
  833. if (isEditing && !isValidWidgetIndex) {
  834. return (
  835. <SentryDocumentTitle title={dashboard.title} orgSlug={orgSlug}>
  836. <Layout.Page withPadding>
  837. <LoadingError message={t('The widget you want to edit was not found.')} />
  838. </Layout.Page>
  839. </SentryDocumentTitle>
  840. );
  841. }
  842. return (
  843. <SentryDocumentTitle title={dashboard.title} orgSlug={orgSlug}>
  844. <PageFiltersContainer
  845. defaultSelection={{
  846. datetime: {start: null, end: null, utc: null, period: DEFAULT_STATS_PERIOD},
  847. }}
  848. >
  849. <CustomMeasurementsProvider organization={organization} selection={selection}>
  850. <DashboardsMEPProvider>
  851. <MetricsCardinalityProvider organization={organization} location={location}>
  852. <MetricsDataSwitcher
  853. organization={organization}
  854. eventView={EventView.fromLocation(location)}
  855. location={location}
  856. hideLoadingIndicator
  857. >
  858. {metricsDataSide => (
  859. <MEPSettingProvider
  860. location={location}
  861. forceTransactions={metricsDataSide.forceTransactionsOnly}
  862. >
  863. <Layout.Page>
  864. <Header
  865. orgSlug={orgSlug}
  866. dashboardTitle={dashboard.title}
  867. goBackLocation={previousLocation}
  868. />
  869. <Body>
  870. <MainWrapper>
  871. <Main>
  872. <BuildSteps symbol="colored-numeric">
  873. <NameWidgetStep title={t('Name your widget')}>
  874. <TitleInput
  875. name="title"
  876. inline={false}
  877. aria-label={t('Widget title')}
  878. placeholder={t('Enter title')}
  879. error={state.errors?.title}
  880. data-test-id="widget-builder-title-input"
  881. onChange={newTitle => {
  882. handleDisplayTypeOrAnnotationChange(
  883. 'title',
  884. newTitle
  885. );
  886. }}
  887. value={state.title}
  888. />
  889. <StyledTextAreaField
  890. name="description"
  891. rows={4}
  892. autosize
  893. inline={false}
  894. aria-label={t('Widget Description')}
  895. placeholder={t('Enter description (Optional)')}
  896. error={state.errors?.description}
  897. onChange={newDescription => {
  898. handleDisplayTypeOrAnnotationChange(
  899. 'description',
  900. newDescription
  901. );
  902. }}
  903. value={state.description}
  904. />
  905. </NameWidgetStep>
  906. <VisualizationStep
  907. location={location}
  908. widget={currentWidget}
  909. dashboardFilters={dashboard.filters}
  910. organization={organization}
  911. pageFilters={pageFilters}
  912. displayType={state.displayType}
  913. error={state.errors?.displayType}
  914. onChange={newDisplayType => {
  915. handleDisplayTypeOrAnnotationChange(
  916. 'displayType',
  917. newDisplayType
  918. );
  919. }}
  920. noDashboardsMEPProvider
  921. isWidgetInvalid={!state.queryConditionsValid}
  922. />
  923. <DataSetStep
  924. dataSet={state.dataSet}
  925. displayType={state.displayType}
  926. onChange={handleDataSetChange}
  927. hasReleaseHealthFeature={hasReleaseHealthFeature}
  928. />
  929. {isTabularChart && (
  930. <DashboardsMEPConsumer>
  931. {({isMetricsData}) => (
  932. <ColumnsStep
  933. dataSet={state.dataSet}
  934. queries={state.queries}
  935. displayType={state.displayType}
  936. widgetType={widgetType}
  937. queryErrors={state.errors?.queries}
  938. onQueryChange={handleQueryChange}
  939. handleColumnFieldChange={getHandleColumnFieldChange(
  940. isMetricsData
  941. )}
  942. explodedFields={explodedFields}
  943. tags={tags}
  944. organization={organization}
  945. />
  946. )}
  947. </DashboardsMEPConsumer>
  948. )}
  949. {![DisplayType.TABLE].includes(state.displayType) && (
  950. <YAxisStep
  951. dataSet={state.dataSet}
  952. displayType={state.displayType}
  953. widgetType={widgetType}
  954. queryErrors={state.errors?.queries}
  955. onYAxisChange={newFields => {
  956. handleYAxisChange(newFields);
  957. }}
  958. aggregates={explodedAggregates}
  959. tags={tags}
  960. organization={organization}
  961. />
  962. )}
  963. <FilterResultsStep
  964. queries={state.queries}
  965. hideLegendAlias={hideLegendAlias}
  966. canAddSearchConditions={canAddSearchConditions}
  967. organization={organization}
  968. queryErrors={state.errors?.queries}
  969. onAddSearchConditions={handleAddSearchConditions}
  970. onQueryChange={handleQueryChange}
  971. onQueryRemove={handleQueryRemove}
  972. selection={pageFilters}
  973. widgetType={widgetType}
  974. dashboardFilters={dashboard.filters}
  975. location={location}
  976. onQueryConditionChange={setQueryConditionsValid}
  977. />
  978. {isTimeseriesChart && (
  979. <GroupByStep
  980. columns={columns
  981. .filter(field => !(field === 'equation|'))
  982. .map((field, index) =>
  983. explodeField({field, alias: fieldAliases[index]})
  984. )}
  985. onGroupByChange={handleGroupByChange}
  986. organization={organization}
  987. tags={tags}
  988. dataSet={state.dataSet}
  989. />
  990. )}
  991. {displaySortByStep && (
  992. <SortByStep
  993. limit={state.limit}
  994. displayType={state.displayType}
  995. queries={state.queries}
  996. dataSet={state.dataSet}
  997. error={state.errors?.orderby}
  998. onSortByChange={handleSortByChange}
  999. onLimitChange={handleLimitChange}
  1000. organization={organization}
  1001. widgetType={widgetType}
  1002. tags={tags}
  1003. />
  1004. )}
  1005. </BuildSteps>
  1006. </Main>
  1007. <Footer
  1008. goBackLocation={previousLocation}
  1009. isEditing={isEditing}
  1010. onSave={handleSave}
  1011. onDelete={handleDelete}
  1012. invalidForm={isFormInvalid()}
  1013. />
  1014. </MainWrapper>
  1015. <Side>
  1016. <WidgetLibrary
  1017. organization={organization}
  1018. selectedWidgetId={
  1019. state.userHasModified ? null : state.prebuiltWidgetId
  1020. }
  1021. onWidgetSelect={prebuiltWidget => {
  1022. setLatestLibrarySelectionTitle(prebuiltWidget.title);
  1023. setDataSetConfig(
  1024. getDatasetConfig(
  1025. prebuiltWidget.widgetType || WidgetType.DISCOVER
  1026. )
  1027. );
  1028. const {id, ...prebuiltWidgetProps} = prebuiltWidget;
  1029. setState({
  1030. ...state,
  1031. ...prebuiltWidgetProps,
  1032. dataSet: prebuiltWidget.widgetType
  1033. ? WIDGET_TYPE_TO_DATA_SET[prebuiltWidget.widgetType]
  1034. : DataSet.EVENTS,
  1035. userHasModified: false,
  1036. prebuiltWidgetId: id || null,
  1037. });
  1038. }}
  1039. bypassOverwriteModal={!state.userHasModified}
  1040. />
  1041. </Side>
  1042. </Body>
  1043. </Layout.Page>
  1044. </MEPSettingProvider>
  1045. )}
  1046. </MetricsDataSwitcher>
  1047. </MetricsCardinalityProvider>
  1048. </DashboardsMEPProvider>
  1049. </CustomMeasurementsProvider>
  1050. </PageFiltersContainer>
  1051. </SentryDocumentTitle>
  1052. );
  1053. }
  1054. export default withPageFilters(withTags(WidgetBuilder));
  1055. const TitleInput = styled(InputField)`
  1056. padding: 0 ${space(2)} 0 0;
  1057. `;
  1058. const BuildSteps = styled(List)`
  1059. gap: ${space(4)};
  1060. max-width: 100%;
  1061. `;
  1062. const Body = styled(Layout.Body)`
  1063. && {
  1064. gap: 0;
  1065. padding: 0;
  1066. }
  1067. grid-template-rows: 1fr;
  1068. @media (min-width: ${p => p.theme.breakpoints.large}) {
  1069. grid-template-columns: minmax(100px, auto) 400px;
  1070. }
  1071. @media (min-width: ${p => p.theme.breakpoints.xlarge}) {
  1072. grid-template-columns: 1fr;
  1073. }
  1074. `;
  1075. // HACK: Since we add 30px of padding to the ListItems
  1076. // there is 30px of overlap when the screen is just above 1200px.
  1077. // When we're up to 1230px (1200 + 30 to account for the padding)
  1078. // we decrease the width of ListItems by 30px
  1079. const Main = styled(Layout.Main)`
  1080. max-width: 1000px;
  1081. flex: 1;
  1082. padding: ${space(4)} ${space(2)};
  1083. @media (min-width: ${p => p.theme.breakpoints.medium}) {
  1084. padding: ${space(4)};
  1085. }
  1086. @media (max-width: calc(${p => p.theme.breakpoints.large} + ${space(4)})) {
  1087. ${ListItem} {
  1088. width: calc(100% - ${space(4)});
  1089. }
  1090. }
  1091. `;
  1092. const Side = styled(Layout.Side)`
  1093. padding: ${space(4)} ${space(2)};
  1094. @media (max-width: ${p => p.theme.breakpoints.large}) {
  1095. border-top: 1px solid ${p => p.theme.gray200};
  1096. grid-row: 2/2;
  1097. grid-column: 1/-1;
  1098. max-width: 100%;
  1099. }
  1100. @media (min-width: ${p => p.theme.breakpoints.large}) {
  1101. border-left: 1px solid ${p => p.theme.gray200};
  1102. /* to be consistent with Layout.Body in other verticals */
  1103. padding-right: ${space(4)};
  1104. max-width: 400px;
  1105. }
  1106. `;
  1107. const MainWrapper = styled('div')`
  1108. display: flex;
  1109. flex-direction: column;
  1110. @media (max-width: ${p => p.theme.breakpoints.large}) {
  1111. grid-column: 1/-1;
  1112. }
  1113. `;
  1114. const NameWidgetStep = styled(BuildStep)`
  1115. ${FieldWrapper} {
  1116. padding: 0 ${space(2)} 0 0;
  1117. border-bottom: none;
  1118. }
  1119. `;
  1120. const StyledTextAreaField = styled(TextareaField)`
  1121. margin-top: ${space(1.5)};
  1122. `;