setupDocs.tsx 13 KB

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