setupDocs.tsx 14 KB

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