setupDocs.tsx 11 KB

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