createProject.tsx 11 KB

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