From 2e345c1ebd498e3f7e088e6fc3e1ca17082b23c1 Mon Sep 17 00:00:00 2001
From: bobzel <zzzman@gmail.com>
Date: Mon, 26 Aug 2024 13:53:26 -0400
Subject: converted unique faces to be a Doc type similar to a collection.

---
 .../collectionFreeForm/FaceCollectionBox.tsx       | 113 +++++++++++++--------
 1 file changed, 68 insertions(+), 45 deletions(-)

(limited to 'src/client/views/collections/collectionFreeForm/FaceCollectionBox.tsx')

diff --git a/src/client/views/collections/collectionFreeForm/FaceCollectionBox.tsx b/src/client/views/collections/collectionFreeForm/FaceCollectionBox.tsx
index 1cc1f59dc..6a0d51e32 100644
--- a/src/client/views/collections/collectionFreeForm/FaceCollectionBox.tsx
+++ b/src/client/views/collections/collectionFreeForm/FaceCollectionBox.tsx
@@ -6,23 +6,21 @@ import 'ldrs/ring';
 import { action, makeObservable, observable } from 'mobx';
 import { observer } from 'mobx-react';
 import React from 'react';
-import { setupMoveUpEvents } from '../../../../ClientUtils';
-import { Utils, emptyFunction } from '../../../../Utils';
+import { lightOrDark, returnTrue, setupMoveUpEvents } from '../../../../ClientUtils';
+import { emptyFunction } from '../../../../Utils';
 import { Doc, Opt } from '../../../../fields/Doc';
-import { Id } from '../../../../fields/FieldSymbols';
 import { List } from '../../../../fields/List';
-import { ImageCast } from '../../../../fields/Types';
+import { ImageCast, StrCast } from '../../../../fields/Types';
 import { DocumentType } from '../../../documents/DocumentTypes';
 import { Docs } from '../../../documents/Documents';
 import { DragManager } from '../../../util/DragManager';
 import { dropActionType } from '../../../util/DropActionTypes';
-import { SnappingManager } from '../../../util/SnappingManager';
 import { undoable } from '../../../util/UndoManager';
 import { ViewBoxBaseComponent } from '../../DocComponent';
-import { ObservableReactComponent } from '../../ObservableReactComponent';
 import { DocumentView } from '../../nodes/DocumentView';
 import { FieldView, FieldViewProps } from '../../nodes/FieldView';
 import { FaceRecognitionHandler } from '../../search/FaceRecognitionHandler';
+import { CollectionStackingView } from '../CollectionStackingView';
 import './FaceCollectionBox.scss';
 import { MarqueeOptionsMenu } from './MarqueeOptionsMenu';
 
@@ -31,31 +29,29 @@ import { MarqueeOptionsMenu } from './MarqueeOptionsMenu';
  * unique face in turn displays the set of images that correspond to the face.
  */
 
-interface UniqueFaceProps {
-    faceDoc: Doc;
-}
-
 /**
- * React component for rendering a unique face and its collection of image Docs.
+ * Viewer for unique face Doc collections.
  *
  * This both displays a collection of images corresponding tp a unique face, and
  * allows for editing the face collection by removing an image, or drag-and-dropping
  * an image that was not recognized.
  */
 @observer
-export class UniqueFaceView extends ObservableReactComponent<UniqueFaceProps> {
+export class UniqueFaceBox extends ViewBoxBaseComponent<FieldViewProps>() {
+    public static LayoutString(fieldKey: string) {
+        return FieldView.LayoutString(UniqueFaceBox, fieldKey);
+    }
     private _dropDisposer?: DragManager.DragDropDisposer;
+    private _oldWheel: HTMLElement | null = null;
 
-    constructor(props: UniqueFaceProps) {
+    constructor(props: FieldViewProps) {
         super(props);
         makeObservable(this);
     }
 
-    @observable _displayImages: boolean = true;
-
     protected createDropTarget = (ele: HTMLDivElement) => {
         this._dropDisposer?.();
-        ele && (this._dropDisposer = DragManager.MakeDropTarget(ele, this.onInternalDrop.bind(this), this._props.faceDoc));
+        ele && (this._dropDisposer = DragManager.MakeDropTarget(ele, this.onInternalDrop.bind(this), this._props.Document));
     };
 
     protected onInternalDrop(e: Event, de: DragManager.DropEvent): boolean {
@@ -63,12 +59,12 @@ export class UniqueFaceView extends ObservableReactComponent<UniqueFaceProps> {
             ?.filter(doc => doc.type === DocumentType.IMG)
             .forEach(imgDoc => {
                 // If the current Face Document has no faces, and the doc has more than one face descriptor, don't let the user add the document first.  Or should we just use the first face ?
-                if (FaceRecognitionHandler.UniqueFaceDescriptors(this._props.faceDoc).length === 0 && FaceRecognitionHandler.ImageDocFaceDescriptors(imgDoc).length > 1) {
+                if (FaceRecognitionHandler.UniqueFaceDescriptors(this._props.Document).length === 0 && FaceRecognitionHandler.ImageDocFaceDescriptors(imgDoc).length > 1) {
                     alert('Cannot add a document with multiple faces as the first item!');
                 } else {
                     // Loop through the documents' face descriptors and choose the face in the iage with the smallest distance (most similar to the face colleciton)
-                    const faceDescriptorsAsFloat32Array = FaceRecognitionHandler.UniqueFaceDescriptors(this._props.faceDoc).map(fd => new Float32Array(Array.from(fd)));
-                    const labeledFaceDescriptor = new faceapi.LabeledFaceDescriptors(FaceRecognitionHandler.UniqueFaceLabel(this._props.faceDoc), faceDescriptorsAsFloat32Array);
+                    const faceDescriptorsAsFloat32Array = FaceRecognitionHandler.UniqueFaceDescriptors(this._props.Document).map(fd => new Float32Array(Array.from(fd)));
+                    const labeledFaceDescriptor = new faceapi.LabeledFaceDescriptors(FaceRecognitionHandler.UniqueFaceLabel(this._props.Document), faceDescriptorsAsFloat32Array);
                     const faceMatcher = new FaceMatcher([labeledFaceDescriptor], 1);
                     const { face_match } = FaceRecognitionHandler.ImageDocFaceDescriptors(imgDoc).reduce(
                         (prev, face) => {
@@ -80,11 +76,12 @@ export class UniqueFaceView extends ObservableReactComponent<UniqueFaceProps> {
 
                     // assign the face in the image that's closest to the face collection to be the face that's assigned to the collection
                     if (face_match) {
-                        FaceRecognitionHandler.UniqueFaceAddFaceImage(imgDoc, face_match, this._props.faceDoc);
+                        FaceRecognitionHandler.UniqueFaceAddFaceImage(imgDoc, face_match, this._props.Document);
                     }
                 }
             });
-        return false;
+        e.stopPropagation();
+        return true;
     }
 
     /**
@@ -92,14 +89,15 @@ export class UniqueFaceView extends ObservableReactComponent<UniqueFaceProps> {
      */
     @action
     onDisplayClick() {
-        this._displayImages = !this._displayImages;
+        this._props.Document._displayImages = !this.props.Document._displayImages;
+        this._props.Document.height = this._props.Document._displayImages ? 400 : 100;
     }
 
     /**
      * Removes a unique face Doc from the colelction of unique faces.
      */
     deleteUniqueFace = undoable(() => {
-        FaceRecognitionHandler.DeleteUniqueFace(this._props.faceDoc);
+        FaceRecognitionHandler.DeleteUniqueFace(this._props.Document);
     }, 'delete face');
 
     /**
@@ -107,9 +105,11 @@ export class UniqueFaceView extends ObservableReactComponent<UniqueFaceProps> {
      * @param imgDoc - image Doc to remove
      */
     removeFaceImageFromUniqueFace = undoable((imgDoc: Doc) => {
-        FaceRecognitionHandler.UniqueFaceRemoveFaceImage(imgDoc, this._props.faceDoc);
+        FaceRecognitionHandler.UniqueFaceRemoveFaceImage(imgDoc, this._props.Document);
     }, 'remove doc from face');
 
+    onPassiveWheel = (e: WheelEvent) => e.stopPropagation();
+
     render() {
         return (
             <div className="face-document-item" ref={ele => this.createDropTarget(ele!)}>
@@ -117,23 +117,35 @@ export class UniqueFaceView extends ObservableReactComponent<UniqueFaceProps> {
                     <IconButton tooltip="Delete Face From Collection" onPointerDown={this.deleteUniqueFace} icon={'x'} style={{ width: '4px' }} size={Size.XSMALL} />
                 </div>
                 <div className="face-document-top">
-                    <h1>{FaceRecognitionHandler.UniqueFaceLabel(this._props.faceDoc)}</h1>
+                    <h1 style={{ color: lightOrDark(StrCast(this._props.Document.backgroundColor)) }}>{FaceRecognitionHandler.UniqueFaceLabel(this._props.Document)}</h1>
                 </div>
-                <IconButton
-                    tooltip="See image information"
-                    onPointerDown={() => this.onDisplayClick()}
-                    icon={<FontAwesomeIcon icon={this._displayImages ? 'caret-up' : 'caret-down'} />}
-                    color={MarqueeOptionsMenu.Instance.userColor}
-                    style={{ width: '19px' }}
-                />
-                {this._displayImages ? (
-                    <div className="face-document-image-container">
-                        {FaceRecognitionHandler.UniqueFaceImages(this._props.faceDoc).map(doc => {
+                <div className="face-collection-toggle">
+                    <IconButton
+                        tooltip="See image information"
+                        onPointerDown={() => this.onDisplayClick()}
+                        icon={<FontAwesomeIcon icon={this._props.Document._displayImages ? 'caret-up' : 'caret-down'} />}
+                        color={MarqueeOptionsMenu.Instance.userColor}
+                        style={{ width: '19px' }}
+                    />
+                </div>
+                {this.props.Document._displayImages ? (
+                    <div
+                        className="face-document-image-container"
+                        style={{
+                            pointerEvents: this._props.isContentActive() ? undefined : 'none',
+                        }}
+                        ref={ele => {
+                            this._oldWheel?.removeEventListener('wheel', this.onPassiveWheel);
+                            this._oldWheel = ele;
+                            // prevent wheel events from passively propagating up through containers and prevents containers from preventDefault which would block scrolling
+                            ele?.addEventListener('wheel', this.onPassiveWheel, { passive: false });
+                        }}>
+                        {FaceRecognitionHandler.UniqueFaceImages(this._props.Document).map((doc, i) => {
                             const [name, type] = ImageCast(doc[Doc.LayoutFieldKey(doc)]).url.href.split('.');
                             return (
                                 <div
                                     className="image-wrapper"
-                                    key={Utils.GenerateGuid()}
+                                    key={i}
                                     onPointerDown={e =>
                                         setupMoveUpEvents(
                                             this,
@@ -165,8 +177,8 @@ export class UniqueFaceView extends ObservableReactComponent<UniqueFaceProps> {
  *
  * Since the collection of recognized faces is stored on the active dashboard, this class
  * does not itself store any Docs, but accesses the myUniqueFaces field of the current
- * dashboard.  Each Face collection Doc is rendered using a FaceCollectionDocView which
- * is not a CollectionView or even a DocumentView (but probably should be).
+ * dashboard.  (This should probably go away as Doc type in favor of it just being a
+ * stacking collection of uniqueFace docs)
  */
 @observer
 export class FaceCollectionBox extends ViewBoxBaseComponent<FieldViewProps>() {
@@ -179,18 +191,29 @@ export class FaceCollectionBox extends ViewBoxBaseComponent<FieldViewProps>() {
         makeObservable(this);
     }
 
+    moveDocument = (doc: Doc | Doc[], targetCollection: Doc | undefined, addDocument: (doc: Doc | Doc[]) => boolean): boolean => !!(this._props.removeDocument?.(doc) && addDocument?.(doc));
+
     render() {
-        return (
-            <div className="searchBox-container" style={{ pointerEvents: 'all', color: SnappingManager.userColor, background: SnappingManager.userBackgroundColor }}>
-                {FaceRecognitionHandler.UniqueFaces().map(doc => (
-                    <UniqueFaceView key={doc[Id]} faceDoc={doc} />
-                ))}
-            </div>
+        return !Doc.ActiveDashboard ? null : (
+            <CollectionStackingView
+                {...this._props} //
+                Document={Doc.ActiveDashboard}
+                fieldKey="myUniqueFaces"
+                moveDocument={this.moveDocument}
+                isContentActive={returnTrue}
+                isAnyChildContentActive={returnTrue}
+                childHideDecorations={true}
+            />
         );
     }
 }
 
 Docs.Prototypes.TemplateMap.set(DocumentType.FACECOLLECTION, {
     layout: { view: FaceCollectionBox, dataField: 'data' },
-    options: { acl: '', _width: 400 },
+    options: { acl: '', _width: 400, dropAction: dropActionType.embed },
+});
+
+Docs.Prototypes.TemplateMap.set(DocumentType.UFACE, {
+    layout: { view: UniqueFaceBox, dataField: 'face_images' },
+    options: { acl: '', _width: 400, _height: 400 },
 });
-- 
cgit v1.2.3-70-g09d2

