UNPKG

labo-components

Version:
107 lines (89 loc) 3.33 kB
import React from "react"; import PropTypes from "prop-types"; import IDUtil from "../../../util/IDUtil"; import { ResourceViewerContext } from "../ResourceViewerContext"; import { getAnnotationsPerType } from "../AnnotationHelpers"; import { CLASSIFICATION } from "../../../util/AnnotationConstants"; import Strings from "../_Strings"; import Classification from "./Types/Classification"; export default class ClassificationSelector extends React.PureComponent { static contextType = ResourceViewerContext; constructor(props) { super(props); } componentDidMount() { document.addEventListener("click", this.close); } componentWillUnmount() { document.removeEventListener("click", this.close); } close = (e) => { if (!e.shiftKey) { this.props.onClose(); } }; // /* ---------------------------------- RENDER FUNCTIONS -------------------------------- */ getClassifications(annotations) { // create a list of all unique classifications in the project const classifications = {}; annotations.forEach((annotation) => { getAnnotationsPerType([CLASSIFICATION], annotation)[ CLASSIFICATION ].forEach((classification) => { classifications[classification.id] = classification; }); }); // return classification list, sorted by label for convenience return Object.values(classifications).sort((a, b) => a.label.toLowerCase() == b.label.toLowerCase() ? 0 : a.label.toLowerCase() > b.label.toLowerCase() ? 1 : -1 ); } // Select a classification from the list onSelect = (classification, shiftKey) => { this.props.onSelect(classification); if (!shiftKey) { this.props.onClose(); } else { this.forceUpdate(); } }; render() { // get all classifications in the total project: const annotations = this.context.annotationClient.annotations; const classifications = this.getClassifications(annotations); // get active classifications const activeAnnotation = this.props.activeAnnotation; const activeClassifications = {}; this.getClassifications([activeAnnotation]).forEach( (classification) => { activeClassifications[classification.id] = true; } ); const list = classifications.map((classification) => ( <Classification key={classification.id} className={ classification.id in activeClassifications ? "active" : "" } classification={classification} click={this.onSelect} /> )); return ( <div className={IDUtil.cssClassName("classification-selector")}> {list.length ? list : Strings.ANNOTATION_TYPE_CLASSIFICATION_CURRENT_EMPTY} </div> ); } } ClassificationSelector.propTypes = { activeAnnotation: PropTypes.object.isRequired, onClose: PropTypes.func.isRequired, onSelect: PropTypes.func.isRequired, };