3 * Copyright (C) 2009-2019 SonarSource SA
4 * mailto:info AT sonarsource DOT com
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 3 of the License, or (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public License
17 * along with this program; if not, write to the Free Software Foundation,
18 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 import * as React from 'react';
22 deleteProjectAlmBinding,
26 } from '../../../../api/almSettings';
27 import throwGlobalError from '../../../../app/utils/throwGlobalError';
28 import PRDecorationBindingRenderer from './PRDecorationBindingRenderer';
31 component: T.Component;
35 formData: T.GithubBinding;
37 instances: T.AlmSettingsInstance[];
44 export default class PRDecorationBinding extends React.PureComponent<Props, State> {
61 this.fetchDefinitions();
64 componentWillUnmount() {
68 fetchDefinitions = () => {
69 const project = this.props.component.key;
70 return Promise.all([getAlmSettings(project), this.getProjectBinding(project)])
71 .then(([instances, data]) => {
73 this.setState(({ formData }) => ({
74 formData: data || formData,
75 hasBinding: Boolean(data),
77 isValid: this.validateForm(),
81 if (!data && instances.length === 1) {
82 this.handleFieldChange('key', instances[0].key);
88 this.setState({ loading: false });
93 getProjectBinding(project: string) {
94 return getProjectAlmBinding(project).catch((response: Response) => {
95 if (response && response.status === 404) {
96 return Promise.resolve(undefined);
98 return throwGlobalError(response);
104 this.setState({ saving: false });
108 handleReset = () => {
109 const { component } = this.props;
110 this.setState({ saving: true });
111 deleteProjectAlmBinding(component.key)
125 .catch(this.catchError);
128 handleSubmit = () => {
129 this.setState({ saving: true });
131 formData: { key, repository }
134 if (key && repository) {
135 setProjectAlmBinding({
137 project: this.props.component.key,
149 .catch(this.catchError);
153 handleFieldChange = (id: keyof T.GithubBinding, value: string) => {
154 this.setState(({ formData: formdata }) => ({
159 isValid: this.validateForm(),
164 validateForm = () => {
165 const { formData } = this.state;
166 return Object.values(formData).reduce(
167 (result: boolean, value) => result && Boolean(value),
174 <PRDecorationBindingRenderer
175 onFieldChange={this.handleFieldChange}
176 onReset={this.handleReset}
177 onSubmit={this.handleSubmit}