createProject.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. import {Fragment, useCallback, useState} from 'react';
  2. import {browserHistory} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import * as Sentry from '@sentry/react';
  5. import omit from 'lodash/omit';
  6. import {PlatformIcon} from 'platformicons';
  7. import {openCreateTeamModal, openModal} from 'sentry/actionCreators/modal';
  8. import {Alert} from 'sentry/components/alert';
  9. import {Button} from 'sentry/components/button';
  10. import Input from 'sentry/components/input';
  11. import * as Layout from 'sentry/components/layouts/thirds';
  12. import ExternalLink from 'sentry/components/links/externalLink';
  13. import {SUPPORTED_LANGUAGES} from 'sentry/components/onboarding/frameworkSuggestionModal';
  14. import PlatformPicker, {Platform} from 'sentry/components/platformPicker';
  15. import {useProjectCreationAccess} from 'sentry/components/projects/useProjectCreationAccess';
  16. import TeamSelector from 'sentry/components/teamSelector';
  17. import {IconAdd} from 'sentry/icons';
  18. import {t, tct} from 'sentry/locale';
  19. import ProjectsStore from 'sentry/stores/projectsStore';
  20. import {space} from 'sentry/styles/space';
  21. import {OnboardingSelectedSDK, Team} from 'sentry/types';
  22. import {trackAnalytics} from 'sentry/utils/analytics';
  23. import useRouteAnalyticsEventNames from 'sentry/utils/routeAnalytics/useRouteAnalyticsEventNames';
  24. import slugify from 'sentry/utils/slugify';
  25. import useApi from 'sentry/utils/useApi';
  26. import useOrganization from 'sentry/utils/useOrganization';
  27. import {useTeams} from 'sentry/utils/useTeams';
  28. import {normalizeUrl} from 'sentry/utils/withDomainRequired';
  29. import IssueAlertOptions from 'sentry/views/projectInstall/issueAlertOptions';
  30. type IssueAlertFragment = Parameters<
  31. React.ComponentProps<typeof IssueAlertOptions>['onChange']
  32. >[0];
  33. function CreateProject() {
  34. const api = useApi();
  35. const organization = useOrganization();
  36. const accessTeams = useTeams().teams.filter((team: Team) => team.hasAccess);
  37. useRouteAnalyticsEventNames(
  38. 'project_creation_page.viewed',
  39. 'Project Create: Creation page viewed'
  40. );
  41. const [projectName, setProjectName] = useState('');
  42. const [platform, setPlatform] = useState<OnboardingSelectedSDK | undefined>(undefined);
  43. const [team, setTeam] = useState(accessTeams?.[0]?.slug);
  44. const [error, setError] = useState(false);
  45. const [inFlight, setInFlight] = useState(false);
  46. const [alertRuleConfig, setAlertRuleConfig] = useState<IssueAlertFragment | undefined>(
  47. undefined
  48. );
  49. const frameworkSelectionEnabled = !!organization?.features.includes(
  50. 'onboarding-sdk-selection'
  51. );
  52. const createProject = useCallback(
  53. async (selectedFramework?: OnboardingSelectedSDK) => {
  54. const {slug} = organization;
  55. const {
  56. shouldCreateCustomRule,
  57. name,
  58. conditions,
  59. actions,
  60. actionMatch,
  61. frequency,
  62. defaultRules,
  63. } = alertRuleConfig || {};
  64. const selectedPlatform = selectedFramework?.key ?? platform?.key;
  65. if (!selectedPlatform) {
  66. return;
  67. }
  68. setInFlight(true);
  69. try {
  70. const projectData = await api.requestPromise(`/teams/${slug}/${team}/projects/`, {
  71. method: 'POST',
  72. data: {
  73. name: projectName,
  74. platform: selectedPlatform,
  75. default_rules: defaultRules ?? true,
  76. },
  77. });
  78. let ruleId: string | undefined;
  79. if (shouldCreateCustomRule) {
  80. const ruleData = await api.requestPromise(
  81. `/projects/${organization.slug}/${projectData.slug}/rules/`,
  82. {
  83. method: 'POST',
  84. data: {
  85. name,
  86. conditions,
  87. actions,
  88. actionMatch,
  89. frequency,
  90. },
  91. }
  92. );
  93. ruleId = ruleData.id;
  94. }
  95. trackAnalytics('project_creation_page.created', {
  96. organization,
  97. issue_alert: defaultRules
  98. ? 'Default'
  99. : shouldCreateCustomRule
  100. ? 'Custom'
  101. : 'No Rule',
  102. project_id: projectData.id,
  103. rule_id: ruleId || '',
  104. });
  105. ProjectsStore.onCreateSuccess(projectData, organization.slug);
  106. browserHistory.push(
  107. normalizeUrl(
  108. `/${organization.slug}/${projectData.slug}/getting-started/${selectedPlatform}/`
  109. )
  110. );
  111. } catch (err) {
  112. setInFlight(false);
  113. setError(err.responseJSON.detail);
  114. // Only log this if the error is something other than:
  115. // * The user not having access to create a project, or,
  116. // * A project with that slug already exists
  117. if (err.status !== 403 && err.status !== 409) {
  118. Sentry.withScope(scope => {
  119. scope.setExtra('err', err);
  120. Sentry.captureMessage('Project creation failed');
  121. });
  122. }
  123. }
  124. },
  125. [api, alertRuleConfig, organization, platform, projectName, team]
  126. );
  127. const handleProjectCreation = useCallback(async () => {
  128. const selectedPlatform = platform;
  129. if (!selectedPlatform) {
  130. return;
  131. }
  132. if (
  133. selectedPlatform.type !== 'language' ||
  134. !Object.values(SUPPORTED_LANGUAGES).includes(
  135. selectedPlatform.language as SUPPORTED_LANGUAGES
  136. )
  137. ) {
  138. createProject();
  139. return;
  140. }
  141. const {FrameworkSuggestionModal, modalCss} = await import(
  142. 'sentry/components/onboarding/frameworkSuggestionModal'
  143. );
  144. openModal(
  145. deps => (
  146. <FrameworkSuggestionModal
  147. {...deps}
  148. organization={organization}
  149. selectedPlatform={selectedPlatform}
  150. onConfigure={selectedFramework => {
  151. createProject(selectedFramework);
  152. }}
  153. onSkip={createProject}
  154. />
  155. ),
  156. {
  157. modalCss,
  158. onClose: () => {
  159. trackAnalytics('project_creation.select_framework_modal_close_button_clicked', {
  160. platform: selectedPlatform.key,
  161. organization,
  162. });
  163. },
  164. }
  165. );
  166. }, [platform, createProject, organization]);
  167. function handlePlatformChange(selectedPlatform: Platform | null) {
  168. if (!selectedPlatform?.id) {
  169. setPlatform(undefined);
  170. setProjectName('');
  171. return;
  172. }
  173. const userModifiedName = !!projectName && projectName !== platform?.key;
  174. const newName = userModifiedName ? projectName : selectedPlatform.id;
  175. setPlatform({
  176. ...omit(selectedPlatform, 'id'),
  177. key: selectedPlatform.id,
  178. });
  179. setProjectName(newName);
  180. }
  181. const {shouldCreateCustomRule, conditions} = alertRuleConfig || {};
  182. const {canCreateProject} = useProjectCreationAccess(organization);
  183. const canSubmitForm =
  184. !inFlight &&
  185. team &&
  186. canCreateProject &&
  187. projectName !== '' &&
  188. (!shouldCreateCustomRule || conditions?.every?.(condition => condition.value));
  189. const createProjectForm = (
  190. <Fragment>
  191. <Layout.Title withMargins>
  192. {t('3. Name your project and assign it a team')}
  193. </Layout.Title>
  194. <CreateProjectForm
  195. onSubmit={(event: React.FormEvent<HTMLFormElement>) => {
  196. // Prevent the page from reloading
  197. event.preventDefault();
  198. frameworkSelectionEnabled ? handleProjectCreation() : createProject();
  199. }}
  200. >
  201. <div>
  202. <FormLabel>{t('Project name')}</FormLabel>
  203. <ProjectNameInputWrap>
  204. <StyledPlatformIcon platform={platform?.key ?? 'other'} size={20} />
  205. <ProjectNameInput
  206. type="text"
  207. name="name"
  208. placeholder={t('project-name')}
  209. autoComplete="off"
  210. value={projectName}
  211. onChange={e => setProjectName(slugify(e.target.value))}
  212. />
  213. </ProjectNameInputWrap>
  214. </div>
  215. <div>
  216. <FormLabel>{t('Team')}</FormLabel>
  217. <TeamSelectInput>
  218. <TeamSelector
  219. name="select-team"
  220. aria-label={t('Select a Team')}
  221. menuPlacement="auto"
  222. clearable={false}
  223. value={team}
  224. placeholder={t('Select a Team')}
  225. onChange={choice => setTeam(choice.value)}
  226. teamFilter={(filterTeam: Team) => filterTeam.hasAccess}
  227. />
  228. <Button
  229. borderless
  230. data-test-id="create-team"
  231. icon={<IconAdd isCircled />}
  232. onClick={() =>
  233. openCreateTeamModal({
  234. organization,
  235. onClose: ({slug}) => setTeam(slug),
  236. })
  237. }
  238. title={t('Create a team')}
  239. aria-label={t('Create a team')}
  240. />
  241. </TeamSelectInput>
  242. </div>
  243. <div>
  244. <Button
  245. type="submit"
  246. data-test-id="create-project"
  247. priority="primary"
  248. disabled={!canSubmitForm}
  249. >
  250. {t('Create Project')}
  251. </Button>
  252. </div>
  253. </CreateProjectForm>
  254. </Fragment>
  255. );
  256. return (
  257. <Fragment>
  258. {error && <Alert type="error">{error}</Alert>}
  259. <div data-test-id="onboarding-info">
  260. <Layout.Title withMargins>{t('Create a new project in 3 steps')}</Layout.Title>
  261. <HelpText>
  262. {tct(
  263. 'Set up a separate project for each part of your application (for example, your API server and frontend client), to quickly pinpoint which part of your application errors are coming from. [link: Read the docs].',
  264. {
  265. link: (
  266. <ExternalLink href="https://docs.sentry.io/product/sentry-basics/integrate-frontend/create-new-project/" />
  267. ),
  268. }
  269. )}
  270. </HelpText>
  271. <Layout.Title withMargins>{t('1. Choose your platform')}</Layout.Title>
  272. <PlatformPicker
  273. platform={platform?.key}
  274. defaultCategory={platform?.category}
  275. setPlatform={handlePlatformChange}
  276. organization={organization}
  277. showOther
  278. />
  279. <IssueAlertOptions onChange={updatedData => setAlertRuleConfig(updatedData)} />
  280. {createProjectForm}
  281. </div>
  282. </Fragment>
  283. );
  284. }
  285. export {CreateProject};
  286. const CreateProjectForm = styled('form')`
  287. display: grid;
  288. grid-template-columns: 300px minmax(250px, max-content) max-content;
  289. gap: ${space(2)};
  290. align-items: end;
  291. padding: ${space(3)} 0;
  292. box-shadow: 0 -1px 0 rgba(0, 0, 0, 0.1);
  293. background: ${p => p.theme.background};
  294. `;
  295. const FormLabel = styled('div')`
  296. font-size: ${p => p.theme.fontSizeExtraLarge};
  297. margin-bottom: ${space(1)};
  298. `;
  299. const ProjectNameInputWrap = styled('div')`
  300. position: relative;
  301. `;
  302. const ProjectNameInput = styled(Input)`
  303. padding-left: calc(${p => p.theme.formPadding.md.paddingLeft}px * 1.5 + 20px);
  304. `;
  305. const StyledPlatformIcon = styled(PlatformIcon)`
  306. position: absolute;
  307. top: 50%;
  308. left: ${p => p.theme.formPadding.md.paddingLeft}px;
  309. transform: translateY(-50%);
  310. `;
  311. const TeamSelectInput = styled('div')`
  312. display: grid;
  313. gap: ${space(1)};
  314. grid-template-columns: 1fr min-content;
  315. align-items: center;
  316. `;
  317. const HelpText = styled('p')`
  318. color: ${p => p.theme.subText};
  319. max-width: 760px;
  320. `;