DropdownLink.jsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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 autobind from 'autobind-decorator'
  20. import DomUtils from '../../../utils/DomUtils'
  21. import SearchInput from '../../molecules/SearchInput'
  22. import Palette from '../../styleUtils/Palette'
  23. import StyleProps from '../../styleUtils/StyleProps'
  24. import arrowImage from './images/arrow.js'
  25. import checkmarkImage from './images/checkmark.svg'
  26. const Wrapper = styled.div`
  27. display: inline-block;
  28. position: relative;
  29. `
  30. const SearchInputWrapper = styled.div``
  31. const LinkButton = styled.div`
  32. display: flex;
  33. align-items: center;
  34. cursor: ${props => props.disabled ? 'default' : 'pointer'};
  35. `
  36. export const List = styled.div`
  37. position: absolute;
  38. z-index: 1001;
  39. padding: ${props => props.padding != null ? props.padding : 8}px;
  40. background: ${Palette.grayscale[1]};
  41. border-radius: 4px;
  42. border: 1px solid ${Palette.grayscale[0]};
  43. ${props => props.width ? StyleProps.exactWidth(props.width) : css`
  44. min-width: 132px;
  45. max-width: 160px;
  46. `}
  47. ${props => props.customStyle || ''}
  48. `
  49. export const Tip = styled.div`
  50. position: absolute;
  51. top: -6px;
  52. right: 11px;
  53. width: 10px;
  54. height: 10px;
  55. background: ${Palette.grayscale[1]};
  56. border-top: 1px solid ${props => props.borderColor || Palette.grayscale[0]};
  57. border-left: 1px solid ${props => props.borderColor || Palette.grayscale[0]};
  58. border-bottom: 1px solid transparent;
  59. border-right: 1px solid transparent;
  60. transform: rotate(45deg);
  61. transition: all ${StyleProps.animations.swift};
  62. `
  63. export const ListItems = styled.div`
  64. max-height: 400px;
  65. overflow: auto;
  66. ${props => props.searchable ? 'margin-top: 8px;' : ''}
  67. `
  68. export const ListItem = styled.div`
  69. padding-top: 13px;
  70. color: ${props => props.selected ? Palette.primary : Palette.grayscale[4]};
  71. cursor: pointer;
  72. display: flex;
  73. align-items: center;
  74. &:first-child {
  75. padding-top: 0;
  76. }
  77. `
  78. export const ListItemLabel = styled.div`
  79. word-break: break-all;
  80. word-break: break-word;
  81. ${props => props.highlighted ? `font-weight: ${StyleProps.fontWeights.medium};` : ''}
  82. ${props => props.addMargin ? css`margin-left: ${props.addMargin}px;` : ''}
  83. ${props => props.customStyle}
  84. `
  85. const Checkmark = styled.div`
  86. ${StyleProps.exactWidth('16px')}
  87. height: 16px;
  88. background: ${props => props.show ? `url('${checkmarkImage}') center no-repeat` : 'transparent'};
  89. margin-right: 8px;
  90. `
  91. const Label = styled.div`
  92. color: ${props => props.secondary ? Palette.grayscale[4] : Palette.primary};
  93. white-space: nowrap;
  94. overflow: hidden;
  95. text-overflow: ellipsis;
  96. `
  97. const Arrow = styled.div`
  98. width: 16px;
  99. height: 16px;
  100. margin-left: 4px;
  101. display: flex;
  102. justify-content: center;
  103. align-items: center;
  104. ${props => props.orientation === 'right' ? css`transform: rotate(-90deg);` : ''}
  105. ${props => props.orientation === 'left' ? css`transform: rotate(90deg);` : ''}
  106. `
  107. const EmptySearch = styled.div`
  108. margin-top: 8px;
  109. `
  110. type ItemType = {
  111. label: string,
  112. value: any,
  113. [string]: any,
  114. }
  115. type Props = {
  116. selectedItem?: any,
  117. items: ItemType[],
  118. onChange?: (item: ItemType) => void,
  119. highlightedItem?: string,
  120. className?: string,
  121. width?: string,
  122. selectItemLabel?: string,
  123. noItemsLabel?: string,
  124. listWidth?: string,
  125. searchable?: boolean,
  126. disabled?: boolean,
  127. secondary?: boolean,
  128. multipleSelection?: boolean,
  129. selectedItems?: string[],
  130. 'data-test-id'?: string,
  131. linkButtonStyle?: any,
  132. arrowImage?: (color: string) => string,
  133. noCheckmark?: boolean,
  134. itemStyle?: (item: ItemType) => string,
  135. style?: { [mixed]: any },
  136. labelStyle?: any,
  137. getLabel?: () => string,
  138. }
  139. type State = {
  140. showDropdownList: boolean,
  141. searchText: string,
  142. }
  143. @observer
  144. class DropdownLink extends React.Component<Props, State> {
  145. static defaultProps: $Shape<Props> = {
  146. selectItemLabel: 'Select',
  147. noItemsLabel: 'No items',
  148. }
  149. state = {
  150. showDropdownList: false,
  151. searchText: '',
  152. }
  153. scrollableParent: HTMLElement
  154. itemMouseDown: boolean
  155. labelRef: HTMLElement
  156. listItemsRef: HTMLElement
  157. listRef: HTMLElement
  158. arrowRef: HTMLElement
  159. tipRef: HTMLElement
  160. searchInputWrapperRef: HTMLElement
  161. componentDidMount() {
  162. window.addEventListener('mousedown', this.handlePageClick, false)
  163. if (this.arrowRef) {
  164. this.scrollableParent = DomUtils.getScrollableParent(this.arrowRef)
  165. this.scrollableParent.addEventListener('scroll', this.handleScroll)
  166. window.addEventListener('resize', this.handleScroll)
  167. }
  168. this.setLabelWidth()
  169. }
  170. componentDidUpdate() {
  171. this.setLabelWidth()
  172. this.updateListPosition()
  173. }
  174. componentWillUnmount() {
  175. window.removeEventListener('mousedown', this.handlePageClick, false)
  176. }
  177. setLabelWidth() {
  178. if (!this.labelRef) {
  179. return
  180. }
  181. this.labelRef.style.width = ''
  182. let width = parseInt(this.props.width, 10)
  183. if (!width) {
  184. return
  185. }
  186. width -= 28
  187. let labelWidth = this.labelRef.offsetWidth
  188. if (labelWidth < width) {
  189. return
  190. }
  191. this.labelRef.style.width = `${width}px`
  192. }
  193. getFilteredItems() {
  194. let items = this.props.items
  195. return items.filter(item =>
  196. typeof item.value === 'string'
  197. ? item.value.toLowerCase().indexOf(this.state.searchText.toLowerCase()) > -1
  198. : item.value === Number(this.state.searchText)
  199. || item.label.toLowerCase().indexOf(this.state.searchText.toLowerCase()) > -1
  200. )
  201. }
  202. @autobind
  203. handleScroll() {
  204. if (this.arrowRef) {
  205. if (DomUtils.isElementInViewport(this.arrowRef, this.scrollableParent)) {
  206. this.updateListPosition()
  207. } else if (this.state.showDropdownList) {
  208. this.setState({ showDropdownList: false })
  209. }
  210. }
  211. }
  212. @autobind
  213. handlePageClick() {
  214. if (!this.itemMouseDown) {
  215. this.setState({ showDropdownList: false })
  216. }
  217. }
  218. handleButtonClick() {
  219. if (this.props.disabled) {
  220. return
  221. }
  222. this.setState({ showDropdownList: !this.state.showDropdownList }, () => {
  223. this.updateListPosition()
  224. this.scrollIntoView()
  225. })
  226. }
  227. handleItemClick(item: ItemType) {
  228. if (!this.props.multipleSelection) {
  229. this.setState({ showDropdownList: false })
  230. }
  231. if (this.props.onChange) {
  232. this.props.onChange(item)
  233. }
  234. }
  235. handleSearchTextChange(searchText: string) {
  236. this.setState({ searchText })
  237. }
  238. scrollIntoView() {
  239. if (!this.listRef || !this.listItemsRef) {
  240. return
  241. }
  242. let itemIndex = this.props.items.findIndex(i => i.value === this.props.selectedItem)
  243. if (itemIndex === -1 || !this.listItemsRef.children[itemIndex]) {
  244. return
  245. }
  246. // $FlowIssue
  247. this.listItemsRef.children[itemIndex].parentNode.scrollTop = this.listItemsRef.children[itemIndex].offsetTop - this.listItemsRef.children[itemIndex].parentNode.offsetTop
  248. }
  249. updateListPosition() {
  250. if (!this.state.showDropdownList || !this.listRef || !this.arrowRef || !this.tipRef) {
  251. return
  252. }
  253. let listWidth = this.listRef.offsetWidth
  254. let arrowWidth = this.arrowRef.offsetWidth
  255. let arrowHeight = this.arrowRef.offsetHeight
  256. let tipHeight = this.tipRef.offsetHeight
  257. const tipOffset = 9
  258. let arrowOffset = this.arrowRef.getBoundingClientRect()
  259. // If a modal is opened, body scroll is removed and body top is set to replicate scroll position
  260. let scrollOffset = 0
  261. if (document.body && parseInt(document.body.style.top, 10) < 0) {
  262. scrollOffset = -parseInt(document.body && document.body.style.top, 10)
  263. }
  264. this.listRef.style.top = `${arrowOffset.top + (window.pageYOffset || scrollOffset) + arrowHeight + tipHeight}px`
  265. this.listRef.style.left = `${arrowOffset.left + tipOffset + (arrowWidth - listWidth)}px`
  266. }
  267. renderSearch() {
  268. if (!this.props.searchable) {
  269. return null
  270. }
  271. return (
  272. <SearchInputWrapper
  273. innerRef={ref => { this.searchInputWrapperRef = ref }}
  274. onMouseDown={() => { this.itemMouseDown = true }}
  275. onMouseUp={() => { this.itemMouseDown = false }}
  276. >
  277. <SearchInput
  278. alwaysOpen
  279. width="100%"
  280. onChange={text => { this.handleSearchTextChange(text) }}
  281. value={this.state.searchText}
  282. />
  283. </SearchInputWrapper>
  284. )
  285. }
  286. renderEmptySearch() {
  287. if (!this.state.searchText || this.getFilteredItems().length > 0) {
  288. return null
  289. }
  290. return <EmptySearch>No items found</EmptySearch>
  291. }
  292. renderItem(item: ItemType) {
  293. let highlighted = item.value !== this.props.selectedItem ? item.value === this.props.highlightedItem : false
  294. let label = item.label || item.value.toString().charAt(0).toUpperCase() + item.value.toString().substr(1)
  295. let selected
  296. if (this.props.multipleSelection && this.props.selectedItems) {
  297. selected = Boolean(this.props.selectedItems.find(i => i === item.value))
  298. } else {
  299. selected = item.value === this.props.selectedItem
  300. }
  301. return (
  302. <ListItem
  303. key={item.label || item.value}
  304. onMouseDown={() => { this.itemMouseDown = true }}
  305. onMouseUp={() => { this.itemMouseDown = false }}
  306. onClick={() => { this.handleItemClick(item) }}
  307. selected={selected}
  308. >
  309. {!this.props.noCheckmark ? <Checkmark show={selected} /> : null}
  310. <ListItemLabel
  311. highlighted={highlighted}
  312. addMargin={this.props.noCheckmark ? 8 : 0}
  313. customStyle={this.props.itemStyle ? this.props.itemStyle(item) : ''}
  314. >{label}</ListItemLabel>
  315. </ListItem>
  316. )
  317. }
  318. renderListItems() {
  319. if (this.state.searchText && this.getFilteredItems().length === 0) {
  320. return null
  321. }
  322. return (
  323. <ListItems
  324. data-test-id="dropdownLink-listItem"
  325. innerRef={ref => { this.listItemsRef = ref }}
  326. searchable={this.props.searchable}
  327. >
  328. {this.getFilteredItems().map((item) => {
  329. return this.renderItem(item)
  330. })}
  331. </ListItems>
  332. )
  333. }
  334. renderList() {
  335. if (!this.props.items || this.props.items.length === 0 || !this.state.showDropdownList) {
  336. return null
  337. }
  338. let body: any = document.body
  339. return ReactDOM.createPortal((
  340. <List innerRef={list => { this.listRef = list }} width={this.props.listWidth}>
  341. <Tip innerRef={ref => { this.tipRef = ref }} />
  342. {this.renderSearch()}
  343. {this.renderEmptySearch()}
  344. {this.renderListItems()}
  345. </List>
  346. ), body)
  347. }
  348. render() {
  349. let renderLabel = () => {
  350. if (this.props.getLabel) {
  351. return this.props.getLabel()
  352. }
  353. if (this.props.items && this.props.items.length && this.props.selectedItem != null) {
  354. let item = this.props.items.find(i => i.value === this.props.selectedItem)
  355. if (item && item.label) {
  356. return item.label
  357. }
  358. }
  359. if (!this.props.items || this.props.items.length === 0) {
  360. return this.props.noItemsLabel
  361. }
  362. return this.props.selectItemLabel
  363. }
  364. let arrowImageFunc = this.props.arrowImage || arrowImage
  365. return (
  366. <Wrapper
  367. className={this.props.className}
  368. onMouseDown={() => { this.itemMouseDown = true }}
  369. onMouseUp={() => { this.itemMouseDown = false }}
  370. data-test-id={this.props['data-test-id'] || 'dropdownLink'}
  371. style={this.props.style}
  372. >
  373. <LinkButton
  374. onClick={() => this.handleButtonClick()}
  375. disabled={this.props.disabled}
  376. style={this.props.linkButtonStyle}
  377. >
  378. <Label
  379. secondary={this.props.secondary}
  380. innerRef={label => { this.labelRef = label }}
  381. data-test-id="dropdownLink-label"
  382. style={this.props.labelStyle}
  383. >{renderLabel()}</Label>
  384. <Arrow
  385. innerRef={arrow => { this.arrowRef = arrow }}
  386. dangerouslySetInnerHTML={{
  387. __html: arrowImageFunc(this.props.secondary ? Palette.grayscale[3] : Palette.primary),
  388. }}
  389. />
  390. </LinkButton>
  391. {this.renderList()}
  392. </Wrapper>
  393. )
  394. }
  395. }
  396. export default DropdownLink