|
| 1 | +import React from 'react'; |
| 2 | +import classNames from 'classnames'; |
| 3 | +import noop from 'lodash/noop'; |
| 4 | +import DrawingTarget from './DrawingTarget'; |
| 5 | +import useOutsideEvent from '../common/useOutsideEvent'; |
| 6 | +import { AnnotationDrawing } from '../@types'; |
| 7 | +import { checkValue } from '../utils/util'; |
| 8 | +import { getShape } from './drawingUtil'; |
| 9 | + |
| 10 | +export type Props = { |
| 11 | + activeId?: string | null; |
| 12 | + annotations: AnnotationDrawing[]; |
| 13 | + className?: string; |
| 14 | + onSelect?: (annotationId: string | null) => void; |
| 15 | +}; |
| 16 | + |
| 17 | +export function filterDrawing({ target: { path_groups: pathGroups } }: AnnotationDrawing): boolean { |
| 18 | + return pathGroups.every(({ paths }) => |
| 19 | + paths.every(({ points }) => points.every(({ x, y }) => checkValue(x) && checkValue(y))), |
| 20 | + ); |
| 21 | +} |
| 22 | + |
| 23 | +export function sortDrawing({ target: targetA }: AnnotationDrawing, { target: targetB }: AnnotationDrawing): number { |
| 24 | + const { height: heightA, width: widthA } = getShape(targetA.path_groups); |
| 25 | + const { height: heightB, width: widthB } = getShape(targetB.path_groups); |
| 26 | + |
| 27 | + // If B is smaller, the result is negative. |
| 28 | + // So, A is sorted to an index lower than B, which means A will be rendered first at bottom |
| 29 | + return heightB * widthB - heightA * widthA; |
| 30 | +} |
| 31 | + |
| 32 | +export function DrawingList({ activeId = null, annotations, className, onSelect = noop }: Props): JSX.Element { |
| 33 | + const [isListening, setIsListening] = React.useState(true); |
| 34 | + const rootElRef = React.createRef<SVGSVGElement>(); |
| 35 | + |
| 36 | + // Document-level event handlers for focus and pointer control |
| 37 | + useOutsideEvent('mousedown', rootElRef, (): void => { |
| 38 | + onSelect(null); |
| 39 | + setIsListening(false); |
| 40 | + }); |
| 41 | + useOutsideEvent('mouseup', rootElRef, (): void => setIsListening(true)); |
| 42 | + |
| 43 | + return ( |
| 44 | + <svg |
| 45 | + ref={rootElRef} |
| 46 | + className={classNames(className, { 'is-listening': isListening })} |
| 47 | + data-resin-component="drawingList" |
| 48 | + preserveAspectRatio="none" |
| 49 | + viewBox="0 0 100 100" |
| 50 | + > |
| 51 | + {annotations |
| 52 | + .filter(filterDrawing) |
| 53 | + .sort(sortDrawing) |
| 54 | + .map(({ id, target }) => ( |
| 55 | + <DrawingTarget |
| 56 | + key={id} |
| 57 | + annotationId={id} |
| 58 | + isActive={activeId === id} |
| 59 | + onSelect={onSelect} |
| 60 | + target={target} |
| 61 | + /> |
| 62 | + ))} |
| 63 | + </svg> |
| 64 | + ); |
| 65 | +} |
| 66 | + |
| 67 | +export default React.memo(DrawingList); |
0 commit comments