Source: TOC/TOC.js

import React, { useState, useEffect, memo } from 'react';
import styled from 'styled-components';
import shortId from 'shortid';
import sortBy from 'lodash/sortBy';
import capitalize from 'lodash/capitalize';
import isEmpty from 'lodash/isEmpty';
import isEqual from 'lodash/isEqual';

import Grid from '@material-ui/core/Grid';
import Tooltip from '@material-ui/core/Tooltip';
import Fab from '@material-ui/core/Fab';
import RadioGroup from '@material-ui/core/RadioGroup';
import Radio from '@material-ui/core/Radio';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import Switch from '@material-ui/core/Switch';
import Slider from '@material-ui/core/Slider';
import IconButton from '@material-ui/core/IconButton';
import Collapse from '@material-ui/core/Collapse';
import Divider from '@material-ui/core/Divider';
import Container from '@material-ui/core/Container';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemText from '@material-ui/core/ListItemText';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import Chip from '@material-ui/core/Chip';
import DialogTitle from '@material-ui/core/DialogTitle';
import Dialog from '@material-ui/core/Dialog';
import DialogContent from '@material-ui/core/DialogContent';

import ToggleButtonGroup from '@material-ui/lab/ToggleButtonGroup';
import ToggleButton from '@material-ui/lab/ToggleButton';

import CloseIcon from '@material-ui/icons/Close';
import ExpandMoreIcon from '@material-ui/icons/ExpandMore';
import ExpandLessIcon from '@material-ui/icons/ExpandLess';
import VisibilityIcon from '@material-ui/icons/Visibility';
import VisibilityOffIcon from '@material-ui/icons/VisibilityOff';
import SubjectIcon from '@material-ui/icons/Subject';
import HelpOutlineIcon from '@material-ui/icons/HelpOutline';
import DonutLargeIcon from '@material-ui/icons/DonutLarge';
import TerrainIcon from '@material-ui/icons/Terrain';
import InfoOutlinedIcon from '@material-ui/icons/InfoOutlined';
import ColorLensIcon from '@material-ui/icons/ColorLens';
import MapIcon from '@material-ui/icons/Map';
import DomainIcon from '@material-ui/icons/Domain';

import './TOC.css';

const HideButton = styled.div`
	position: absolute;
	top: -19px;
	left: -18px;
`;

const Square = styled.div`
	width: 12px;
	height: 12px;
	border-width: 1px;
	border-style: solid;
	${(props) => props.stroke && `border-color: ${props.stroke};`}
	${(props) => props.fill && `background-color: ${props.fill};`}
`;

const MAP_LABEL_TO_ICON = {
	rgb: <ColorLensIcon />,
	mappe: <MapIcon />,
	fabbricati: <DomainIcon />
};

/**
 * ShowLayerInfo component
 *
 * @param {Object} props
 * @param {Object[]} props.layers
 * @param {Object} props.layerToGetInfo
 */
function ShowLayerInfo({ layers, layerToGetInfo, ...rest }) {
	return (
		<Dialog open {...rest}>
			<DialogTitle>Informazioni livello</DialogTitle>
			<DialogContent>
				<List dense>
					<ListItem disableGutters divider>
						<ListItemIcon>
							<TerrainIcon />
						</ListItemIcon>
						<ListItemText primary={capitalize(layerToGetInfo.get('label'))} secondary='Nome' />
					</ListItem>
					<ListItem disableGutters divider>
						<ListItemIcon>
							<DonutLargeIcon />
						</ListItemIcon>
						<ListItemText primary={layerToGetInfo.values_.type ? layerToGetInfo.get('type').toUpperCase() : 'Non definito'} secondary='Tipologia' />
					</ListItem>
					<ListItem disableGutters divider>
						<ListItemIcon>
							<HelpOutlineIcon />
						</ListItemIcon>
						<ListItemText primary={layerToGetInfo.get('canGetInfo') ? 'Si' : 'No'} secondary='Interrogabile' />
					</ListItem>
					<ListItem disableGutters>
						<ListItemIcon>
							<SubjectIcon />
						</ListItemIcon>
						<ListItemText primary={layers && layers.filter((l) => l.get('idParent') === layer.ol_uid).length} secondary='Sottolivelli' />
					</ListItem>
				</List>
			</DialogContent>
		</Dialog>
	);
}

/**
 * TOC component
 *
 * @param {Object} props
 * @param {string} props.className
 * @param {Object[]} props.layers
 * @param {Object} props.layerToInteraction
 * @param {function} props.onChangeLayerToInteraction
 * @param {function} props.onChangeLayerVisibility
 * @param {function} props.onChangeOpacity
 * @param {boolean} props.layerSelectable
 * @param {function} props.onClose
 */
function TOC({ className, layers, layerToInteraction, onChangeLayerToInteraction, onChangeLayerVisibility, onChangeOpacity, onClose }) {
	const [layersToIterate, changeLayersToIterate] = useState([]);
	const [layerExpanded, changeLayerExpanded] = useState(null);
	const [layerToGetInfo, changeLayerToGetInfo] = useState(false);

	let mutuallyExclusiveLayers = [];
	let mutuallyInclusiveLayers = [];
	let mutuallyExclusiveVisibleLayer;

	useEffect(() => {
		if (!isEqual(layersToIterate, layers)) {
			changeLayersToIterate(layers);
		}
	}, [layers]);

	if (!isEmpty(layersToIterate)) {
		const orderedLayers = sortBy(layersToIterate, (l) => l.getZIndex());

		mutuallyExclusiveLayers = orderedLayers.filter((l) => l.get('mutuallyExclusive'));
		mutuallyInclusiveLayers = orderedLayers.filter((l) => !l.get('mutuallyExclusive') && l.get('label') && l.get('isRoot'));
		mutuallyExclusiveVisibleLayer = mutuallyExclusiveLayers.find((l) => l.getVisible());
	}

	const onChangeLayerExpanded = (layerId) => {
		if (layerExpanded === layerId) {
			changeLayerExpanded(null);
			return;
		}

		changeLayerExpanded(layerId);
	};

	return (
		<>
			<div className={className}>
				{onClose && (
					<HideButton>
						<Tooltip placement='left' title='Nascondi'>
							<Fab size='small' onClick={onClose}>
								<CloseIcon />
							</Fab>
						</Tooltip>
					</HideButton>
				)}

				<Grid container direction='column' spacing={3}>
					<Grid item container justify='center'>
						<Grid item>
							<ToggleButtonGroup value={mutuallyExclusiveVisibleLayer && mutuallyExclusiveVisibleLayer.ol_uid} exclusive>
								{mutuallyExclusiveLayers.map((layer) => (
									<ToggleButton key={layer.ol_uid} value={layer.ol_uid} onClick={() => onChangeLayerVisibility(layer, true)}>
										{layer.get('icon') || MAP_LABEL_TO_ICON[layer.get('label')] || layer.get('label')}
									</ToggleButton>
								))}
							</ToggleButtonGroup>
						</Grid>
					</Grid>

					{!isEmpty(mutuallyInclusiveLayers) && (
						<Grid item>
							<RadioGroup value={layerToInteraction && layerToInteraction.ol_uid} onChange={(_, value) => onChangeLayerToInteraction(value)}>
								<Grid item container direction='column' spacing={2}>
									{mutuallyInclusiveLayers.map((layer, i) => {
										const isVisible = layer.getVisible();
										const opacity = layer.getOpacity();
										const canGetInfo = layer.get('canGetInfo');
										const canShowDetails = layerExpanded === layer.ol_uid;
										const isLastElement = mutuallyInclusiveLayers.length - 1 === i;
										const isLayerActive = layerToInteraction && layerToInteraction.ol_uid === layer.ol_uid;
										const subLayers = layersToIterate.filter((l) => l.get('idParent') === layer.ol_uid);

										return (
											<React.Fragment key={layer.ol_uid}>
												<Grid item container spacing={2} justify='space-between' alignItems='center'>
													<Grid item>
														<Tooltip placement='top' title={`${isVisible ? 'Nascondi' : 'Mostra'} livello ${layer.get('label')}`}>
															<FormControlLabel
																control={
																	<>
																		<Switch
																			checked={isVisible}
																			onChange={() => {
																				onChangeLayerVisibility(layer, !isVisible);

																				if (!isEmpty(subLayers)) {
																					subLayers.forEach((subLayer) => onChangeLayerVisibility(subLayer, !isVisible));
																				}
																			}}
																			color='primary'
																		/>
																		{isEmpty(subLayers) && !isEmpty(layer.get('legend')) ? (
																			layer.get('legend').map((legend) => <Square key={shortId.generate()} fill={legend.fill} stroke={legend.stroke} />)
																		) : (
																			<Square fill='white' stroke='white' />
																		)}
																	</>
																}
																label={<div className='p-l-16'>{layer.get('label')}</div>}
															/>
														</Tooltip>
													</Grid>
													<Grid item>
														<Grid container spacing={0} alignItems='center'>
															{layer.get('canShowLayerResume') && (
																<Grid item>
																	<Tooltip placement='top' title='Visualizza informazioni'>
																		<IconButton onClick={() => changeLayerToGetInfo(layer)}>
																			<InfoOutlinedIcon fontSize='small' />
																		</IconButton>
																	</Tooltip>
																</Grid>
															)}
															<Grid item>
																<Tooltip placement='top' title={`${canShowDetails ? 'Chiudi' : 'Apri'} sottomenu`}>
																	<IconButton onClick={() => onChangeLayerExpanded(layer.ol_uid)}>
																		{canShowDetails ? <ExpandLessIcon fontSize='small' /> : <ExpandMoreIcon fontSize='small' />}
																	</IconButton>
																</Tooltip>
															</Grid>
														</Grid>
													</Grid>
												</Grid>
												<Collapse in={canShowDetails}>
													<Container maxWidth='md'>
														<Grid container spacing={1} direction='column'>
															{onChangeOpacity && (
																<Grid item container spacing={2} alignItems='center'>
																	<Grid item>
																		<VisibilityOffIcon
																			style={{
																				color: 'rgba(0, 0, 0, 0.54)'
																			}}
																		/>
																	</Grid>
																	<Grid item xs>
																		<Slider
																			disabled={!isVisible}
																			defaultValue={0}
																			value={opacity}
																			step={0.1}
																			min={0}
																			max={1}
																			onChange={(e, value) => {
																				onChangeOpacity(layer, value);

																				if (!isEmpty(subLayers)) {
																					subLayers.forEach((subLayer) => onChangeOpacity(subLayer, value));
																				}
																			}}
																			valueLabelFormat={(value) => `${value * 100}%`}
																			marks
																		/>
																	</Grid>
																	<Grid item>
																		<VisibilityIcon
																			style={{
																				color: 'rgba(0, 0, 0, 0.54)'
																			}}
																		/>
																	</Grid>
																</Grid>
															)}
															{canGetInfo && (
																<Grid item>
																	<FormControlLabel control={<Radio disabled={!isVisible} value={layer.ol_uid} />} label={isLayerActive ? 'Livello attivo' : 'Livello disattivo'} />
																</Grid>
															)}

															{!isEmpty(subLayers) && (
																<Grid item container direction='column' spacing={2} style={{ marginBottom: 16 }}>
																	{subLayers.map((subLayer) => {
																		const isSubLayerVisible = subLayer.getVisible();

																		return (
																			<Grid item xs key={subLayer.ol_uid}>
																				<Grid container spacing={1} alignItems='center'>
																					{!isEmpty(subLayer.get('legend')) &&
																						subLayer.get('legend').map((legend) => (
																							<Grid item key={shortId.generate()}>
																								<Square fill={legend.fill} stroke={legend.stroke} />
																							</Grid>
																						))}
																					<Grid item xs>
																						<Chip
																							style={{ width: '100%' }}
																							icon={<TerrainIcon />}
																							label={subLayer.get('label')}
																							onClick={() => {
																								onChangeLayerVisibility(subLayer, !isSubLayerVisible);
																							}}
																							color={isSubLayerVisible ? 'primary' : 'default'}
																							clickable
																						/>
																					</Grid>
																				</Grid>
																			</Grid>
																		);
																	})}
																</Grid>
															)}
														</Grid>
													</Container>
												</Collapse>
												{!isLastElement && <Divider variant='middle' />}
											</React.Fragment>
										);
									})}
								</Grid>
							</RadioGroup>
						</Grid>
					)}
				</Grid>
			</div>

			{layerToGetInfo && <ShowLayerInfo layers={layersToIterate} layerToGetInfo={layerToGetInfo} onClose={() => changeLayerToGetInfo(null)} />}
		</>
	);
}

TOC.defaultProps = {
	fromTop: 0,
	fromRight: 0
};

export default memo(TOC);