setupDocs.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  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 FirstEventFooter from './components/firstEventFooter';
  23. import FullIntroduction from './components/fullIntroduction';
  24. import {HeartbeatFooter} from './components/heartbeatFooter';
  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 ProjecDocs(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 api = useApi();
  109. const [clientState, setClientState] = usePersistedOnboardingState();
  110. const selectedPlatforms = clientState?.selectedPlatforms || [];
  111. const platformToProjectIdMap = clientState?.platformToProjectIdMap || {};
  112. // id is really slug here
  113. const projectSlugs = selectedPlatforms
  114. .map(platform => platformToProjectIdMap[platform])
  115. .filter((slug): slug is string => slug !== undefined);
  116. const selectedProjectsSet = new Set(projectSlugs);
  117. // get projects in the order they appear in selectedPlatforms
  118. const projects = projectSlugs
  119. .map(slug => rawProjects.find(project => project.slug === slug))
  120. .filter((project): project is Project => project !== undefined);
  121. // SDK instrumentation
  122. const [hasError, setHasError] = useState(false);
  123. const [platformDocs, setPlatformDocs] = useState<PlatformDoc | null>(null);
  124. const [loadedPlatform, setLoadedPlatform] = useState<PlatformKey | null>(null);
  125. // store what projects have sent first event in state based project.firstEvent
  126. const [hasFirstEventMap, setHasFirstEventMap] = useState<Record<string, boolean>>(
  127. projects.reduce((accum, project: Project) => {
  128. accum[project.id] = !!project.firstEvent;
  129. return accum;
  130. }, {} as Record<string, boolean>)
  131. );
  132. const checkProjectHasFirstEvent = (project: Project) => {
  133. return !!hasFirstEventMap[project.id];
  134. };
  135. const {project_id: rawProjectId} = qs.parse(search);
  136. const rawProjectIndex = projects.findIndex(p => p.id === rawProjectId);
  137. const firstProjectNoError = projects.findIndex(
  138. p => selectedProjectsSet.has(p.slug) && !checkProjectHasFirstEvent(p)
  139. );
  140. // Select a project based on search params. If non exist, use the first project without first event.
  141. const projectIndex = rawProjectIndex >= 0 ? rawProjectIndex : firstProjectNoError;
  142. const project = projects[projectIndex];
  143. // find the next project that doesn't have a first event
  144. const nextProject = projects.find(
  145. (p, i) => i > projectIndex && !checkProjectHasFirstEvent(p)
  146. );
  147. const integrationSlug = project?.platform && platformToIntegrationMap[project.platform];
  148. const [integrationUseManualSetup, setIntegrationUseManualSetup] = useState(false);
  149. useEffect(() => {
  150. // should not redirect if we don't have an active client state or projects aren't loaded
  151. if (!clientState || loadingProjects) {
  152. return;
  153. }
  154. if (
  155. // If no projects remaining, then we can leave
  156. !project
  157. ) {
  158. // marke onboarding as complete
  159. setClientState({
  160. ...clientState,
  161. state: 'finished',
  162. });
  163. browserHistory.push(
  164. normalizeUrl(
  165. `/organizations/${organization.slug}/issues/?referrer=onboarding-setup-docs-on-complete`
  166. )
  167. );
  168. }
  169. });
  170. const currentPlatform = loadedPlatform ?? project?.platform ?? 'other';
  171. const fetchData = useCallback(async () => {
  172. // TODO: add better error handling logic
  173. if (!project?.platform) {
  174. return;
  175. }
  176. if (integrationSlug && !integrationUseManualSetup) {
  177. setLoadedPlatform(project.platform);
  178. setPlatformDocs(null);
  179. setHasError(false);
  180. return;
  181. }
  182. try {
  183. const loadedDocs = await loadDocs(
  184. api,
  185. organization.slug,
  186. project.slug,
  187. project.platform
  188. );
  189. setPlatformDocs(loadedDocs);
  190. setLoadedPlatform(project.platform);
  191. setHasError(false);
  192. } catch (error) {
  193. setHasError(error);
  194. throw error;
  195. }
  196. }, [project, api, organization, integrationSlug, integrationUseManualSetup]);
  197. useEffect(() => {
  198. fetchData();
  199. }, [fetchData]);
  200. if (!project) {
  201. return null;
  202. }
  203. const setNewProject = (newProjectId: string) => {
  204. setLoadedPlatform(null);
  205. setPlatformDocs(null);
  206. setHasError(false);
  207. setIntegrationUseManualSetup(false);
  208. const searchParams = new URLSearchParams({
  209. sub_step: 'project',
  210. project_id: newProjectId,
  211. });
  212. browserHistory.push(`${window.location.pathname}?${searchParams}`);
  213. clientState &&
  214. setClientState({
  215. ...clientState,
  216. state: 'projects_selected',
  217. url: `setup-docs/?${searchParams}`,
  218. });
  219. };
  220. const selectProject = (newProjectId: string) => {
  221. const matchedProject = projects.find(p => p.id === newProjectId);
  222. trackAdvancedAnalyticsEvent('growth.onboarding_clicked_project_in_sidebar', {
  223. organization,
  224. platform: matchedProject?.platform || 'unknown',
  225. });
  226. setNewProject(newProjectId);
  227. };
  228. return (
  229. <Fragment>
  230. <Wrapper>
  231. <SidebarWrapper
  232. hasHeartbeatFooter={
  233. !!organization?.features.includes('onboarding-heartbeat-footer')
  234. }
  235. >
  236. <ProjectSidebarSection
  237. projects={projects}
  238. selectedPlatformToProjectIdMap={Object.fromEntries(
  239. selectedPlatforms.map(platform => [
  240. platform,
  241. platformToProjectIdMap[platform],
  242. ])
  243. )}
  244. activeProject={project}
  245. {...{checkProjectHasFirstEvent, selectProject}}
  246. hasHeartbeatFooter={
  247. !!organization?.features.includes('onboarding-heartbeat-footer')
  248. }
  249. />
  250. </SidebarWrapper>
  251. <MainContent>
  252. {integrationSlug && !integrationUseManualSetup ? (
  253. <IntegrationSetup
  254. integrationSlug={integrationSlug}
  255. project={project}
  256. onClickManualSetup={() => {
  257. setIntegrationUseManualSetup(true);
  258. }}
  259. />
  260. ) : (
  261. <ProjecDocs
  262. platform={loadedPlatform}
  263. project={project}
  264. hasError={hasError}
  265. platformDocs={platformDocs}
  266. onRetry={fetchData}
  267. />
  268. )}
  269. </MainContent>
  270. </Wrapper>
  271. {project &&
  272. (organization.features?.includes('onboarding-heartbeat-footer') ? (
  273. <HeartbeatFooter
  274. projectSlug={project.slug}
  275. nextProjectSlug={nextProject?.slug}
  276. route={route}
  277. router={router}
  278. location={location}
  279. onSetupNextProject={() => {
  280. const orgIssuesURL = `/organizations/${organization.slug}/issues/?project=${project.id}&referrer=onboarding-setup-docs`;
  281. trackAdvancedAnalyticsEvent(
  282. 'growth.onboarding_clicked_setup_platform_later',
  283. {
  284. organization,
  285. platform: currentPlatform,
  286. project_index: projectIndex,
  287. }
  288. );
  289. if (!project.platform || !clientState) {
  290. browserHistory.push(orgIssuesURL);
  291. return;
  292. }
  293. // if we have a next project, switch to that
  294. if (nextProject) {
  295. setNewProject(nextProject.id);
  296. } else {
  297. setClientState({
  298. ...clientState,
  299. state: 'finished',
  300. });
  301. browserHistory.push(orgIssuesURL);
  302. }
  303. }}
  304. newOrg
  305. />
  306. ) : (
  307. <FirstEventFooter
  308. project={project}
  309. organization={organization}
  310. isLast={!nextProject}
  311. hasFirstEvent={checkProjectHasFirstEvent(project)}
  312. onClickSetupLater={() => {
  313. const orgIssuesURL = `/organizations/${organization.slug}/issues/?project=${project.id}&referrer=onboarding-setup-docs`;
  314. trackAdvancedAnalyticsEvent(
  315. 'growth.onboarding_clicked_setup_platform_later',
  316. {
  317. organization,
  318. platform: currentPlatform,
  319. project_index: projectIndex,
  320. }
  321. );
  322. if (!project.platform || !clientState) {
  323. browserHistory.push(orgIssuesURL);
  324. return;
  325. }
  326. // if we have a next project, switch to that
  327. if (nextProject) {
  328. setNewProject(nextProject.id);
  329. } else {
  330. setClientState({
  331. ...clientState,
  332. state: 'finished',
  333. });
  334. browserHistory.push(orgIssuesURL);
  335. }
  336. }}
  337. handleFirstIssueReceived={() => {
  338. const newHasFirstEventMap = {...hasFirstEventMap, [project.id]: true};
  339. setHasFirstEventMap(newHasFirstEventMap);
  340. }}
  341. />
  342. ))}
  343. </Fragment>
  344. );
  345. }
  346. export default withProjects(SetupDocs);
  347. type AlertType = React.ComponentProps<typeof Alert>['type'];
  348. const getAlertSelector = (type: AlertType) =>
  349. type === 'muted' ? null : `.alert[level="${type}"], .alert-${type}`;
  350. const mapAlertStyles = (p: {theme: Theme}, type: AlertType) =>
  351. css`
  352. ${getAlertSelector(type)} {
  353. ${alertStyles({theme: p.theme, type})};
  354. display: block;
  355. }
  356. `;
  357. const AnimatedContentWrapper = styled(motion.div)`
  358. overflow: hidden;
  359. `;
  360. AnimatedContentWrapper.defaultProps = {
  361. initial: {
  362. height: 0,
  363. },
  364. animate: {
  365. height: 'auto',
  366. },
  367. exit: {
  368. height: 0,
  369. },
  370. };
  371. const Content = styled(motion.div)`
  372. h1,
  373. h2,
  374. h3,
  375. h4,
  376. h5,
  377. h6,
  378. p {
  379. margin-bottom: 18px;
  380. }
  381. div[data-language] {
  382. margin-bottom: ${space(2)};
  383. }
  384. code {
  385. color: ${p => p.theme.pink400};
  386. }
  387. h2 {
  388. font-size: 1.4em;
  389. }
  390. .alert h5 {
  391. font-size: 1em;
  392. margin-bottom: 0.625rem;
  393. }
  394. /**
  395. * XXX(epurkhiser): This comes from the doc styles and avoids bottom margin issues in alerts
  396. */
  397. .content-flush-bottom *:last-child {
  398. margin-bottom: 0;
  399. }
  400. ${p => Object.keys(p.theme.alert).map(type => mapAlertStyles(p, type as AlertType))}
  401. `;
  402. const DocsWrapper = styled(motion.div)``;
  403. DocsWrapper.defaultProps = {
  404. initial: {opacity: 0, y: 40},
  405. animate: {opacity: 1, y: 0},
  406. exit: {opacity: 0},
  407. };
  408. const Wrapper = styled('div')`
  409. display: flex;
  410. flex-direction: row;
  411. margin: ${space(2)};
  412. justify-content: center;
  413. `;
  414. const MainContent = styled('div')`
  415. max-width: 850px;
  416. min-width: 0;
  417. flex-grow: 1;
  418. `;
  419. // the number icon will be space(2) + 30px to the left of the margin of center column
  420. // so we need to offset the right margin by that much
  421. // also hide the sidebar if the screen is too small
  422. const SidebarWrapper = styled('div')<{hasHeartbeatFooter: boolean}>`
  423. margin: ${space(1)} calc(${space(2)} + 30px + ${space(4)}) 0 ${space(2)};
  424. @media (max-width: 1150px) {
  425. display: none;
  426. }
  427. flex-basis: ${p => (p.hasHeartbeatFooter ? '256px' : '240px')};
  428. flex-grow: 0;
  429. flex-shrink: 0;
  430. min-width: 240px;
  431. `;