Dropdown.jsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  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. word-break: break-word;
  110. &:first-child {
  111. border-top-left-radius: ${StyleProps.borderRadius};
  112. border-top-right-radius: ${StyleProps.borderRadius};
  113. }
  114. &:last-child {
  115. border-bottom-left-radius: ${StyleProps.borderRadius};
  116. border-bottom-right-radius: ${StyleProps.borderRadius};
  117. }
  118. &:hover {
  119. background: ${Palette.primary};
  120. color: white;
  121. ${Checkmark} #symbol {
  122. stroke: white;
  123. }
  124. }
  125. `
  126. const DuplicatedLabel = styled.div`
  127. display: flex;
  128. font-size: 11px;
  129. span {
  130. text-overflow: ellipsis;
  131. white-space: nowrap;
  132. overflow: hidden;
  133. }
  134. `
  135. const Separator = styled.div`
  136. width: calc(100% - 32px);
  137. height: 1px;
  138. margin: 8px 16px;
  139. background: ${Palette.grayscale[3]};
  140. `
  141. const Labels = styled.div`
  142. word-break: break-word;
  143. max-width: 100%;
  144. `
  145. export const updateTipStyle = (listItemsRef: HTMLElement, tipRef: HTMLElement, firstItemRef: HTMLElement) => {
  146. if (tipRef && firstItemRef) {
  147. let svgPath = tipRef.querySelector('#path')
  148. if (svgPath) {
  149. if (listItemsRef.clientHeight < listItemsRef.scrollHeight) {
  150. // $FlowIssue
  151. svgPath.style.fill = 'white'
  152. firstItemRef.style.borderTopRightRadius = '0'
  153. } else {
  154. // $FlowIssue
  155. svgPath.style.fill = ''
  156. firstItemRef.style.borderTopRightRadius = ''
  157. }
  158. }
  159. }
  160. }
  161. export const scrollItemIntoView = (
  162. listRef: HTMLElement,
  163. listItemsRef: HTMLElement,
  164. itemIndex: number
  165. ) => {
  166. if (!listRef || !listItemsRef) {
  167. return
  168. }
  169. if (itemIndex === -1 || !listItemsRef.children[itemIndex]) {
  170. return
  171. }
  172. // $FlowIssue
  173. listItemsRef.children[itemIndex].parentNode.scrollTop = listItemsRef.children[itemIndex].offsetTop - listItemsRef.children[itemIndex].parentNode.offsetTop - 32
  174. }
  175. type Props = {
  176. selectedItem: any,
  177. items: any[],
  178. labelField: string,
  179. valueField: string,
  180. className: string,
  181. onChange: (item: any) => void,
  182. noItemsMessage: string,
  183. noSelectionMessage: string,
  184. disabled: boolean,
  185. disabledLoading: boolean,
  186. width: number,
  187. 'data-test-id'?: string,
  188. embedded?: boolean,
  189. dimFirstItem?: boolean,
  190. multipleSelection?: boolean,
  191. selectedItems?: ?any[],
  192. highlight?: boolean,
  193. required?: boolean,
  194. }
  195. type State = {
  196. showDropdownList: boolean,
  197. firstItemHover: boolean
  198. }
  199. @observer
  200. class Dropdown extends React.Component<Props, State> {
  201. static defaultProps: $Shape<Props> = {
  202. noSelectionMessage: 'Select an item',
  203. }
  204. state = {
  205. showDropdownList: false,
  206. firstItemHover: false,
  207. }
  208. buttonRef: HTMLElement
  209. listRef: HTMLElement
  210. listItemsRef: HTMLElement
  211. firstItemRef: HTMLElement
  212. tipRef: HTMLElement
  213. scrollableParent: HTMLElement
  214. buttonRect: ClientRect
  215. itemMouseDown: boolean
  216. checkmarkRefs: { [string]: HTMLElement } = {}
  217. componentDidMount() {
  218. window.addEventListener('mousedown', this.handlePageClick, false)
  219. if (this.buttonRef) {
  220. this.scrollableParent = DomUtils.getScrollableParent(this.buttonRef)
  221. this.scrollableParent.addEventListener('scroll', this.handleScroll)
  222. window.addEventListener('resize', this.handleScroll)
  223. this.buttonRect = this.buttonRef.getBoundingClientRect()
  224. }
  225. }
  226. componentWillReceiveProps(newProps: Props) {
  227. if (!this.props.multipleSelection) {
  228. return
  229. }
  230. // Clear checkmark if items are removed in newProps
  231. let newSelectedItems = newProps.selectedItems || []
  232. let oldSelectedItems = this.props.selectedItems || []
  233. let hash = item => `${this.getLabel(item)}-${this.getValue(item) || ''}`
  234. let needsCheckmarkClear = oldSelectedItems.filter(oldItem => !newSelectedItems.find(newItem => hash(oldItem) === hash(newItem)))
  235. needsCheckmarkClear.forEach(clearItem => {
  236. this.toggleCheckmarkAnimation(clearItem, this.checkmarkRefs[hash(clearItem)], true)
  237. })
  238. }
  239. componentWillUpdate() {
  240. if (this.buttonRef) this.buttonRect = this.buttonRef.getBoundingClientRect()
  241. }
  242. componentDidUpdate() {
  243. this.updateListPosition()
  244. }
  245. componentWillUnmount() {
  246. window.removeEventListener('mousedown', this.handlePageClick, false)
  247. window.removeEventListener('resize', this.handleScroll, false)
  248. this.scrollableParent.removeEventListener('scroll', this.handleScroll, false)
  249. }
  250. getLabel(item: any) {
  251. let labelField = this.props.labelField || 'label'
  252. if (item == null) {
  253. return this.props.noSelectionMessage
  254. }
  255. if (item[labelField] != null) {
  256. return item[labelField].toString()
  257. }
  258. if (item.value != null) {
  259. return item.value.toString()
  260. }
  261. return item.toString()
  262. }
  263. getValue(item: any) {
  264. let valueField = this.props.valueField || 'value'
  265. if (item == null) {
  266. return null
  267. }
  268. return (item[valueField] != null && item[valueField].toString()) || this.getLabel(item)
  269. }
  270. @autobind
  271. handleScroll() {
  272. if (this.buttonRef) {
  273. if (DomUtils.isElementInViewport(this.buttonRef, this.scrollableParent)) {
  274. this.buttonRect = this.buttonRef.getBoundingClientRect()
  275. this.updateListPosition()
  276. } else if (this.state.showDropdownList) {
  277. this.setState({ showDropdownList: false })
  278. }
  279. }
  280. }
  281. @autobind
  282. handlePageClick() {
  283. if (!this.itemMouseDown) {
  284. this.setState({ showDropdownList: false })
  285. }
  286. }
  287. handleButtonClick() {
  288. if (this.props.disabled) {
  289. return
  290. }
  291. this.setState({ showDropdownList: !this.state.showDropdownList }, () => {
  292. this.scrollIntoView()
  293. })
  294. }
  295. handleItemClick(item: any) {
  296. if (!this.props.multipleSelection) {
  297. this.setState({ showDropdownList: false, firstItemHover: false })
  298. } else {
  299. let selected = Boolean(this.props.selectedItems && this.props.selectedItems.find(i =>
  300. this.getValue(i) === this.getValue(item)))
  301. this.toggleCheckmarkAnimation(
  302. item,
  303. this.checkmarkRefs[`${this.getLabel(item)}-${this.getValue(item) || ''}`],
  304. selected
  305. )
  306. }
  307. if (this.props.onChange) {
  308. this.props.onChange(item)
  309. }
  310. }
  311. handleItemMouseEnter(index: number) {
  312. if (index === 0) {
  313. this.setState({ firstItemHover: true })
  314. }
  315. }
  316. handleItemMouseLeave(index: number) {
  317. if (index === 0) {
  318. this.setState({ firstItemHover: false })
  319. }
  320. }
  321. toggleCheckmarkAnimation(item: any, checkmarkRef: HTMLElement, selected: boolean) {
  322. if (!item || !checkmarkRef) {
  323. return
  324. }
  325. let symbol = checkmarkRef.querySelector('#symbol')
  326. if (symbol) {
  327. symbol.style.animationName = selected ? 'dashOff' : 'dashOn'
  328. }
  329. }
  330. updateListPosition() {
  331. if (!this.state.showDropdownList || !this.listRef || !this.buttonRef || !document.body) {
  332. return
  333. }
  334. let buttonHeight = this.buttonRef.offsetHeight
  335. let tipHeight = 8
  336. let listTop = this.buttonRect.top + buttonHeight + tipHeight
  337. let listHeight = this.listRef.offsetHeight
  338. if (listTop + listHeight > window.innerHeight) {
  339. listTop = window.innerHeight - listHeight - 16
  340. this.tipRef.style.display = 'none'
  341. } else {
  342. this.tipRef.style.display = 'block'
  343. }
  344. // If a modal is opened, body scroll is removed and body top is set to replicate scroll position
  345. let scrollOffset = 0
  346. if (parseInt(document.body.style.top, 10) < 0) {
  347. scrollOffset = -parseInt(document.body && document.body.style.top, 10)
  348. }
  349. let widthDiff = this.listRef.offsetWidth - this.buttonRef.offsetWidth
  350. this.listRef.style.top = `${listTop + (window.pageYOffset || scrollOffset)}px`
  351. this.listRef.style.left = `${(this.buttonRect.left + window.pageXOffset) - widthDiff}px`
  352. updateTipStyle(this.listItemsRef, this.tipRef, this.firstItemRef)
  353. }
  354. scrollIntoView() {
  355. let itemIndex = this.props.items.findIndex(i => this.getValue(i) === this.getValue(this.props.selectedItem))
  356. scrollItemIntoView(this.listRef, this.listItemsRef, itemIndex)
  357. }
  358. renderList() {
  359. if (!this.props.items || this.props.items.length === 0 || !this.state.showDropdownList) {
  360. return null
  361. }
  362. const body: any = document.body
  363. let selectedValue = this.getValue(this.props.selectedItem)
  364. let duplicatedLabels = []
  365. this.props.items.forEach((item, i) => {
  366. let label = this.getLabel(item)
  367. for (let j = i + 1; j < this.props.items.length; j += 1) {
  368. if (label === this.getLabel(this.props.items[j]) && !duplicatedLabels.find(item2 => this.getLabel(item2) === label)) {
  369. duplicatedLabels.push(label)
  370. }
  371. }
  372. })
  373. const firstItemValue = this.props.items.length > 0 ? this.getValue(this.props.items[0]) : null
  374. const isFirstItemSelected = selectedValue === firstItemValue
  375. let list = ReactDOM.createPortal((
  376. <List {...this.props} innerRef={ref => { this.listRef = ref }}>
  377. <Tip
  378. innerRef={ref => { this.tipRef = ref }}
  379. primary={this.state.firstItemHover || isFirstItemSelected}
  380. dangerouslySetInnerHTML={{ __html: tipImage }}
  381. />
  382. <ListItems innerRef={ref => { this.listItemsRef = ref }}>
  383. {this.props.items.map((item, i) => {
  384. if (item.separator === true) {
  385. return <Separator key={`sep-${i}`} />
  386. }
  387. let label = this.getLabel(item)
  388. let value = this.getValue(item)
  389. let duplicatedLabel = duplicatedLabels.find(l => l === label)
  390. let multipleSelected = this.props.selectedItems && this.props.selectedItems
  391. .find(i => this.getValue(i) === value)
  392. let listItem = (
  393. <ListItem
  394. data-test-id="dropdownListItem"
  395. innerRef={ref => { if (i === 0) { this.firstItemRef = ref } }}
  396. key={value}
  397. onMouseDown={() => { this.itemMouseDown = true }}
  398. onMouseUp={() => { this.itemMouseDown = false }}
  399. onMouseEnter={() => { this.handleItemMouseEnter(i) }}
  400. onMouseLeave={() => { this.handleItemMouseLeave(i) }}
  401. onClick={() => { this.handleItemClick(item) }}
  402. selected={!this.props.multipleSelection && value === selectedValue}
  403. multipleSelected={this.props.multipleSelection && multipleSelected}
  404. dim={this.props.dimFirstItem && i === 0}
  405. paddingLeft={this.props.multipleSelection ? 8 : 16}
  406. >
  407. {this.props.multipleSelection ? (
  408. <Checkmark
  409. innerRef={ref => { this.checkmarkRefs[`${label}-${value || ''}`] = ref }}
  410. dangerouslySetInnerHTML={{ __html: checkmarkImage }}
  411. show={multipleSelected}
  412. />
  413. ) : null}
  414. <Labels>
  415. {label === '' ? '\u00A0' : label}
  416. {duplicatedLabel ? <DuplicatedLabel> (<span>{value || ''}</span>)</DuplicatedLabel> : ''}
  417. </Labels>
  418. </ListItem>
  419. )
  420. return listItem
  421. })}
  422. </ListItems>
  423. </List>
  424. ), body)
  425. return list
  426. }
  427. render() {
  428. let buttonValue = () => {
  429. if (this.props.items && this.props.items.length) {
  430. if (this.props.multipleSelection && this.props.selectedItems && this.props.selectedItems.length > 0) {
  431. return this.props.selectedItems.map(i => this.getLabel(this.props.items.find(item =>
  432. this.getValue(item) === this.getValue(i)))).join(', ')
  433. }
  434. return this.getLabel(this.props.selectedItem)
  435. }
  436. return this.props.noItemsMessage || ''
  437. }
  438. return (
  439. <Wrapper
  440. className={this.props.className}
  441. onMouseDown={() => { this.itemMouseDown = true }}
  442. onMouseUp={() => { this.itemMouseDown = false }}
  443. data-test-id={this.props['data-test-id'] || 'dropdown'}
  444. embedded={this.props.embedded}
  445. >
  446. <DropdownButton
  447. {...this.props}
  448. data-test-id="dropdown-dropdownButton"
  449. innerRef={ref => { this.buttonRef = ref }}
  450. onMouseDown={() => { this.itemMouseDown = true }}
  451. onMouseUp={() => { this.itemMouseDown = false }}
  452. value={buttonValue()}
  453. onClick={() => this.handleButtonClick()}
  454. />
  455. {this.props.required ? <Required disabledLoading={this.props.disabledLoading} /> : null}
  456. {this.renderList()}
  457. </Wrapper>
  458. )
  459. }
  460. }
  461. export default Dropdown