setupDocs.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. import {Fragment, useCallback, useEffect, useState} from 'react';
  2. import {browserHistory} from 'react-router';
  3. import {css, Theme} from '@emotion/react';
  4. import styled from '@emotion/styled';
  5. import {motion} from 'framer-motion';
  6. import * as qs from 'query-string';
  7. import {loadDocs} from 'sentry/actionCreators/projects';
  8. import {Alert, alertStyles} from 'sentry/components/alert';
  9. import ExternalLink from 'sentry/components/links/externalLink';
  10. import LoadingError from 'sentry/components/loadingError';
  11. import {PlatformKey} from 'sentry/data/platformCategories';
  12. import platforms from 'sentry/data/platforms';
  13. import {t, tct} from 'sentry/locale';
  14. import {space} from 'sentry/styles/space';
  15. import {Project} from 'sentry/types';
  16. import trackAdvancedAnalyticsEvent from 'sentry/utils/analytics/trackAdvancedAnalyticsEvent';
  17. import getDynamicText from 'sentry/utils/getDynamicText';
  18. import {platformToIntegrationMap} from 'sentry/utils/integrationUtil';
  19. import useApi from 'sentry/utils/useApi';
  20. import {normalizeUrl} from 'sentry/utils/withDomainRequired';
  21. import withProjects from 'sentry/utils/withProjects';
  22. import {HeartbeatFooter} from 'sentry/views/onboarding/components/heartbeatFooter';
  23. import FirstEventFooter from './components/firstEventFooter';
  24. import FullIntroduction from './components/fullIntroduction';
  25. import ProjectSidebarSection from './components/projectSidebarSection';
  26. import IntegrationSetup from './integrationSetup';
  27. import {StepProps} from './types';
  28. import {usePersistedOnboardingState} from './utils';
  29. /**
  30. * The documentation will include the following string should it be missing the
  31. * verification example, which currently a lot of docs are.
  32. */
  33. const INCOMPLETE_DOC_FLAG = 'TODO-ADD-VERIFICATION-EXAMPLE';
  34. type PlatformDoc = {html: string; link: string};
  35. type Props = {
  36. projects: Project[];
  37. search: string;
  38. loadingProjects?: boolean;
  39. } & StepProps;
  40. function ProjectDocs(props: {
  41. hasError: boolean;
  42. onRetry: () => void;
  43. platform: PlatformKey | null;
  44. platformDocs: PlatformDoc | null;
  45. project: Project;
  46. }) {
  47. const testOnlyAlert = (
  48. <Alert type="warning">
  49. Platform documentation is not rendered in for tests in CI
  50. </Alert>
  51. );
  52. const missingExampleWarning = () => {
  53. const missingExample =
  54. props.platformDocs && props.platformDocs.html.includes(INCOMPLETE_DOC_FLAG);
  55. if (!missingExample) {
  56. return null;
  57. }
  58. return (
  59. <Alert type="warning" showIcon>
  60. {tct(
  61. `Looks like this getting started example is still undergoing some
  62. work and doesn't include an example for triggering an event quite
  63. yet. If you have trouble sending your first event be sure to consult
  64. the [docsLink:full documentation] for [platform].`,
  65. {
  66. docsLink: <ExternalLink href={props.platformDocs?.link} />,
  67. platform: platforms.find(p => p.id === props.platform)?.name,
  68. }
  69. )}
  70. </Alert>
  71. );
  72. };
  73. const docs = props.platformDocs !== null && (
  74. <DocsWrapper key={props.platformDocs.html}>
  75. <Content dangerouslySetInnerHTML={{__html: props.platformDocs.html}} />
  76. {missingExampleWarning()}
  77. </DocsWrapper>
  78. );
  79. const loadingError = (
  80. <LoadingError
  81. message={t(
  82. 'Failed to load documentation for the %s platform.',
  83. props.project?.platform
  84. )}
  85. onRetry={props.onRetry}
  86. />
  87. );
  88. const currentPlatform = props.platform ?? props.project?.platform ?? 'other';
  89. return (
  90. <Fragment>
  91. <FullIntroduction currentPlatform={currentPlatform} />
  92. {getDynamicText({
  93. value: !props.hasError ? docs : loadingError,
  94. fixed: testOnlyAlert,
  95. })}
  96. </Fragment>
  97. );
  98. }
  99. function SetupDocs({
  100. organization,
  101. projects: rawProjects,
  102. search,
  103. loadingProjects,
  104. route,
  105. router,
  106. location,
  107. }: Props) {
  108. const heartbeatFooter = !!organization?.features.includes(
  109. 'onboarding-heartbeat-footer'
  110. );
  111. const singleSelectPlatform = !!organization?.features.includes(
  112. 'onboarding-remove-multiselect-platform'
  113. );
  114. const api = useApi();
  115. const [clientState, setClientState] = usePersistedOnboardingState();
  116. const selectedPlatforms = clientState?.selectedPlatforms || [];
  117. const platformToProjectIdMap = clientState?.platformToProjectIdMap || {};
  118. // id is really slug here
  119. const projectSlugs = selectedPlatforms
  120. .map(platform => platformToProjectIdMap[platform])
  121. .filter((slug): slug is string => slug !== undefined);
  122. const selectedProjectsSet = new Set(projectSlugs);
  123. // get projects in the order they appear in selectedPlatforms
  124. const projects = projectSlugs
  125. .map(slug => rawProjects.find(project => project.slug === slug))
  126. .filter((project): project is Project => project !== undefined);
  127. // SDK instrumentation
  128. const [hasError, setHasError] = useState(false);
  129. const [platformDocs, setPlatformDocs] = useState<PlatformDoc | null>(null);
  130. const [loadedPlatform, setLoadedPlatform] = useState<PlatformKey | null>(null);
  131. // store what projects have sent first event in state based project.firstEvent
  132. const [hasFirstEventMap, setHasFirstEventMap] = useState<Record<string, boolean>>(
  133. projects.reduce((accum, project: Project) => {
  134. accum[project.id] = !!project.firstEvent;
  135. return accum;
  136. }, {} as Record<string, boolean>)
  137. );
  138. const checkProjectHasFirstEvent = (project: Project) => {
  139. return !!hasFirstEventMap[project.id];
  140. };
  141. const {project_id: rawProjectId} = qs.parse(search);
  142. const rawProjectIndex = projects.findIndex(p => p.id === rawProjectId);
  143. const firstProjectNoError = projects.findIndex(
  144. p => selectedProjectsSet.has(p.slug) && !checkProjectHasFirstEvent(p)
  145. );
  146. // Select a project based on search params. If non exist, use the first project without first event.
  147. const projectIndex = rawProjectIndex >= 0 ? rawProjectIndex : firstProjectNoError;
  148. const project = projects[projectIndex];
  149. // find the next project that doesn't have a first event
  150. const nextProject = projects.find(
  151. (p, i) => i > projectIndex && !checkProjectHasFirstEvent(p)
  152. );
  153. const integrationSlug = project?.platform && platformToIntegrationMap[project.platform];
  154. const [integrationUseManualSetup, setIntegrationUseManualSetup] = useState(false);
  155. useEffect(() => {
  156. // should not redirect if we don't have an active client state or projects aren't loaded
  157. if (!clientState || loadingProjects) {
  158. return;
  159. }
  160. if (
  161. // If no projects remaining, then we can leave
  162. !project
  163. ) {
  164. // marke onboarding as complete
  165. setClientState({
  166. ...clientState,
  167. state: 'finished',
  168. });
  169. browserHistory.push(
  170. normalizeUrl(
  171. `/organizations/${organization.slug}/issues/?referrer=onboarding-setup-docs-on-complete`
  172. )
  173. );
  174. }
  175. });
  176. const currentPlatform = loadedPlatform ?? project?.platform ?? 'other';
  177. const fetchData = useCallback(async () => {
  178. // TODO: add better error handling logic
  179. if (!project?.platform) {
  180. return;
  181. }
  182. if (integrationSlug && !integrationUseManualSetup) {
  183. setLoadedPlatform(project.platform);
  184. setPlatformDocs(null);
  185. setHasError(false);
  186. return;
  187. }
  188. try {
  189. const loadedDocs = await loadDocs(
  190. api,
  191. organization.slug,
  192. project.slug,
  193. project.platform
  194. );
  195. setPlatformDocs(loadedDocs);
  196. setLoadedPlatform(project.platform);
  197. setHasError(false);
  198. } catch (error) {
  199. setHasError(error);
  200. throw error;
  201. }
  202. }, [project, api, organization, integrationSlug, integrationUseManualSetup]);
  203. useEffect(() => {
  204. fetchData();
  205. }, [fetchData]);
  206. if (!project) {
  207. return null;
  208. }
  209. const setNewProject = (newProjectId: string) => {
  210. setLoadedPlatform(null);
  211. setPlatformDocs(null);
  212. setHasError(false);
  213. setIntegrationUseManualSetup(false);
  214. const searchParams = new URLSearchParams({
  215. sub_step: 'project',
  216. project_id: newProjectId,
  217. });
  218. browserHistory.push(`${window.location.pathname}?${searchParams}`);
  219. clientState &&
  220. setClientState({
  221. ...clientState,
  222. state: 'projects_selected',
  223. url: `setup-docs/?${searchParams}`,
  224. });
  225. };
  226. const selectProject = (newProjectId: string) => {
  227. const matchedProject = projects.find(p => p.id === newProjectId);
  228. trackAdvancedAnalyticsEvent('growth.onboarding_clicked_project_in_sidebar', {
  229. organization,
  230. platform: matchedProject?.platform || 'unknown',
  231. });
  232. setNewProject(newProjectId);
  233. };
  234. return (
  235. <Fragment>
  236. <Wrapper>
  237. {!singleSelectPlatform && (
  238. <SidebarWrapper>
  239. <ProjectSidebarSection
  240. projects={projects}
  241. selectedPlatformToProjectIdMap={Object.fromEntries(
  242. selectedPlatforms.map(platform => [
  243. platform,
  244. platformToProjectIdMap[platform],
  245. ])
  246. )}
  247. activeProject={project}
  248. {...{checkProjectHasFirstEvent, selectProject}}
  249. />
  250. </SidebarWrapper>
  251. )}
  252. <MainContent>
  253. {integrationSlug && !integrationUseManualSetup ? (
  254. <IntegrationSetup
  255. integrationSlug={integrationSlug}
  256. project={project}
  257. onClickManualSetup={() => {
  258. setIntegrationUseManualSetup(true);
  259. }}
  260. />
  261. ) : (
  262. <ProjectDocs
  263. platform={loadedPlatform}
  264. project={project}
  265. hasError={hasError}
  266. platformDocs={platformDocs}
  267. onRetry={fetchData}
  268. />
  269. )}
  270. </MainContent>
  271. </Wrapper>
  272. {project &&
  273. (heartbeatFooter ? (
  274. <HeartbeatFooter
  275. projectSlug={project.slug}
  276. route={route}
  277. router={router}
  278. location={location}
  279. newOrg
  280. />
  281. ) : (
  282. <FirstEventFooter
  283. project={project}
  284. organization={organization}
  285. isLast={!nextProject}
  286. hasFirstEvent={checkProjectHasFirstEvent(project)}
  287. onClickSetupLater={() => {
  288. const orgIssuesURL = `/organizations/${organization.slug}/issues/?project=${project.id}&referrer=onboarding-setup-docs`;
  289. trackAdvancedAnalyticsEvent(
  290. 'growth.onboarding_clicked_setup_platform_later',
  291. {
  292. organization,
  293. platform: currentPlatform,
  294. project_index: projectIndex,
  295. }
  296. );
  297. if (!project.platform || !clientState) {
  298. browserHistory.push(orgIssuesURL);
  299. return;
  300. }
  301. // if we have a next project, switch to that
  302. if (nextProject) {
  303. setNewProject(nextProject.id);
  304. } else {
  305. setClientState({
  306. ...clientState,
  307. state: 'finished',
  308. });
  309. browserHistory.push(orgIssuesURL);
  310. }
  311. }}
  312. handleFirstIssueReceived={() => {
  313. const newHasFirstEventMap = {...hasFirstEventMap, [project.id]: true};
  314. setHasFirstEventMap(newHasFirstEventMap);
  315. }}
  316. />
  317. ))}
  318. </Fragment>
  319. );
  320. }
  321. export default withProjects(SetupDocs);
  322. type AlertType = React.ComponentProps<typeof Alert>['type'];
  323. const getAlertSelector = (type: AlertType) =>
  324. type === 'muted' ? null : `.alert[level="${type}"], .alert-${type}`;
  325. const mapAlertStyles = (p: {theme: Theme}, type: AlertType) =>
  326. css`
  327. ${getAlertSelector(type)} {
  328. ${alertStyles({theme: p.theme, type})};
  329. display: block;
  330. }
  331. `;
  332. const AnimatedContentWrapper = styled(motion.div)`
  333. overflow: hidden;
  334. `;
  335. AnimatedContentWrapper.defaultProps = {
  336. initial: {
  337. height: 0,
  338. },
  339. animate: {
  340. height: 'auto',
  341. },
  342. exit: {
  343. height: 0,
  344. },
  345. };
  346. const Content = styled(motion.div)`
  347. h1,
  348. h2,
  349. h3,
  350. h4,
  351. h5,
  352. h6,
  353. p {
  354. margin-bottom: 18px;
  355. }
  356. div[data-language] {
  357. margin-bottom: ${space(2)};
  358. }
  359. code {
  360. color: ${p => p.theme.pink400};
  361. }
  362. h2 {
  363. font-size: 1.4em;
  364. }
  365. .alert h5 {
  366. font-size: 1em;
  367. margin-bottom: 0.625rem;
  368. }
  369. /**
  370. * XXX(epurkhiser): This comes from the doc styles and avoids bottom margin issues in alerts
  371. */
  372. .content-flush-bottom *:last-child {
  373. margin-bottom: 0;
  374. }
  375. ${p => Object.keys(p.theme.alert).map(type => mapAlertStyles(p, type as AlertType))}
  376. `;
  377. const DocsWrapper = styled(motion.div)``;
  378. DocsWrapper.defaultProps = {
  379. initial: {opacity: 0, y: 40},
  380. animate: {opacity: 1, y: 0},
  381. exit: {opacity: 0},
  382. };
  383. const Wrapper = styled('div')`
  384. display: flex;
  385. flex-direction: row;
  386. margin: ${space(2)};
  387. justify-content: center;
  388. `;
  389. const MainContent = styled('div')`
  390. max-width: 850px;
  391. min-width: 0;
  392. flex-grow: 1;
  393. `;
  394. // the number icon will be space(2) + 30px to the left of the margin of center column
  395. // so we need to offset the right margin by that much
  396. // also hide the sidebar if the screen is too small
  397. const SidebarWrapper = styled('div')`
  398. margin: ${space(1)} calc(${space(2)} + 30px + ${space(4)}) 0 ${space(2)};
  399. @media (max-width: 1150px) {
  400. display: none;
  401. }
  402. flex-basis: 240px;
  403. flex-grow: 0;
  404. flex-shrink: 0;
  405. min-width: 240px;
  406. `;