index.jsx 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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 { observer } from 'mobx-react'
  17. import styled, { css } from 'styled-components'
  18. import ReactDOM from 'react-dom'
  19. import SearchInput from '../../molecules/SearchInput'
  20. import Palette from '../../styleUtils/Palette'
  21. import StyleProps from '../../styleUtils/StyleProps'
  22. import arrowImage from './images/arrow.svg'
  23. import checkmarkImage from './images/checkmark.svg'
  24. const Wrapper = styled.div`
  25. display: inline-block;
  26. position: relative;
  27. `
  28. const SearchInputWrapper = styled.div``
  29. const LinkButton = styled.div`
  30. display: flex;
  31. align-items: center;
  32. cursor: ${props => props.disabled ? 'default' : 'pointer'};
  33. `
  34. const List = styled.div`
  35. position: absolute;
  36. z-index: 20;
  37. padding: 8px;
  38. background: ${Palette.grayscale[1]};
  39. border-radius: 4px;
  40. border: 1px solid ${Palette.grayscale[0]};
  41. ${props => props.width ? StyleProps.exactWidth(props.width) : css`
  42. min-width: 132px;
  43. max-width: 160px;
  44. `}
  45. `
  46. const Tip = styled.div`
  47. position: absolute;
  48. top: -6px;
  49. right: 8px;
  50. width: 10px;
  51. height: 10px;
  52. background: ${Palette.grayscale[1]};
  53. border-top: 1px solid ${Palette.grayscale[0]};
  54. border-left: 1px solid ${Palette.grayscale[0]};
  55. border-bottom: 1px solid transparent;
  56. border-right: 1px solid transparent;
  57. transform: rotate(45deg);
  58. `
  59. const ListItems = styled.div`
  60. max-height: 400px;
  61. overflow: auto;
  62. ${props => props.searchable ? 'margin-top: 8px;' : ''}
  63. `
  64. const ListItem = styled.div`
  65. padding-top: 13px;
  66. color: ${props => props.selected ? Palette.primary : Palette.grayscale[4]};
  67. cursor: pointer;
  68. display: flex;
  69. &:first-child {
  70. padding-top: 0;
  71. }
  72. `
  73. const ListItemLabel = styled.div`
  74. word-break: break-all;
  75. word-break: break-word;
  76. ${props => props.highlighted ? `font-weight: ${StyleProps.fontWeights.medium};` : ''}
  77. `
  78. const Checkmark = styled.div`
  79. ${StyleProps.exactWidth('16px')}
  80. height: 16px;
  81. background: ${props => props.show ? `url('${checkmarkImage}') center no-repeat` : 'transparent'};
  82. margin-right: 8px;
  83. `
  84. const Label = styled.div`
  85. color: ${Palette.primary};
  86. white-space: nowrap;
  87. overflow: hidden;
  88. text-overflow: ellipsis;
  89. `
  90. const Arrow = styled.div`
  91. width: 16px;
  92. height: 16px;
  93. background: url('${arrowImage}') center no-repeat;
  94. margin-left: 4px;
  95. margin-top: -1px;
  96. `
  97. const EmptySearch = styled.div`
  98. margin-top: 8px;
  99. `
  100. type ItemType = {
  101. label: string,
  102. value: string,
  103. [string]: any,
  104. }
  105. type Props = {
  106. selectedItem?: string,
  107. items: ItemType[],
  108. onChange?: (item: ItemType) => void,
  109. highlightedItem?: string,
  110. className?: string,
  111. width?: string,
  112. selectItemLabel?: string,
  113. noItemsLabel?: string,
  114. listWidth?: string,
  115. searchable?: boolean,
  116. disabled?: boolean,
  117. 'data-test-id'?: string,
  118. }
  119. type State = {
  120. showDropdownList: boolean,
  121. searchText: string,
  122. }
  123. @observer
  124. class DropdownLink extends React.Component<Props, State> {
  125. static defaultProps: $Shape<Props> = {
  126. selectItemLabel: 'Select',
  127. noItemsLabel: 'No items',
  128. }
  129. itemMouseDown: boolean
  130. labelRef: HTMLElement
  131. listItemsRef: HTMLElement
  132. listRef: HTMLElement
  133. arrowRef: HTMLElement
  134. tipRef: HTMLElement
  135. searchInputWrapperRef: HTMLElement
  136. constructor() {
  137. super()
  138. this.state = {
  139. showDropdownList: false,
  140. searchText: '',
  141. }
  142. const self: any = this
  143. self.handlePageClick = this.handlePageClick.bind(this)
  144. }
  145. componentDidMount() {
  146. window.addEventListener('mousedown', this.handlePageClick, false)
  147. this.setLabelWidth()
  148. }
  149. componentDidUpdate() {
  150. this.setLabelWidth()
  151. this.updateListPosition()
  152. }
  153. componentWillUnmount() {
  154. window.removeEventListener('mousedown', this.handlePageClick, false)
  155. }
  156. setLabelWidth() {
  157. if (!this.labelRef) {
  158. return
  159. }
  160. this.labelRef.style.width = ''
  161. let width = parseInt(this.props.width, 10)
  162. if (!width) {
  163. return
  164. }
  165. width -= 28
  166. let labelWidth = this.labelRef.offsetWidth
  167. if (labelWidth < width) {
  168. return
  169. }
  170. this.labelRef.style.width = `${width}px`
  171. }
  172. getFilteredItems() {
  173. return this.props.items.filter(item =>
  174. item.value.toLowerCase().indexOf(this.state.searchText.toLowerCase()) > -1 ||
  175. item.label.toLowerCase().indexOf(this.state.searchText.toLowerCase()) > -1
  176. )
  177. }
  178. handlePageClick() {
  179. if (!this.itemMouseDown) {
  180. this.setState({ showDropdownList: false })
  181. }
  182. }
  183. handleButtonClick() {
  184. if (this.props.disabled) {
  185. return
  186. }
  187. this.setState({ showDropdownList: !this.state.showDropdownList }, () => {
  188. this.scrollIntoView()
  189. })
  190. }
  191. handleItemClick(item: ItemType) {
  192. this.setState({ showDropdownList: false })
  193. if (this.props.onChange) {
  194. this.props.onChange(item)
  195. }
  196. }
  197. handleSearchTextChange(searchText: string) {
  198. this.setState({ searchText })
  199. }
  200. scrollIntoView() {
  201. if (!this.listRef || !this.listItemsRef) {
  202. return
  203. }
  204. let itemIndex = this.props.items.findIndex(i => i.value === this.props.selectedItem)
  205. if (itemIndex === -1 || !this.listItemsRef.children[itemIndex]) {
  206. return
  207. }
  208. // $FlowIssue
  209. this.listItemsRef.children[itemIndex].parentNode.scrollTop = this.listItemsRef.children[itemIndex].offsetTop - this.listItemsRef.children[itemIndex].parentNode.offsetTop
  210. }
  211. updateListPosition() {
  212. if (!this.state.showDropdownList || !this.listRef || !this.arrowRef || !this.tipRef) {
  213. return
  214. }
  215. let listWidth = this.listRef.offsetWidth
  216. let arrowWidth = this.arrowRef.offsetWidth
  217. let arrowHeight = this.arrowRef.offsetHeight
  218. let tipHeight = this.tipRef.offsetHeight
  219. const tipOffset = 7
  220. let arrowOffset = this.arrowRef.getBoundingClientRect()
  221. this.listRef.style.top = `${arrowOffset.top + window.pageYOffset + arrowHeight + tipHeight}px`
  222. this.listRef.style.left = `${arrowOffset.left + tipOffset + (arrowWidth - listWidth)}px`
  223. }
  224. renderSearch() {
  225. if (!this.props.searchable) {
  226. return null
  227. }
  228. return (
  229. <SearchInputWrapper
  230. innerRef={ref => { this.searchInputWrapperRef = ref }}
  231. onMouseDown={() => { this.itemMouseDown = true }}
  232. onMouseUp={() => { this.itemMouseDown = false }}
  233. >
  234. <SearchInput
  235. alwaysOpen
  236. width="100%"
  237. onChange={text => { this.handleSearchTextChange(text) }}
  238. value={this.state.searchText}
  239. />
  240. </SearchInputWrapper>
  241. )
  242. }
  243. renderEmptySearch() {
  244. if (!this.state.searchText || this.getFilteredItems().length > 0) {
  245. return null
  246. }
  247. return <EmptySearch>No items found</EmptySearch>
  248. }
  249. renderListItems() {
  250. if (this.state.searchText && this.getFilteredItems().length === 0) {
  251. return null
  252. }
  253. return (
  254. <ListItems innerRef={ref => { this.listItemsRef = ref }} searchable={this.props.searchable}>
  255. {this.getFilteredItems().map((item) => {
  256. let highlighted = item.value !== this.props.selectedItem ? item.value === this.props.highlightedItem : false
  257. let listItem = (
  258. <ListItem
  259. key={item.label}
  260. onMouseDown={() => { this.itemMouseDown = true }}
  261. onMouseUp={() => { this.itemMouseDown = false }}
  262. onClick={() => { this.handleItemClick(item) }}
  263. selected={item.value === this.props.selectedItem}
  264. >
  265. <Checkmark show={item.value === this.props.selectedItem} />
  266. <ListItemLabel highlighted={highlighted}>{item.label}</ListItemLabel>
  267. </ListItem>
  268. )
  269. return listItem
  270. })}
  271. </ListItems>
  272. )
  273. }
  274. renderList() {
  275. if (!this.props.items || this.props.items.length === 0 || !this.state.showDropdownList) {
  276. return null
  277. }
  278. let body: any = document.body
  279. return ReactDOM.createPortal((
  280. <List innerRef={list => { this.listRef = list }} width={this.props.listWidth}>
  281. <Tip innerRef={ref => { this.tipRef = ref }} />
  282. {this.renderSearch()}
  283. {this.renderEmptySearch()}
  284. {this.renderListItems()}
  285. </List>
  286. ), body)
  287. }
  288. render() {
  289. let renderLabel = () => {
  290. if (this.props.items && this.props.items.length && this.props.selectedItem) {
  291. let item = this.props.items.find(i => i.value === this.props.selectedItem)
  292. if (item && item.label) {
  293. return item.label
  294. }
  295. }
  296. if (!this.props.items || this.props.items.length === 0) {
  297. return this.props.noItemsLabel
  298. }
  299. return this.props.selectItemLabel
  300. }
  301. return (
  302. <Wrapper
  303. className={this.props.className}
  304. onMouseDown={() => { this.itemMouseDown = true }}
  305. onMouseUp={() => { this.itemMouseDown = false }}
  306. data-test-id={this.props['data-test-id'] || 'dropdownLink'}
  307. >
  308. <LinkButton
  309. onClick={() => this.handleButtonClick()}
  310. disabled={this.props.disabled}
  311. >
  312. <Label innerRef={label => { this.labelRef = label }} data-test-id="dropdownLinkLabel">{renderLabel()}</Label>
  313. <Arrow innerRef={arrow => { this.arrowRef = arrow }} />
  314. </LinkButton>
  315. {this.renderList()}
  316. </Wrapper>
  317. )
  318. }
  319. }
  320. export default DropdownLink