Endpoint.jsx 12 KB

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