createProject.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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 trackAdvancedAnalyticsEvent from 'sentry/utils/analytics/trackAdvancedAnalyticsEvent';
  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. trackAdvancedAnalyticsEvent('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. const nextUrl = `/${organization.slug}/${projectData.slug}/getting-started/${platformKey}/`;
  218. browserHistory.push(normalizeUrl(nextUrl));
  219. } catch (err) {
  220. this.setState({
  221. inFlight: false,
  222. error: err.responseJSON.detail,
  223. });
  224. // Only log this if the error is something other than:
  225. // * The user not having access to create a project, or,
  226. // * A project with that slug already exists
  227. if (err.status !== 403 && err.status !== 409) {
  228. Sentry.withScope(scope => {
  229. scope.setExtra('err', err);
  230. scope.setExtra('props', this.props);
  231. scope.setExtra('state', this.state);
  232. Sentry.captureMessage('Project creation failed');
  233. });
  234. }
  235. }
  236. };
  237. setPlatform = (platformKey: PlatformName | null) => {
  238. if (!platformKey) {
  239. this.setState({platform: null, projectName: ''});
  240. return;
  241. }
  242. this.setState(({projectName, platform}) => {
  243. // Avoid replacing project name when the user already modified it
  244. const userModifiedName = projectName && projectName !== platform;
  245. const newName = userModifiedName ? projectName : platformKey;
  246. return {
  247. platform: platformKey,
  248. projectName: slugify(newName),
  249. };
  250. });
  251. };
  252. render() {
  253. const {platform, error} = this.state;
  254. return (
  255. <Fragment>
  256. {error && <Alert type="error">{error}</Alert>}
  257. <div data-test-id="onboarding-info">
  258. <Layout.Title withMargins>{t('Create a new project in 3 steps')}</Layout.Title>
  259. <HelpText>
  260. {tct(
  261. '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].',
  262. {
  263. link: (
  264. <ExternalLink href="https://docs.sentry.io/product/sentry-basics/integrate-frontend/create-new-project/" />
  265. ),
  266. }
  267. )}
  268. </HelpText>
  269. <Layout.Title withMargins>{t('1. Choose your platform')}</Layout.Title>
  270. <PlatformPicker
  271. platform={platform}
  272. defaultCategory={this.defaultCategory}
  273. setPlatform={this.setPlatform}
  274. organization={this.props.organization}
  275. showOther
  276. />
  277. <IssueAlertOptions
  278. onChange={updatedData => {
  279. this.setState({dataFragment: updatedData});
  280. }}
  281. />
  282. {this.renderProjectForm()}
  283. </div>
  284. </Fragment>
  285. );
  286. }
  287. }
  288. // TODO(davidenwang): change to functional component and replace withTeams with useTeams
  289. export default withRouteAnalytics(
  290. withApi(withSentryRouter(withOrganization(withTeams(CreateProject))))
  291. );
  292. export {CreateProject};
  293. const CreateProjectForm = styled('form')`
  294. display: grid;
  295. grid-template-columns: 300px minmax(250px, max-content) max-content;
  296. gap: ${space(2)};
  297. align-items: end;
  298. padding: ${space(3)} 0;
  299. box-shadow: 0 -1px 0 rgba(0, 0, 0, 0.1);
  300. background: ${p => p.theme.background};
  301. `;
  302. const FormLabel = styled('div')`
  303. font-size: ${p => p.theme.fontSizeExtraLarge};
  304. margin-bottom: ${space(1)};
  305. `;
  306. const ProjectNameInputWrap = styled('div')`
  307. position: relative;
  308. `;
  309. const ProjectNameInput = styled(Input)`
  310. padding-left: calc(${p => p.theme.formPadding.md.paddingLeft}px * 1.5 + 20px);
  311. `;
  312. const StyledPlatformIcon = styled(PlatformIcon)`
  313. position: absolute;
  314. top: 50%;
  315. left: ${p => p.theme.formPadding.md.paddingLeft}px;
  316. transform: translateY(-50%);
  317. `;
  318. const TeamSelectInput = styled('div')`
  319. display: grid;
  320. gap: ${space(1)};
  321. grid-template-columns: 1fr min-content;
  322. align-items: center;
  323. `;
  324. const HelpText = styled('p')`
  325. color: ${p => p.theme.subText};
  326. max-width: 760px;
  327. `;