import React, { Component } from 'react'
import PropTypes from 'prop-types'
import MenyStyled from './menu.styled'
import { MenuItem, NormalizeMenuItems } from './menu-item'
class Menu extends Component {
constructor(props) {
super(props)
this.state = {
items: props.items,
}
}
componentWillReceiveProps (nextProps) {
this.setState({
items: nextProps.items,
})
}
onSelectMenu = (menu, parentIndex, ownIndex) => {
const { onSelectMenu } = this.props
this.updateSelected(parentIndex, ownIndex).then(() => {
onSelectMenu && onSelectMenu(menu)
})
}
updateSelected = (parentIndex, ownIndex) => {
const { items } = this.state
return new Promise((resolve) => {
const listItems = items.map((item, index) => {
const parentMatch = (index === parentIndex);
return {
...item,
active: parentMatch,
opened: parentMatch && item.items,
items: item.items && item.items.map((subItem, subMenuIndex) => ({
...subItem,
active: (parentMatch && subMenuIndex === ownIndex),
}))
}
})
this.setState({ items: listItems }, () => {
resolve()
})
})
}
onToggleMenu = (menu, parentIndex, ownIndex) => {
const { onToggleMenu } = this.props
this.updateSelected(parentIndex, ownIndex).then(() => {
onToggleMenu && onToggleMenu(menu)
})
}
itemIsActive = (item) => {
const { activeItem } = this.props
if (item.active !== undefined)
return item.active
let hasActiveChildren = false
if (item.items && item.items.length > 0) {
//possui filhos
//se algum filho for ativo deve ativar o pai tambem
hasActiveChildren = item.items.filter(this.itemIsActive).length > 0
}
return (activeItem !== null) ? (item.key === activeItem) || hasActiveChildren : false
}
normalizeItens = () => {
const { prefix, activeItem } = this.props
const { items } = this.state
return (
items.map((item, index) => {
item.active = this.itemIsActive(item)
return NormalizeMenuItems(item, prefix, this.onSelectMenu, this.onToggleMenu, index)
})
)
}
render () {
const { width = '196px', items = [], children } = this.props
return (
<MenyStyled width={width}>
{items && items.length > 0 && this.normalizeItens()}
{(!items || items.length == 0) && (children && children.length > 0) && children}
</MenyStyled>
)
}
}
Menu.propTypes = {
children: PropTypes.node,
width: PropTypes.string,
items: PropTypes.array,
activeItem: PropTypes.string
}
export { MenuItem }
export { Menu }
|