setupDocs.tsx 13 KB

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