vitalsAlertCTA.tsx 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. import {useEffect} from 'react';
  2. import styled from '@emotion/styled';
  3. import maxBy from 'lodash/maxBy';
  4. import {promptsUpdate} from 'sentry/actionCreators/prompts';
  5. import {
  6. NotificationBar,
  7. StyledNotificationBarIconInfo,
  8. } from 'sentry/components/alerts/notificationBar';
  9. import Button from 'sentry/components/button';
  10. import ButtonBar from 'sentry/components/buttonBar';
  11. import ExternalLink from 'sentry/components/links/externalLink';
  12. import {IconClose} from 'sentry/icons';
  13. import {t, tct} from 'sentry/locale';
  14. import trackAdvancedAnalyticsEvent from 'sentry/utils/analytics/trackAdvancedAnalyticsEvent';
  15. import useApi from 'sentry/utils/useApi';
  16. import useOrganization from 'sentry/utils/useOrganization';
  17. import {
  18. INDUSTRY_STANDARDS,
  19. MIN_VITAL_COUNT_FOR_DISPLAY,
  20. SENTRY_CUSTOMERS,
  21. } from './constants';
  22. import {VitalsKey, VitalsResult} from './types';
  23. import {getCountParameterName, getRelativeDiff, getWorstVital} from './utils';
  24. interface Props {
  25. data: VitalsResult;
  26. dismissAlert: () => void;
  27. }
  28. function getPercentage(diff: number) {
  29. return <strong>{Math.abs(Math.round(diff * 100))}%</strong>;
  30. }
  31. function getDocsLink(vital: VitalsKey) {
  32. switch (vital) {
  33. case 'FCP':
  34. return 'https://docs.sentry.io/product/performance/web-vitals/#first-contentful-paint-fcp';
  35. case 'LCP':
  36. return 'https://docs.sentry.io/product/performance/web-vitals/#largest-contentful-paint-lcp';
  37. default:
  38. // just one link for mobile vitals
  39. return 'https://docs.sentry.io/product/performance/mobile-vitals/#app-start';
  40. }
  41. }
  42. function getVitalsType(vital: VitalsKey) {
  43. return ['FCP', 'LCP'].includes(vital) ? 'web' : 'mobile';
  44. }
  45. export default function VitalsAlertCTA({data, dismissAlert}: Props) {
  46. const organization = useOrganization();
  47. // persist to dismiss alert
  48. const api = useApi({persistInFlight: true});
  49. const vital = getWorstVital(data);
  50. const userVitalValue = vital ? data[vital] : 0;
  51. const userVitalCount = vital ? data[getCountParameterName(vital)] : 0;
  52. const sentryDiff = vital ? getRelativeDiff(userVitalValue, SENTRY_CUSTOMERS[vital]) : 0;
  53. const industryDiff = vital
  54. ? getRelativeDiff(userVitalValue, INDUSTRY_STANDARDS[vital])
  55. : 0;
  56. // must have the global-views
  57. // and either be an owner/manager or the org allows open membership
  58. const canSeeAllProjects =
  59. organization.features.includes('global-views') &&
  60. (['owner', 'manager'].includes(organization.orgRole || '') ||
  61. organization.features.includes('open-membership'));
  62. // find the project that has the most events of the same type
  63. const bestProjectData = vital
  64. ? maxBy(data.projectData, item => {
  65. const parameterName = getCountParameterName(vital);
  66. return item[parameterName];
  67. })
  68. : null;
  69. const industryDiffPercentage = getPercentage(industryDiff);
  70. const sentryDiffPercentage = getPercentage(sentryDiff);
  71. const vitalsType = vital ? getVitalsType(vital) : null;
  72. const getAnalyticsParams = () => {
  73. // shouldn't call any analytics function if this is missing
  74. // but this check helps us with typing
  75. if (!vital || !vitalsType) {
  76. throw new Error('Cannot get analytics params without vital');
  77. }
  78. return {
  79. vital,
  80. vitals_type: vitalsType,
  81. organization,
  82. user_vital_value: userVitalValue,
  83. user_vital_count: userVitalCount,
  84. sentry_diff: sentryDiff,
  85. industry_diff: industryDiff,
  86. can_see_all_projects: canSeeAllProjects,
  87. } as const;
  88. };
  89. const showVitalsAlert = () => {
  90. // check if we have the vital and the count is at least at the min
  91. if (!vital || userVitalCount < MIN_VITAL_COUNT_FOR_DISPLAY) {
  92. return false;
  93. }
  94. // if worst vital is better than Sentry users, we shouldn't show this alert
  95. if (sentryDiff < 0) {
  96. return false;
  97. }
  98. // must either be able to see all proejcts or we can pick a specific project
  99. return canSeeAllProjects || bestProjectData;
  100. };
  101. useEffect(() => {
  102. if (!vital || !showVitalsAlert()) {
  103. return;
  104. }
  105. trackAdvancedAnalyticsEvent('vitals_alert.displayed', getAnalyticsParams());
  106. });
  107. if (!vital || !showVitalsAlert()) {
  108. return null;
  109. }
  110. function getVitalWithLink() {
  111. if (!vital) {
  112. throw new Error('Cannot get vitals link without vital');
  113. }
  114. const url = new URL(getDocsLink(vital));
  115. url.searchParams.append('referrer', 'vitals-alert');
  116. return (
  117. <ExternalLink
  118. onClick={() => {
  119. trackAdvancedAnalyticsEvent('vitals_alert.clicked_docs', getAnalyticsParams());
  120. }}
  121. href={url.toString()}
  122. >
  123. {vital}
  124. </ExternalLink>
  125. );
  126. }
  127. const getText = () => {
  128. const args = {
  129. vital: getVitalWithLink(),
  130. industryDiffPercentage,
  131. sentryDiffPercentage,
  132. };
  133. // different language if we are better than the industry average
  134. if (industryDiff < 0) {
  135. return tct(
  136. "Your organization's [vital] is [industryDiffPercentage] lower than the industry standard, but [sentryDiffPercentage] higher than typical Sentry users.",
  137. args
  138. );
  139. }
  140. return tct(
  141. "Your organization's [vital] is [industryDiffPercentage] higher than the industry standard and [sentryDiffPercentage] higher than typical Sentry users.",
  142. args
  143. );
  144. };
  145. const getVitalsURL = () => {
  146. const performanceRoot = `/organizations/${organization.slug}/performance`;
  147. const baseParams: Record<string, string | undefined> = {
  148. statsPeriod: '7d',
  149. referrer: `vitals-alert-${vital.toLowerCase()}`,
  150. project: canSeeAllProjects ? '-1' : bestProjectData?.projectId,
  151. };
  152. // we can land on a specific web vital
  153. if (vitalsType === 'web') {
  154. const searchParams = new URLSearchParams({
  155. ...baseParams,
  156. vitalName: `measurements.${vital.toLowerCase()}`,
  157. });
  158. return `${performanceRoot}/vitaldetail/?${searchParams}`;
  159. }
  160. // otherwise it's just the mobile vital screen
  161. const searchParams = new URLSearchParams({
  162. ...baseParams,
  163. landingDisplay: 'mobile',
  164. });
  165. return `${performanceRoot}/?${searchParams}`;
  166. };
  167. const buttonText = vitalsType === 'web' ? t('See Web Vitals') : t('See Mobile Vitals');
  168. const dismissAndPromptUpdate = () => {
  169. promptsUpdate(api, {
  170. organizationId: organization?.id,
  171. feature: 'vitals_alert',
  172. status: 'dismissed',
  173. });
  174. dismissAlert();
  175. };
  176. return (
  177. <NotificationBar>
  178. <StyledNotificationBarIconInfo />
  179. {getText()}
  180. <NotificationBarButtons gap={1}>
  181. <Button
  182. to={getVitalsURL()}
  183. size="xs"
  184. onClick={() => {
  185. dismissAndPromptUpdate();
  186. trackAdvancedAnalyticsEvent(
  187. 'vitals_alert.clicked_see_vitals',
  188. getAnalyticsParams()
  189. );
  190. }}
  191. >
  192. {buttonText}
  193. </Button>
  194. <Button
  195. icon={<IconClose />}
  196. onClick={() => {
  197. dismissAndPromptUpdate();
  198. trackAdvancedAnalyticsEvent('vitals_alert.dismissed', getAnalyticsParams());
  199. }}
  200. size="xs"
  201. priority="link"
  202. title={t('Dismiss')}
  203. aria-label={t('Dismiss')}
  204. />
  205. </NotificationBarButtons>
  206. </NotificationBar>
  207. );
  208. }
  209. const NotificationBarButtons = styled(ButtonBar)`
  210. margin-left: auto;
  211. white-space: nowrap;
  212. `;