Endpoint.jsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. /*
  2. Copyright (C) 2017 Cloudbase Solutions SRL
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU Affero General Public License as
  5. published by the Free Software Foundation, either version 3 of the
  6. License, or (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU Affero General Public License for more details.
  11. You should have received a copy of the GNU Affero General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. */
  14. // @flow
  15. import React from 'react'
  16. import styled from 'styled-components'
  17. import { observer } from 'mobx-react'
  18. import { observe } from 'mobx'
  19. import EndpointLogos from '../../atoms/EndpointLogos'
  20. import StatusIcon from '../../atoms/StatusIcon'
  21. import CopyButton from '../../atoms/CopyButton'
  22. import StatusImage from '../../atoms/StatusImage'
  23. import Button from '../../atoms/Button'
  24. import LoadingButton from '../../molecules/LoadingButton'
  25. import type { Endpoint as EndpointType } from '../../../types/Endpoint'
  26. import type { Field } from '../../../types/Field'
  27. import notificationStore from '../../../stores/NotificationStore'
  28. import endpointStore, { passwordFields } from '../../../stores/EndpointStore'
  29. import providerStore from '../../../stores/ProviderStore'
  30. import ObjectUtils from '../../../utils/ObjectUtils'
  31. import Palette from '../../styleUtils/Palette'
  32. import DomUtils from '../../../utils/DomUtils'
  33. import { ContentPlugin } from '../../../plugins/endpoint'
  34. import DefaultContentPlugin from '../../../plugins/endpoint/default/ContentPlugin'
  35. import KeyboardManager from '../../../utils/KeyboardManager'
  36. const Wrapper = styled.div`
  37. padding: 48px 0 32px 0;
  38. display: flex;
  39. align-items: center;
  40. flex-direction: column;
  41. min-height: 0;
  42. `
  43. const Status = styled.div`
  44. display: flex;
  45. flex-direction: column;
  46. align-items: center;
  47. flex-shrink: 0;
  48. `
  49. const StatusHeader = styled.div`
  50. display: flex;
  51. align-items: center;
  52. `
  53. const StatusMessage = styled.div`
  54. margin-left: 8px;
  55. display: flex;
  56. align-items: center;
  57. line-height: 12px;
  58. `
  59. const ShowErrorButton = styled.span`
  60. font-size: 10px;
  61. color: ${Palette.primary};
  62. margin-left: 8px;
  63. cursor: pointer;
  64. `
  65. const StatusError = styled.div`
  66. max-width: 100%;
  67. margin: 16px 16px 0 16px;
  68. max-height: 140px;
  69. overflow: auto;
  70. cursor: pointer;
  71. &:hover > span {
  72. opacity: 1;
  73. }
  74. > span {
  75. background-position-y: 4px;
  76. margin-left: 4px;
  77. }
  78. `
  79. const Content = styled.div`
  80. width: 100%;
  81. display: flex;
  82. flex-direction: column;
  83. min-height: 0;
  84. `
  85. const LoadingWrapper = styled.div`
  86. display: flex;
  87. flex-direction: column;
  88. align-items: center;
  89. margin: 32px 0;
  90. `
  91. const LoadingText = styled.div`
  92. font-size: 18px;
  93. margin-top: 32px;
  94. `
  95. const Buttons = styled.div`
  96. display: flex;
  97. justify-content: space-between;
  98. margin-top: 32px;
  99. flex-shrink: 0;
  100. padding: 0 32px;
  101. `
  102. type Props = {
  103. type: ?string,
  104. cancelButtonText: string,
  105. deleteOnCancel: boolean,
  106. endpoint: ?EndpointType,
  107. onCancelClick: (opts?: { autoClose?: boolean }) => void,
  108. onResizeUpdate: (scrollableRef: HTMLElement, scrollOffset?: number) => void,
  109. }
  110. type State = {
  111. invalidFields: any[],
  112. validating: boolean,
  113. showErrorMessage: boolean,
  114. endpoint: ?EndpointType,
  115. isNew: ?boolean,
  116. }
  117. @observer
  118. class Endpoint extends React.Component<Props, State> {
  119. static defaultProps: $Shape<Props> = {
  120. cancelButtonText: 'Cancel',
  121. }
  122. state = {
  123. invalidFields: [],
  124. validating: false,
  125. showErrorMessage: false,
  126. endpoint: null,
  127. isNew: null,
  128. }
  129. scrollableRef: HTMLElement
  130. closeTimeout: TimeoutID
  131. contentPluginRef: DefaultContentPlugin
  132. isValidateButtonEnabled: boolean
  133. providerStoreObserver: () => void
  134. endpointValidationObserver: () => void
  135. componentWillMount() {
  136. this.componentWillReceiveProps(this.props)
  137. this.providerStoreObserver = observe(providerStore, 'connectionInfoSchema', () => {
  138. this.props.onResizeUpdate(this.scrollableRef)
  139. })
  140. this.endpointValidationObserver = observe(endpointStore, 'validation', () => {
  141. this.componentWillReceiveProps(this.props)
  142. })
  143. }
  144. componentDidMount() {
  145. providerStore.getConnectionInfoSchema(this.getEndpointType())
  146. KeyboardManager.onEnter('endpoint', () => {
  147. if (this.isValidateButtonEnabled) this.handleValidateClick()
  148. }, 2)
  149. }
  150. componentWillReceiveProps(props: Props) {
  151. if (this.state.validating) {
  152. if (endpointStore.validation && !endpointStore.validation.valid) {
  153. this.setState({ validating: false })
  154. }
  155. }
  156. if (props.endpoint && endpointStore.connectionInfo) {
  157. this.setState({
  158. endpoint: {
  159. ...ObjectUtils.flatten(props.endpoint || {}),
  160. ...ObjectUtils.flatten(endpointStore.connectionInfo || {}),
  161. },
  162. })
  163. } else {
  164. this.setState({
  165. isNew: this.state.isNew === null || this.state.isNew,
  166. endpoint: {
  167. type: props.type,
  168. ...ObjectUtils.flatten(this.state.endpoint || {}),
  169. },
  170. })
  171. }
  172. props.onResizeUpdate(this.scrollableRef)
  173. }
  174. componentWillUnmount() {
  175. endpointStore.clearValidation()
  176. providerStore.clearConnectionInfoSchema()
  177. clearTimeout(this.closeTimeout)
  178. KeyboardManager.removeKeyDown('endpoint')
  179. this.providerStoreObserver()
  180. this.endpointValidationObserver()
  181. }
  182. getEndpointType() {
  183. if (this.props.endpoint) {
  184. return this.props.endpoint.type
  185. }
  186. return this.props.type || ''
  187. }
  188. getFieldValue(field: ?Field) {
  189. if (!field || !this.state.endpoint) {
  190. return ''
  191. }
  192. if (this.state.endpoint[field.name] != null) {
  193. return this.state.endpoint[field.name]
  194. }
  195. if (Object.keys(field).find(k => k === 'default')) {
  196. return field.default
  197. }
  198. return ''
  199. }
  200. handleFieldsChange(items: { field: Field, value: any }[]) {
  201. let endpoint: any = { ...this.state.endpoint }
  202. items.forEach(item => {
  203. endpoint[item.field.name] = item.value
  204. })
  205. this.setState({ endpoint })
  206. }
  207. handleValidateClick() {
  208. if (!this.highlightRequired()) {
  209. this.setState({ validating: true })
  210. notificationStore.alert('Saving endpoint ...')
  211. endpointStore.clearValidation()
  212. if (this.state.isNew) {
  213. this.add()
  214. } else {
  215. this.update()
  216. }
  217. } else {
  218. notificationStore.alert('Please fill all the required fields', 'error')
  219. }
  220. }
  221. handleShowErrorMessageClick() {
  222. this.setState({ showErrorMessage: !this.state.showErrorMessage }, () => {
  223. this.props.onResizeUpdate(this.scrollableRef)
  224. })
  225. }
  226. handleCopyErrorMessageClick() {
  227. if (!endpointStore.validation) {
  228. return
  229. }
  230. let succesful = DomUtils.copyTextToClipboard(endpointStore.validation.message)
  231. if (succesful) {
  232. notificationStore.alert('The message has been copied to clipboard.')
  233. }
  234. }
  235. handleCancelClick() {
  236. if (this.props.deleteOnCancel && this.state.isNew === false) {
  237. endpointStore.delete(endpointStore.endpoints[0])
  238. }
  239. this.props.onCancelClick()
  240. }
  241. highlightRequired() {
  242. let invalidFields = this.contentPluginRef.findInvalidFields()
  243. this.setState({ invalidFields })
  244. return invalidFields.length > 0
  245. }
  246. update() {
  247. if (!this.state.endpoint) {
  248. return
  249. }
  250. endpointStore.update(this.state.endpoint).then(() => {
  251. let endpoint = endpointStore.endpoints.find(e => this.state.endpoint && e.id === this.state.endpoint.id)
  252. if (!endpoint) {
  253. throw new Error('endpoint not found')
  254. }
  255. this.setState({ endpoint: ObjectUtils.flatten(endpoint) })
  256. notificationStore.alert('Validating endpoint ...')
  257. endpointStore.validate(endpoint)
  258. })
  259. }
  260. add() {
  261. if (!this.state.endpoint) {
  262. return
  263. }
  264. endpointStore.add(this.state.endpoint).then(() => {
  265. let endpoint = endpointStore.endpoints[0]
  266. this.setState({ isNew: false, endpoint: ObjectUtils.flatten(endpoint) })
  267. notificationStore.alert('Validating endpoint ...')
  268. endpointStore.validate(endpoint)
  269. })
  270. }
  271. renderEndpointStatus() {
  272. const validation = endpointStore.validation
  273. if (!this.state.validating && !validation) {
  274. return null
  275. }
  276. let status = 'RUNNING'
  277. let message = 'Validating Endpoint ...'
  278. let error = null
  279. let showErrorButton = null
  280. if (validation) {
  281. if (validation.valid) {
  282. message = 'Endpoint is Valid'
  283. status = 'COMPLETED'
  284. } else {
  285. status = 'ERROR'
  286. message = 'Validation failed'
  287. if (validation.message) {
  288. showErrorButton = (
  289. <ShowErrorButton onClick={() => { this.handleShowErrorMessageClick() }}>
  290. {this.state.showErrorMessage ? 'Hide' : 'Show'} Error</ShowErrorButton>
  291. )
  292. error = this.state.showErrorMessage ?
  293. <StatusError onClick={() => { this.handleCopyErrorMessageClick() }}>{validation.message}<CopyButton /></StatusError> : null
  294. }
  295. }
  296. }
  297. return (
  298. <Status data-test-id="endpointStatus">
  299. <StatusHeader>
  300. <StatusIcon status={status} />
  301. <StatusMessage>{message}{showErrorButton}</StatusMessage>
  302. </StatusHeader>
  303. {error}
  304. </Status>
  305. )
  306. }
  307. renderButtons() {
  308. this.isValidateButtonEnabled = true
  309. let actionButton = <Button large onClick={() => this.handleValidateClick()}>Validate and save</Button>
  310. let message = 'Validating Endpoint ...'
  311. if (this.state.validating || (endpointStore.validation && endpointStore.validation.valid)) {
  312. if (endpointStore.validation && endpointStore.validation.valid) {
  313. message = 'Saving ...'
  314. }
  315. this.isValidateButtonEnabled = false
  316. actionButton = <LoadingButton large>{message}</LoadingButton>
  317. }
  318. return (
  319. <Buttons>
  320. <Button large secondary onClick={() => { this.handleCancelClick() }}>{this.props.cancelButtonText}</Button>
  321. {actionButton}
  322. </Buttons>
  323. )
  324. }
  325. renderContent() {
  326. const endpointType = this.getEndpointType()
  327. if (providerStore.connectionSchemaLoading || !endpointType) {
  328. return null
  329. }
  330. return (
  331. <Content>
  332. {/* Fix browsers autofilling password fields */}
  333. <div style={{ position: 'absolute', left: '-10000px' }}>
  334. <input name="username" type="text" />
  335. <input name="password" type="password" />
  336. </div>
  337. {this.renderEndpointStatus()}
  338. {React.createElement(ContentPlugin[endpointType] || ContentPlugin.default, {
  339. connectionInfoSchema: providerStore.connectionInfoSchema,
  340. // $FlowIgnore
  341. validation: endpointStore.validation,
  342. invalidFields: this.state.invalidFields,
  343. validating: this.state.validating,
  344. disabled: this.state.validating,
  345. cancelButtonText: this.props.cancelButtonText,
  346. passwordFields,
  347. getFieldValue: field => this.getFieldValue(field),
  348. highlightRequired: () => this.highlightRequired(),
  349. handleFieldChange: (field, value) => {
  350. if (field) this.handleFieldsChange([{ field, value }])
  351. },
  352. handleFieldsChange: fields => { this.handleFieldsChange(fields) },
  353. handleValidateClick: () => { this.handleValidateClick() },
  354. handleCancelClick: () => { this.handleCancelClick() },
  355. scrollableRef: ref => { this.scrollableRef = ref },
  356. onRef: ref => { this.contentPluginRef = ref },
  357. onResizeUpdate: (scrollOffset: number) => { this.props.onResizeUpdate(this.scrollableRef, scrollOffset) },
  358. })}
  359. {this.renderButtons()}
  360. </Content>
  361. )
  362. }
  363. renderLoading() {
  364. if (!providerStore.connectionSchemaLoading) {
  365. return null
  366. }
  367. return (
  368. <LoadingWrapper>
  369. <StatusImage loading />
  370. <LoadingText>Loading connection schema ...</LoadingText>
  371. </LoadingWrapper>
  372. )
  373. }
  374. render() {
  375. if (endpointStore.validation && endpointStore.validation.valid
  376. && !this.closeTimeout) {
  377. this.closeTimeout = setTimeout(() => {
  378. this.props.onCancelClick({ autoClose: true })
  379. }, 2000)
  380. }
  381. return (
  382. <Wrapper>
  383. <EndpointLogos style={{ marginBottom: '16px' }} height={128} endpoint={this.getEndpointType()} />
  384. {this.renderContent()}
  385. {this.renderLoading()}
  386. </Wrapper>
  387. )
  388. }
  389. }
  390. export default Endpoint