createProject.tsx 11 KB

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