setupDocs.tsx 12 KB

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