Dropdown.jsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  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 DropdownButton from '../../atoms/DropdownButton'
  21. import Palette from '../../styleUtils/Palette'
  22. import DomUtils from '../../../utils/DomUtils'
  23. import StyleProps from '../../styleUtils/StyleProps'
  24. import checkmarkImage from './images/checkmark'
  25. import tipImage from './images/tip'
  26. import requiredImage from './images/required.svg'
  27. const getWidth = props => {
  28. if (props.width) {
  29. return props.width - 2
  30. }
  31. return StyleProps.inputSizes.regular.width - 2
  32. }
  33. const Wrapper = styled.div`
  34. position: relative;
  35. ${props => props.embedded ? 'width: 100%;' : ''}
  36. `
  37. const Required = styled.div`
  38. position: absolute;
  39. width: 8px;
  40. height: 8px;
  41. right: -16px;
  42. top: 12px;
  43. background: url('${requiredImage}') center no-repeat;
  44. ${props => props.disabledLoading ? StyleProps.animations.disabledLoading : ''}
  45. `
  46. const List = styled.div`
  47. position: absolute;
  48. background: white;
  49. cursor: pointer;
  50. width: ${props => getWidth(props)}px;
  51. border: 1px solid ${Palette.grayscale[3]};
  52. border-radius: ${StyleProps.borderRadius};
  53. z-index: 1000;
  54. `
  55. const ListItems = styled.div`
  56. max-height: 400px;
  57. overflow: auto;
  58. `
  59. export const Tip = styled.div`
  60. position: absolute;
  61. width: 16px;
  62. height: 8px;
  63. right: 8px;
  64. top: -8px;
  65. z-index: 11;
  66. transition: all ${StyleProps.animations.swift};
  67. overflow: hidden;
  68. svg {
  69. #path {
  70. transition: all ${StyleProps.animations.swift};
  71. fill: ${props => props.primary ? Palette.primary : 'white'};
  72. }
  73. }
  74. `
  75. const Checkmark = styled.div`
  76. ${StyleProps.exactWidth('16px')}
  77. height: 16px;
  78. margin-right: 8px;
  79. margin-top: 1px;
  80. display: flex;
  81. justify-content: center;
  82. align-items: center;
  83. #symbol {
  84. transition: stroke ${StyleProps.animations.swift};
  85. stroke-dasharray: 12;
  86. stroke-dashoffset: ${props => props.show ? 24 : 12};
  87. animation-duration: 100ms;
  88. animation-timing-function: ease-in-out;
  89. animation-fill-mode: forwards;
  90. @keyframes dashOn {
  91. from { stroke-dashoffset: 12; }
  92. to { stroke-dashoffset: 24; }
  93. }
  94. @keyframes dashOff {
  95. from { stroke-dashoffset: 24; }
  96. to { stroke-dashoffset: 12; }
  97. }
  98. }
  99. `
  100. const ListItem = styled.div`
  101. position: relative;
  102. display: flex;
  103. color: ${props => props.multipleSelected ? Palette.primary : props.selected ? 'white' : props.dim ? Palette.grayscale[3] : Palette.grayscale[4]};
  104. ${props => props.selected ? css`background: ${Palette.primary};` : ''}
  105. ${props => props.selected ? css`font-weight: ${StyleProps.fontWeights.medium};` : ''}
  106. padding: 8px 16px;
  107. transition: all ${StyleProps.animations.swift};
  108. padding-left: ${props => props.paddingLeft}px;
  109. &:first-child {
  110. border-top-left-radius: ${StyleProps.borderRadius};
  111. border-top-right-radius: ${StyleProps.borderRadius};
  112. }
  113. &:last-child {
  114. border-bottom-left-radius: ${StyleProps.borderRadius};
  115. border-bottom-right-radius: ${StyleProps.borderRadius};
  116. }
  117. &:hover {
  118. background: ${Palette.primary};
  119. color: white;
  120. ${Checkmark} #symbol {
  121. stroke: white;
  122. }
  123. }
  124. `
  125. const DuplicatedLabel = styled.div`
  126. display: flex;
  127. font-size: 11px;
  128. span {
  129. text-overflow: ellipsis;
  130. white-space: nowrap;
  131. overflow: hidden;
  132. }
  133. `
  134. const Separator = styled.div`
  135. width: calc(100% - 32px);
  136. height: 1px;
  137. margin: 8px 16px;
  138. background: ${Palette.grayscale[3]};
  139. `
  140. const Labels = styled.div`
  141. word-break: break-word;
  142. max-width: 100%;
  143. `
  144. export const updateTipStyle = (listItemsRef: HTMLElement, tipRef: HTMLElement, firstItemRef: HTMLElement) => {
  145. if (tipRef && firstItemRef) {
  146. let svgPath = tipRef.querySelector('#path')
  147. if (svgPath) {
  148. if (listItemsRef.clientHeight < listItemsRef.scrollHeight) {
  149. // $FlowIssue
  150. svgPath.style.fill = 'white'
  151. firstItemRef.style.borderTopRightRadius = '0'
  152. } else {
  153. // $FlowIssue
  154. svgPath.style.fill = ''
  155. firstItemRef.style.borderTopRightRadius = ''
  156. }
  157. }
  158. }
  159. }
  160. export const scrollItemIntoView = (
  161. listRef: HTMLElement,
  162. listItemsRef: HTMLElement,
  163. itemIndex: number
  164. ) => {
  165. if (!listRef || !listItemsRef) {
  166. return
  167. }
  168. if (itemIndex === -1 || !listItemsRef.children[itemIndex]) {
  169. return
  170. }
  171. // $FlowIssue
  172. listItemsRef.children[itemIndex].parentNode.scrollTop = listItemsRef.children[itemIndex].offsetTop - listItemsRef.children[itemIndex].parentNode.offsetTop - 32
  173. }
  174. type Props = {
  175. selectedItem: any,
  176. items: any[],
  177. labelField: string,
  178. valueField: string,
  179. className: string,
  180. onChange: (item: any) => void,
  181. noItemsMessage: string,
  182. noSelectionMessage: string,
  183. disabled: boolean,
  184. disabledLoading: boolean,
  185. width: number,
  186. 'data-test-id'?: string,
  187. embedded?: boolean,
  188. dimFirstItem?: boolean,
  189. multipleSelection?: boolean,
  190. selectedItems?: ?any[],
  191. highlight?: boolean,
  192. required?: boolean,
  193. }
  194. type State = {
  195. showDropdownList: boolean,
  196. firstItemHover: boolean
  197. }
  198. @observer
  199. class Dropdown extends React.Component<Props, State> {
  200. static defaultProps: $Shape<Props> = {
  201. noSelectionMessage: 'Select an item',
  202. }
  203. state = {
  204. showDropdownList: false,
  205. firstItemHover: false,
  206. }
  207. buttonRef: HTMLElement
  208. listRef: HTMLElement
  209. listItemsRef: HTMLElement
  210. firstItemRef: HTMLElement
  211. tipRef: HTMLElement
  212. scrollableParent: HTMLElement
  213. buttonRect: ClientRect
  214. itemMouseDown: boolean
  215. componentDidMount() {
  216. window.addEventListener('mousedown', this.handlePageClick, false)
  217. if (this.buttonRef) {
  218. this.scrollableParent = DomUtils.getScrollableParent(this.buttonRef)
  219. this.scrollableParent.addEventListener('scroll', this.handleScroll)
  220. window.addEventListener('resize', this.handleScroll)
  221. this.buttonRect = this.buttonRef.getBoundingClientRect()
  222. }
  223. }
  224. componentWillUpdate() {
  225. if (this.buttonRef) this.buttonRect = this.buttonRef.getBoundingClientRect()
  226. }
  227. componentDidUpdate() {
  228. this.updateListPosition()
  229. }
  230. componentWillUnmount() {
  231. window.removeEventListener('mousedown', this.handlePageClick, false)
  232. window.removeEventListener('resize', this.handleScroll, false)
  233. this.scrollableParent.removeEventListener('scroll', this.handleScroll, false)
  234. }
  235. getLabel(item: any) {
  236. let labelField = this.props.labelField || 'label'
  237. if (item == null) {
  238. return this.props.noSelectionMessage
  239. }
  240. if (item[labelField] != null) {
  241. return item[labelField].toString()
  242. }
  243. if (item.value != null) {
  244. return item.value.toString()
  245. }
  246. return item.toString()
  247. }
  248. getValue(item: any) {
  249. let valueField = this.props.valueField || 'value'
  250. if (item == null) {
  251. return null
  252. }
  253. return (item[valueField] != null && item[valueField].toString()) || this.getLabel(item)
  254. }
  255. @autobind
  256. handleScroll() {
  257. if (this.buttonRef) {
  258. if (DomUtils.isElementInViewport(this.buttonRef, this.scrollableParent)) {
  259. this.buttonRect = this.buttonRef.getBoundingClientRect()
  260. this.updateListPosition()
  261. } else if (this.state.showDropdownList) {
  262. this.setState({ showDropdownList: false })
  263. }
  264. }
  265. }
  266. @autobind
  267. handlePageClick() {
  268. if (!this.itemMouseDown) {
  269. this.setState({ showDropdownList: false })
  270. }
  271. }
  272. handleButtonClick() {
  273. if (this.props.disabled) {
  274. return
  275. }
  276. this.setState({ showDropdownList: !this.state.showDropdownList }, () => {
  277. this.scrollIntoView()
  278. })
  279. }
  280. handleItemClick(item: any, checkmarkRef: HTMLElement) {
  281. if (!this.props.multipleSelection) {
  282. this.setState({ showDropdownList: false, firstItemHover: false })
  283. } else {
  284. this.toggleCheckmarkAnimation(item, checkmarkRef)
  285. }
  286. if (this.props.onChange) {
  287. this.props.onChange(item)
  288. }
  289. }
  290. handleItemMouseEnter(index: number) {
  291. if (index === 0) {
  292. this.setState({ firstItemHover: true })
  293. }
  294. }
  295. handleItemMouseLeave(index: number) {
  296. if (index === 0) {
  297. this.setState({ firstItemHover: false })
  298. }
  299. }
  300. toggleCheckmarkAnimation(item: any, checkmarkRef: HTMLElement) {
  301. if (!item || !checkmarkRef) {
  302. return
  303. }
  304. let multipleSelected = this.props.selectedItems && this.props.selectedItems.find(i =>
  305. this.getValue(i) === this.getValue(item))
  306. let symbol = checkmarkRef.querySelector('#symbol')
  307. if (symbol) {
  308. symbol.style.animationName = multipleSelected ? 'dashOff' : 'dashOn'
  309. }
  310. }
  311. updateListPosition() {
  312. if (!this.state.showDropdownList || !this.listRef || !this.buttonRef || !document.body) {
  313. return
  314. }
  315. let buttonHeight = this.buttonRef.offsetHeight
  316. let tipHeight = 8
  317. let listTop = this.buttonRect.top + buttonHeight + tipHeight
  318. let listHeight = this.listRef.offsetHeight
  319. if (listTop + listHeight > window.innerHeight) {
  320. listTop = window.innerHeight - listHeight - 16
  321. this.tipRef.style.display = 'none'
  322. } else {
  323. this.tipRef.style.display = 'block'
  324. }
  325. // If a modal is opened, body scroll is removed and body top is set to replicate scroll position
  326. let scrollOffset = 0
  327. if (parseInt(document.body.style.top, 10) < 0) {
  328. scrollOffset = -parseInt(document.body && document.body.style.top, 10)
  329. }
  330. let widthDiff = this.listRef.offsetWidth - this.buttonRef.offsetWidth
  331. this.listRef.style.top = `${listTop + (window.pageYOffset || scrollOffset)}px`
  332. this.listRef.style.left = `${(this.buttonRect.left + window.pageXOffset) - widthDiff}px`
  333. updateTipStyle(this.listItemsRef, this.tipRef, this.firstItemRef)
  334. }
  335. scrollIntoView() {
  336. let itemIndex = this.props.items.findIndex(i => this.getValue(i) === this.getValue(this.props.selectedItem))
  337. scrollItemIntoView(this.listRef, this.listItemsRef, itemIndex)
  338. }
  339. renderList() {
  340. if (!this.props.items || this.props.items.length === 0 || !this.state.showDropdownList) {
  341. return null
  342. }
  343. const body: any = document.body
  344. let selectedValue = this.getValue(this.props.selectedItem)
  345. let duplicatedLabels = []
  346. this.props.items.forEach((item, i) => {
  347. let label = this.getLabel(item)
  348. for (let j = i + 1; j < this.props.items.length; j += 1) {
  349. if (label === this.getLabel(this.props.items[j]) && !duplicatedLabels.find(item2 => this.getLabel(item2) === label)) {
  350. duplicatedLabels.push(label)
  351. }
  352. }
  353. })
  354. const firstItemValue = this.props.items.length > 0 ? this.getValue(this.props.items[0]) : null
  355. const isFirstItemSelected = selectedValue === firstItemValue
  356. let list = ReactDOM.createPortal((
  357. <List {...this.props} innerRef={ref => { this.listRef = ref }}>
  358. <Tip
  359. innerRef={ref => { this.tipRef = ref }}
  360. primary={this.state.firstItemHover || isFirstItemSelected}
  361. dangerouslySetInnerHTML={{ __html: tipImage }}
  362. />
  363. <ListItems innerRef={ref => { this.listItemsRef = ref }}>
  364. {this.props.items.map((item, i) => {
  365. if (item.separator === true) {
  366. return <Separator key={`sep-${i}`} />
  367. }
  368. let label = this.getLabel(item)
  369. let value = this.getValue(item)
  370. let duplicatedLabel = duplicatedLabels.find(l => l === label)
  371. let multipleSelected = this.props.selectedItems && this.props.selectedItems
  372. .find(i => this.getValue(i) === value)
  373. let checkmarkRef
  374. let listItem = (
  375. <ListItem
  376. data-test-id="dropdownListItem"
  377. innerRef={ref => { if (i === 0) { this.firstItemRef = ref } }}
  378. key={value}
  379. onMouseDown={() => { this.itemMouseDown = true }}
  380. onMouseUp={() => { this.itemMouseDown = false }}
  381. onMouseEnter={() => { this.handleItemMouseEnter(i) }}
  382. onMouseLeave={() => { this.handleItemMouseLeave(i) }}
  383. onClick={() => { this.handleItemClick(item, checkmarkRef) }}
  384. selected={!this.props.multipleSelection && value === selectedValue}
  385. multipleSelected={this.props.multipleSelection && multipleSelected}
  386. dim={this.props.dimFirstItem && i === 0}
  387. paddingLeft={this.props.multipleSelection ? 8 : 16}
  388. >
  389. {this.props.multipleSelection ? (
  390. <Checkmark
  391. innerRef={ref => { checkmarkRef = ref }}
  392. dangerouslySetInnerHTML={{ __html: checkmarkImage }}
  393. show={multipleSelected}
  394. />
  395. ) : null}
  396. <Labels>
  397. {label === '' ? '\u00A0' : label}
  398. {duplicatedLabel ? <DuplicatedLabel> (<span>{value || ''}</span>)</DuplicatedLabel> : ''}
  399. </Labels>
  400. </ListItem>
  401. )
  402. return listItem
  403. })}
  404. </ListItems>
  405. </List>
  406. ), body)
  407. return list
  408. }
  409. render() {
  410. let buttonValue = () => {
  411. if (this.props.items && this.props.items.length) {
  412. if (this.props.multipleSelection && this.props.selectedItems && this.props.selectedItems.length > 0) {
  413. return this.props.selectedItems.map(i => this.getLabel(this.props.items.find(item =>
  414. this.getValue(item) === this.getValue(i)))).join(', ')
  415. }
  416. return this.getLabel(this.props.selectedItem)
  417. }
  418. return this.props.noItemsMessage || ''
  419. }
  420. return (
  421. <Wrapper
  422. className={this.props.className}
  423. onMouseDown={() => { this.itemMouseDown = true }}
  424. onMouseUp={() => { this.itemMouseDown = false }}
  425. data-test-id={this.props['data-test-id'] || 'dropdown'}
  426. embedded={this.props.embedded}
  427. >
  428. <DropdownButton
  429. {...this.props}
  430. data-test-id="dropdown-dropdownButton"
  431. innerRef={ref => { this.buttonRef = ref }}
  432. onMouseDown={() => { this.itemMouseDown = true }}
  433. onMouseUp={() => { this.itemMouseDown = false }}
  434. value={buttonValue()}
  435. onClick={() => this.handleButtonClick()}
  436. />
  437. {this.props.required ? <Required disabledLoading={this.props.disabledLoading} /> : null}
  438. {this.renderList()}
  439. </Wrapper>
  440. )
  441. }
  442. }
  443. export default Dropdown