widgetContainer.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. import {useEffect, useState} from 'react';
  2. import {browserHistory} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import omit from 'lodash/omit';
  5. import pick from 'lodash/pick';
  6. import * as qs from 'query-string';
  7. import {CompactSelect, SelectOption} from 'sentry/components/compactSelect';
  8. import {CompositeSelect} from 'sentry/components/compactSelect/composite';
  9. import DropdownButton from 'sentry/components/dropdownButton';
  10. import {IconEllipsis} from 'sentry/icons/iconEllipsis';
  11. import {t} from 'sentry/locale';
  12. import {space} from 'sentry/styles/space';
  13. import {Organization} from 'sentry/types';
  14. import {trackAnalytics} from 'sentry/utils/analytics';
  15. import EventView from 'sentry/utils/discover/eventView';
  16. import {Field} from 'sentry/utils/discover/fields';
  17. import {DisplayModes} from 'sentry/utils/discover/types';
  18. import {useMEPSettingContext} from 'sentry/utils/performance/contexts/metricsEnhancedSetting';
  19. import {usePerformanceDisplayType} from 'sentry/utils/performance/contexts/performanceDisplayContext';
  20. import useOrganization from 'sentry/utils/useOrganization';
  21. import {normalizeUrl} from 'sentry/utils/withDomainRequired';
  22. import withOrganization from 'sentry/utils/withOrganization';
  23. import {GenericPerformanceWidgetDataType} from '../types';
  24. import {_setChartSetting, filterAllowedChartsMetrics, getChartSetting} from '../utils';
  25. import {
  26. ChartDefinition,
  27. PerformanceWidgetSetting,
  28. WIDGET_DEFINITIONS,
  29. } from '../widgetDefinitions';
  30. import {HistogramWidget} from '../widgets/histogramWidget';
  31. import {LineChartListWidget} from '../widgets/lineChartListWidget';
  32. import {SingleFieldAreaWidget} from '../widgets/singleFieldAreaWidget';
  33. import {StackedAreaChartListWidget} from '../widgets/stackedAreaChartListWidget';
  34. import {TrendsWidget} from '../widgets/trendsWidget';
  35. import {VitalWidget} from '../widgets/vitalWidget';
  36. import {ChartRowProps} from './widgetChartRow';
  37. interface Props extends ChartRowProps {
  38. allowedCharts: PerformanceWidgetSetting[];
  39. chartHeight: number;
  40. defaultChartSetting: PerformanceWidgetSetting;
  41. eventView: EventView;
  42. index: number;
  43. organization: Organization;
  44. rowChartSettings: PerformanceWidgetSetting[];
  45. setRowChartSettings: (settings: PerformanceWidgetSetting[]) => void;
  46. withStaticFilters: boolean;
  47. chartColor?: string;
  48. forceDefaultChartSetting?: boolean;
  49. }
  50. function trackChartSettingChange(
  51. previousChartSetting: PerformanceWidgetSetting,
  52. chartSetting: PerformanceWidgetSetting,
  53. fromDefault: boolean,
  54. organization: Organization
  55. ) {
  56. trackAnalytics('performance_views.landingv3.widget.switch', {
  57. organization,
  58. from_widget: previousChartSetting,
  59. to_widget: chartSetting,
  60. from_default: fromDefault,
  61. is_new_menu: organization.features.includes('performance-new-widget-designs'),
  62. });
  63. }
  64. const _WidgetContainer = (props: Props) => {
  65. const {
  66. organization,
  67. index,
  68. chartHeight,
  69. rowChartSettings,
  70. setRowChartSettings,
  71. ...rest
  72. } = props;
  73. const performanceType = usePerformanceDisplayType();
  74. let _chartSetting = getChartSetting(
  75. index,
  76. chartHeight,
  77. performanceType,
  78. rest.defaultChartSetting,
  79. rest.forceDefaultChartSetting
  80. );
  81. const mepSetting = useMEPSettingContext();
  82. const allowedCharts = filterAllowedChartsMetrics(
  83. props.organization,
  84. props.allowedCharts,
  85. mepSetting
  86. );
  87. if (!allowedCharts.includes(_chartSetting)) {
  88. _chartSetting = rest.defaultChartSetting;
  89. }
  90. const [chartSetting, setChartSettingState] = useState(_chartSetting);
  91. const setChartSetting = (setting: PerformanceWidgetSetting) => {
  92. if (!props.forceDefaultChartSetting) {
  93. _setChartSetting(index, chartHeight, performanceType, setting);
  94. }
  95. setChartSettingState(setting);
  96. const newSettings = [...rowChartSettings];
  97. newSettings[index] = setting;
  98. setRowChartSettings(newSettings);
  99. trackChartSettingChange(
  100. chartSetting,
  101. setting,
  102. rest.defaultChartSetting === chartSetting,
  103. organization
  104. );
  105. };
  106. useEffect(() => {
  107. setChartSettingState(_chartSetting);
  108. }, [rest.defaultChartSetting, _chartSetting]);
  109. const chartDefinition = WIDGET_DEFINITIONS({organization})[chartSetting];
  110. // Construct an EventView that matches this widget's definition. The
  111. // `eventView` from the props is the _landing page_ EventView, which is different
  112. const widgetEventView = makeEventViewForWidget(props.eventView, chartDefinition);
  113. const showNewWidgetDesign = organization.features.includes(
  114. 'performance-new-widget-designs'
  115. );
  116. const widgetProps = {
  117. ...chartDefinition,
  118. chartSetting,
  119. chartDefinition,
  120. InteractiveTitle: showNewWidgetDesign
  121. ? containerProps => (
  122. <WidgetInteractiveTitle
  123. {...containerProps}
  124. eventView={widgetEventView}
  125. allowedCharts={allowedCharts}
  126. chartSetting={chartSetting}
  127. setChartSetting={setChartSetting}
  128. rowChartSettings={rowChartSettings}
  129. />
  130. )
  131. : null,
  132. ContainerActions: !showNewWidgetDesign
  133. ? containerProps => (
  134. <WidgetContainerActions
  135. {...containerProps}
  136. eventView={widgetEventView}
  137. allowedCharts={allowedCharts}
  138. chartSetting={chartSetting}
  139. setChartSetting={setChartSetting}
  140. rowChartSettings={rowChartSettings}
  141. />
  142. )
  143. : null,
  144. };
  145. const passedProps = pick(props, [
  146. 'eventView',
  147. 'location',
  148. 'organization',
  149. 'chartHeight',
  150. 'withStaticFilters',
  151. ]);
  152. const titleTooltip = showNewWidgetDesign ? '' : widgetProps.titleTooltip;
  153. switch (widgetProps.dataType) {
  154. case GenericPerformanceWidgetDataType.TRENDS:
  155. return (
  156. <TrendsWidget {...passedProps} {...widgetProps} titleTooltip={titleTooltip} />
  157. );
  158. case GenericPerformanceWidgetDataType.AREA:
  159. return (
  160. <SingleFieldAreaWidget
  161. {...passedProps}
  162. {...widgetProps}
  163. titleTooltip={titleTooltip}
  164. />
  165. );
  166. case GenericPerformanceWidgetDataType.VITALS:
  167. return (
  168. <VitalWidget {...passedProps} {...widgetProps} titleTooltip={titleTooltip} />
  169. );
  170. case GenericPerformanceWidgetDataType.LINE_LIST:
  171. return (
  172. <LineChartListWidget
  173. {...passedProps}
  174. {...widgetProps}
  175. titleTooltip={titleTooltip}
  176. />
  177. );
  178. case GenericPerformanceWidgetDataType.HISTOGRAM:
  179. return (
  180. <HistogramWidget {...passedProps} {...widgetProps} titleTooltip={titleTooltip} />
  181. );
  182. case GenericPerformanceWidgetDataType.STACKED_AREA:
  183. return <StackedAreaChartListWidget {...passedProps} {...widgetProps} />;
  184. default:
  185. throw new Error(`Widget type "${widgetProps.dataType}" has no implementation.`);
  186. }
  187. };
  188. export function WidgetInteractiveTitle({
  189. chartSetting,
  190. eventView,
  191. setChartSetting,
  192. allowedCharts,
  193. rowChartSettings,
  194. }) {
  195. const organization = useOrganization();
  196. const menuOptions: SelectOption<string>[] = [];
  197. const settingsMap = WIDGET_DEFINITIONS({organization});
  198. for (const setting of allowedCharts) {
  199. const options = settingsMap[setting];
  200. menuOptions.push({
  201. value: setting,
  202. label: options.title,
  203. disabled: setting !== chartSetting && rowChartSettings.includes(setting),
  204. });
  205. }
  206. const chartDefinition = WIDGET_DEFINITIONS({organization})[chartSetting];
  207. if (chartDefinition.allowsOpenInDiscover) {
  208. menuOptions.push({label: t('Open in Discover'), value: 'open_in_discover'});
  209. }
  210. const handleChange = option => {
  211. if (option.value === 'open_in_discover') {
  212. browserHistory.push(
  213. normalizeUrl(getEventViewDiscoverPath(organization, eventView))
  214. );
  215. } else {
  216. setChartSetting(option.value);
  217. }
  218. };
  219. return (
  220. <StyledCompactSelect
  221. options={menuOptions}
  222. value={chartSetting}
  223. onChange={handleChange}
  224. triggerProps={{borderless: true, size: 'zero'}}
  225. offset={4}
  226. />
  227. );
  228. }
  229. const StyledCompactSelect = styled(CompactSelect)`
  230. /* Reset font-weight set by HeaderTitleLegend, buttons are already bold and
  231. * setting this higher up causes it to trickle into the menues */
  232. font-weight: normal;
  233. margin: -${space(0.5)} -${space(1)} -${space(0.25)};
  234. min-width: 0;
  235. button {
  236. padding: ${space(0.5)} ${space(1)};
  237. font-size: ${p => p.theme.fontSizeLarge};
  238. }
  239. `;
  240. export function WidgetContainerActions({
  241. chartSetting,
  242. eventView,
  243. setChartSetting,
  244. allowedCharts,
  245. rowChartSettings,
  246. }: {
  247. allowedCharts: PerformanceWidgetSetting[];
  248. chartSetting: PerformanceWidgetSetting;
  249. eventView: EventView;
  250. rowChartSettings: PerformanceWidgetSetting[];
  251. setChartSetting: (setting: PerformanceWidgetSetting) => void;
  252. }) {
  253. const organization = useOrganization();
  254. const menuOptions: SelectOption<PerformanceWidgetSetting>[] = [];
  255. const settingsMap = WIDGET_DEFINITIONS({organization});
  256. for (const setting of allowedCharts) {
  257. const options = settingsMap[setting];
  258. menuOptions.push({
  259. value: setting,
  260. label: options.title,
  261. disabled: setting !== chartSetting && rowChartSettings.includes(setting),
  262. });
  263. }
  264. const chartDefinition = WIDGET_DEFINITIONS({organization})[chartSetting];
  265. function handleWidgetActionChange(value) {
  266. if (value === 'open_in_discover') {
  267. browserHistory.push(
  268. normalizeUrl(getEventViewDiscoverPath(organization, eventView))
  269. );
  270. }
  271. }
  272. return (
  273. <CompositeSelect
  274. trigger={triggerProps => (
  275. <DropdownButton
  276. {...triggerProps}
  277. size="xs"
  278. borderless
  279. showChevron={false}
  280. icon={<IconEllipsis aria-label={t('More')} />}
  281. />
  282. )}
  283. position="bottom-end"
  284. >
  285. <CompositeSelect.Region
  286. label={t('Display')}
  287. options={menuOptions}
  288. value={chartSetting}
  289. onChange={opt => setChartSetting(opt.value)}
  290. />
  291. {chartDefinition.allowsOpenInDiscover && (
  292. <CompositeSelect.Region
  293. label={t('Other')}
  294. options={[{label: t('Open in Discover'), value: 'open_in_discover'}]}
  295. value=""
  296. onChange={opt => handleWidgetActionChange(opt.value)}
  297. />
  298. )}
  299. </CompositeSelect>
  300. );
  301. }
  302. const getEventViewDiscoverPath = (
  303. organization: Organization,
  304. eventView: EventView
  305. ): string => {
  306. const discoverUrlTarget = eventView.getResultsViewUrlTarget(organization.slug);
  307. // The landing page EventView has some additional conditions, but
  308. // `EventView#getResultsViewUrlTarget` omits those! Get them manually
  309. discoverUrlTarget.query.query = eventView.getQueryWithAdditionalConditions();
  310. return `${discoverUrlTarget.pathname}?${qs.stringify(
  311. omit(discoverUrlTarget.query, ['widths']) // Column widths are not useful in this case
  312. )}`;
  313. };
  314. /**
  315. * Constructs an `EventView` that matches a widget's chart definition.
  316. * @param baseEventView Any valid event view. The easiest way to make a new EventView is to clone an existing one, because `EventView#constructor` takes too many abstract arguments
  317. * @param chartDefinition
  318. */
  319. const makeEventViewForWidget = (
  320. baseEventView: EventView,
  321. chartDefinition: ChartDefinition
  322. ): EventView => {
  323. const widgetEventView = baseEventView.clone();
  324. widgetEventView.name = chartDefinition.title;
  325. widgetEventView.yAxis = chartDefinition.fields[0]; // All current widgets only have one field
  326. widgetEventView.display = DisplayModes.PREVIOUS;
  327. widgetEventView.fields = ['transaction', 'project', ...chartDefinition.fields].map(
  328. fieldName => ({field: fieldName} as Field)
  329. );
  330. return widgetEventView;
  331. };
  332. const WidgetContainer = withOrganization(_WidgetContainer);
  333. export default WidgetContainer;