All files / app/codeCharta/ui/codeMap codeMap.mouseEvent.service.ts

90.04% Statements 217/241
83.03% Branches 93/112
83.33% Functions 35/42
91.88% Lines 215/234

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 45720x 20x   20x   20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x             20x 20x 20x     20x 20x 20x 20x 20x       20x 87x       87x 87x 87x 87x 87x 87x 87x 87x 87x     24x       48x           24x     24x               87x 87x 87x 87x 87x 87x 87x 87x 87x       24x 72x         121x       1x 1x 1x 1x 1x 1x 1x       1x                                     24x 24x     87x 4x   1x 1x   1x 1x   1x 1x   1x 1x         25x 25x 25x       52x 52x 52x 3x   3x 2x     52x       24x 24x   24x 10x 10x 10x 10x     14x 14x   14x   14x 14x   14x 14x 14x   14x       14x   14x         14x         14x 14x   14x 11x   11x 11x 11x 4x 4x               4x   4x 4x         6x 6x   6x 6x 6x   6x       7x 7x 1x   7x       7x   7x 7x 7x   7x 7x       105x 3x 3x         5x 1x 1x         2x 2x       1x       1x 1x       87x 14x 14x 14x 14x       5x 5x     5x 5x 3x   5x 3x 3x 3x 3x           11x 5x 5x   11x 5x 5x   11x 11x       11x 11x 8x   3x   11x 4x   7x         14x   14x                       14x       3x     3x 1x                   3x       10x 10x 9x 5x 5x   4x 4x   9x   10x       11x             27x       117x       5x   5x 5x 5x 5x 5x 5x     5x 5x 5x               10x   10x 10x 10x 10x 10x       89x 89x     89x 1x   88x     89x 65x        
import { Injectable, OnDestroy } from "@angular/core"
import { ThreeCameraService } from "./threeViewer/threeCamera.service"
import { CodeMapBuilding } from "./rendering/codeMapBuilding"
import { ViewCubeMouseEventsService } from "../viewCube/viewCube.mouseEvents.service"
import { BlacklistItem, CcState } from "../../codeCharta.model"
import { ThreeSceneService } from "./threeViewer/threeSceneService"
import { ThreeRendererService } from "./threeViewer/threeRenderer.service"
import { isPathHiddenOrExcluded } from "../../util/codeMapHelper"
import { hierarchy } from "d3-hierarchy"
import { Intersection, Object3D, Raycaster, Vector2 } from "three"
import { CodeMapLabelService } from "./codeMap.label.service"
import { ThreeViewerService } from "./threeViewer/threeViewer.service"
import { setHoveredNodeId } from "../../state/store/appStatus/hoveredNodeId/hoveredNodeId.actions"
import { setRightClickedNodeData } from "../../state/store/appStatus/rightClickedNodeData/rightClickedNodeData.actions"
import { idToNodeSelector } from "../../state/selectors/accumulatedData/idToNode.selector"
import { IdToBuildingService } from "../../services/idToBuilding/idToBuilding.service"
import { hoveredNodeIdSelector } from "../../state/store/appStatus/hoveredNodeId/hoveredNodeId.selector"
import { tap } from "rxjs"
import { visibleFileStatesSelector } from "../../state/selectors/visibleFileStates/visibleFileStates.selector"
import { blacklistSelector } from "../../state/store/fileSettings/blacklist/blacklist.selector"
import { debounce } from "../../util/debounce"
import { Store, State } from "@ngrx/store"
 
interface Coordinates {
    x: number
    y: number
}
 
export enum ClickType {
    LeftClick = 0,
    RightClick = 2
}
 
export enum CursorType {
    Default = "default",
    Grabbing = "grabbing",
    Pointer = "pointer",
    Moving = "move"
}
 
@Injectable({ providedIn: "root" })
export class CodeMapMouseEventService implements OnDestroy {
    private readonly THRESHOLD_FOR_MOUSE_MOVEMENT_TRACKING = 3
 
    private intersectedBuilding: CodeMapBuilding
 
    private mouse: Coordinates = { x: 0, y: 0 }
    private oldMouse: Coordinates = { x: 0, y: 0 }
    private mouseOnLastClick: Coordinates = { x: 0, y: 0 }
    private isGrabbing = false
    private isMoving = false
    private raycaster = new Raycaster()
    private labelHoveredBuilding = null
    private labelSelectedBuilding = null
    private subscriptions = [
        this.store
            .select(visibleFileStatesSelector)
            .pipe(tap(() => this.onFilesSelectionChanged()))
            .subscribe(),
        this.store
            .select(blacklistSelector)
            .pipe(tap(blacklist => this.onBlacklistChanged(blacklist)))
            .subscribe(),
        this.store
            .select(hoveredNodeIdSelector)
            .pipe(
                tap(hoveredNodeId => {
                    Iif (hoveredNodeId !== null) {
                        this.hoverNode(hoveredNodeId)
                    } else {
                        this.unhoverNode(false)
                    }
                })
            )
            .subscribe()
    ]
 
    constructor(
        private threeCameraService: ThreeCameraService,
        private threeRendererService: ThreeRendererService,
        private threeSceneService: ThreeSceneService,
        private store: Store<CcState>,
        private state: State<CcState>,
        private codeMapLabelService: CodeMapLabelService,
        private viewCubeMouseEvents: ViewCubeMouseEventsService,
        private threeViewerService: ThreeViewerService,
        private idToBuilding: IdToBuildingService
    ) {}
 
    ngOnDestroy(): void {
        for (const subscription of this.subscriptions) {
            subscription.unsubscribe()
        }
    }
 
    static changeCursorIndicator(cursorIcon: CursorType) {
        document.body.style.cursor = cursorIcon
    }
 
    start() {
        this.threeRendererService.renderer.domElement.addEventListener("mousemove", debounce(this.onDocumentMouseMove, 1))
        this.threeRendererService.renderer.domElement.addEventListener("mouseup", event => this.onDocumentMouseUp(event))
        this.threeRendererService.renderer.domElement.addEventListener("mousedown", event => this.onDocumentMouseDown(event))
        this.threeRendererService.renderer.domElement.addEventListener("dblclick", () => this.onDocumentDoubleClick())
        this.threeRendererService.renderer.domElement.addEventListener("mouseleave", event => this.onDocumentMouseLeave(event))
        this.threeRendererService.renderer.domElement.addEventListener("mouseenter", () => this.onDocumentMouseEnter())
        this.threeRendererService.renderer.domElement.addEventListener(
            "wheel",
            debounce(() => this.threeRendererService.render())
        )
        this.viewCubeMouseEvents.subscribe("viewCubeEventPropagation", this.onViewCubeEventPropagation)
    }
 
    hoverNode(id: number) {
        Iif (this.isGrabbingOrMoving()) {
            return
        }
 
        const { buildings } = this.threeSceneService.getMapMesh().getMeshDescription()
        for (const building of buildings) {
            Iif (building.node.id === id) {
                this.hoverBuilding(building, false)
                break
            }
        }
        this.threeRendererService.render()
    }
 
    unhoverNode(updateStore = true) {
        this.unhoverBuilding(updateStore)
        this.threeRendererService.render()
    }
 
    onViewCubeEventPropagation = (data: { type: string; event: MouseEvent }) => {
        switch (data.type) {
            case "mousemove":
                this.onDocumentMouseMove(data.event)
                break
            case "mouseup":
                this.onDocumentMouseUp(data.event)
                break
            case "mousedown":
                this.onDocumentMouseDown(data.event)
                break
            case "dblclick":
                this.onDocumentDoubleClick()
                break
        }
    }
 
    onFilesSelectionChanged() {
        this.threeSceneService.clearSelection()
        this.threeSceneService.clearConstantHighlight()
        this.clearLabelHoveredBuilding()
    }
 
    onBlacklistChanged(blacklist: BlacklistItem[]) {
        const selectedBuilding = this.threeSceneService.getSelectedBuilding()
        this.clearLabelHoveredBuilding()
        if (selectedBuilding) {
            const isSelectedBuildingBlacklisted = isPathHiddenOrExcluded(selectedBuilding.node.path, blacklist)
 
            if (isSelectedBuildingBlacklisted) {
                this.threeSceneService.clearSelection()
            }
        }
        this.unhoverBuilding()
    }
 
    updateHovering() {
        if (this.hasMouseMoved(this.oldMouse)) {
            const labels = this.threeSceneService.labels?.children
 
            if (this.isGrabbingOrMoving()) {
                this.threeSceneService.resetLabel()
                this.clearLabelHoveredBuilding()
                this.threeRendererService.render()
                return
            }
 
            this.oldMouse.x = this.mouse.x
            this.oldMouse.y = this.mouse.y
 
            const mapMesh = this.threeSceneService.getMapMesh()
 
            if (mapMesh) {
                this.threeCameraService.camera.updateMatrixWorld(false)
 
                let nodeNameHoveredLabel = ""
                const mouseCoordinates = this.transformHTMLToSceneCoordinates()
                const camera = this.threeCameraService.camera
 
                Iif (camera.isPerspectiveCamera) {
                    this.raycaster.setFromCamera(mouseCoordinates as Vector2, camera)
                }
 
                const hoveredLabel = this.calculateHoveredLabel(labels)
 
                Iif (hoveredLabel) {
                    this.threeSceneService.animateLabel(hoveredLabel.object, this.raycaster, labels)
                    nodeNameHoveredLabel = hoveredLabel.object.userData.node.path
                }
 
                this.intersectedBuilding =
                    nodeNameHoveredLabel !== ""
                        ? mapMesh.getBuildingByPath(nodeNameHoveredLabel)
                        : mapMesh.checkMouseRayMeshIntersection(mouseCoordinates, camera)
 
                const from = this.threeSceneService.getHighlightedBuilding()
                const to = this.intersectedBuilding
 
                if (from?.id !== to?.id) {
                    this.clearLabelHoveredBuilding()
 
                    this.threeSceneService.resetLabel()
                    this.unhoverBuilding()
                    if (to && !this.isGrabbingOrMoving()) {
                        this.setLabelHoveredLeaf(to, labels)
                        this.hoverBuilding(to)
                    }
                }
            }
        }
    }
 
    setLabelHoveredLeaf(codeMapBuilding: CodeMapBuilding, labels: Object3D[]) {
        if (codeMapBuilding?.node?.isLeaf) {
            const labelForBuilding =
                this.threeSceneService.getLabelForHoveredNode(codeMapBuilding, labels) ?? this.drawLabelHoveredBuilding(codeMapBuilding)
            this.threeSceneService.animateLabel(labelForBuilding, this.raycaster, labels)
        }
    }
 
    drawLabelHoveredBuilding(codeMapBuilding: CodeMapBuilding) {
        const enforceLabel = true
        this.codeMapLabelService.addLeafLabel(codeMapBuilding.node, 0, enforceLabel)
 
        const labels = this.threeSceneService.labels?.children
        const labelForBuilding = this.threeSceneService.getLabelForHoveredNode(codeMapBuilding, labels)
        this.labelHoveredBuilding = codeMapBuilding.node
 
        return labelForBuilding
    }
 
    drawLabelSelectedBuilding(codeMapBuilding: CodeMapBuilding) {
        this.clearLabelHoveredBuilding()
        if (this.labelSelectedBuilding !== null) {
            this.codeMapLabelService.clearTemporaryLabel(this.labelSelectedBuilding)
        }
        Iif (!codeMapBuilding.node.isLeaf) {
            return
        }
 
        this.codeMapLabelService.addLeafLabel(codeMapBuilding.node, 0, true)
 
        const labels = this.threeSceneService.labels?.children
        const labelForBuilding = this.threeSceneService.getLabelForHoveredNode(codeMapBuilding, labels)
        this.threeSceneService.animateLabel(labelForBuilding, this.raycaster, labels)
 
        this.labelSelectedBuilding = codeMapBuilding.node
        return labelForBuilding
    }
 
    clearLabelHoveredBuilding() {
        if (this.labelHoveredBuilding !== null) {
            this.codeMapLabelService.clearTemporaryLabel(this.labelHoveredBuilding)
            this.labelHoveredBuilding = null
        }
    }
 
    private clearLabelSelectedBuilding() {
        if (this.labelSelectedBuilding !== null) {
            this.codeMapLabelService.clearTemporaryLabel(this.labelSelectedBuilding)
            this.labelSelectedBuilding = null
        }
    }
 
    private EnableOrbitalsRotation(isRotation: boolean) {
        this.threeViewerService.enableRotation(isRotation)
        this.viewCubeMouseEvents.enableRotation(isRotation)
    }
 
    onDocumentMouseEnter() {
        this.EnableOrbitalsRotation(true)
    }
 
    onDocumentMouseLeave(event: MouseEvent) {
        if (!(event.relatedTarget instanceof HTMLCanvasElement)) {
            this.EnableOrbitalsRotation(false)
        }
    }
 
    onDocumentMouseMove = (event: MouseEvent) => {
        this.mouse.x = event.clientX
        this.mouse.y = event.clientY
        this.updateHovering()
        this.viewCubeMouseEvents.propagateMovement()
    }
 
    onDocumentDoubleClick() {
        const highlightedBuilding = this.threeSceneService.getHighlightedBuilding()
        const selectedBuilding = this.threeSceneService.getSelectedBuilding()
        // Check if mouse moved to prevent opening the building link after
        // rotating the map, when the cursor ends on a building.
        const fileSourceLink = highlightedBuilding?.node.link
        if (fileSourceLink && !this.hasMouseMoved(this.mouseOnLastClick)) {
            window.open(fileSourceLink, "_blank")
        }
        if (selectedBuilding?.node.isLeaf) {
            const sourceLink = selectedBuilding.node.link
            if (sourceLink) {
                window.open(sourceLink, "_blank")
                return
            }
        }
    }
 
    onDocumentMouseDown(event: MouseEvent) {
        if (event.button === ClickType.RightClick) {
            this.isMoving = true
            CodeMapMouseEventService.changeCursorIndicator(CursorType.Moving)
        }
        if (event.button === ClickType.LeftClick) {
            this.isGrabbing = true
            CodeMapMouseEventService.changeCursorIndicator(CursorType.Grabbing)
        }
        this.mouseOnLastClick = { x: event.clientX, y: event.clientY }
        ;(document.activeElement as HTMLElement).blur()
    }
 
    onDocumentMouseUp(event: MouseEvent) {
        this.viewCubeMouseEvents.resetIsDragging()
        if (event.button === ClickType.LeftClick) {
            this.onLeftClick()
        } else {
            this.onRightClick()
        }
        if (this.intersectedBuilding !== undefined) {
            CodeMapMouseEventService.changeCursorIndicator(CursorType.Pointer)
        } else {
            CodeMapMouseEventService.changeCursorIndicator(CursorType.Default)
        }
    }
 
    private calculateHoveredLabel(labels: Object3D[]) {
        let labelClosestToViewPoint: Intersection | null = null
 
        for (let counter = 0; counter < labels?.length; counter += 2) {
            const intersect = this.raycaster.intersectObject(this.threeSceneService.labels.children[counter])
            Iif (intersect.length > 0) {
                if (labelClosestToViewPoint === null) {
                    labelClosestToViewPoint = intersect[0]
                } else {
                    labelClosestToViewPoint =
                        labelClosestToViewPoint.distance < intersect[0].distance ? labelClosestToViewPoint : intersect[0]
                }
            }
        }
 
        return labelClosestToViewPoint
    }
 
    private onRightClick() {
        this.isMoving = false
        // Check if mouse moved to prevent the node context menu to show up
        // after moving the map, when the cursor ends on a building.
        if (this.intersectedBuilding && !this.hasMouseMovedMoreThanThreePixels(this.mouseOnLastClick)) {
            this.store.dispatch(
                setRightClickedNodeData({
                    value: {
                        nodeId: this.intersectedBuilding.node.id,
                        xPositionOfRightClickEvent: this.mouse.x,
                        yPositionOfRightClickEvent: this.mouse.y
                    }
                })
            )
        }
        this.threeRendererService.render()
    }
 
    private onLeftClick() {
        this.isGrabbing = false
        if (!this.hasMouseMovedMoreThanThreePixels(this.mouseOnLastClick)) {
            if (this.intersectedBuilding) {
                this.threeSceneService.selectBuilding(this.intersectedBuilding)
                this.drawLabelSelectedBuilding(this.intersectedBuilding)
            } else {
                this.threeSceneService.clearSelection()
                this.clearLabelSelectedBuilding()
            }
            this.threeSceneService.clearConstantHighlight()
        }
        this.threeRendererService.render()
    }
 
    private hasMouseMovedMoreThanThreePixels({ x, y }: Coordinates) {
        return (
            Math.abs(this.mouse.x - x) > this.THRESHOLD_FOR_MOUSE_MOVEMENT_TRACKING ||
            Math.abs(this.mouse.y - y) > this.THRESHOLD_FOR_MOUSE_MOVEMENT_TRACKING
        )
    }
 
    private hasMouseMoved({ x, y }: Coordinates) {
        return this.mouse.x !== x || this.mouse.y !== y
    }
 
    private isGrabbingOrMoving() {
        return this.isGrabbing || this.isMoving
    }
 
    private hoverBuilding(hoveredBuilding: CodeMapBuilding, updateStore = true) {
        CodeMapMouseEventService.changeCursorIndicator(CursorType.Pointer)
 
        const idToNode = idToNodeSelector(this.state.getValue())
        const codeMapNode = idToNode.get(hoveredBuilding.node.id)
        for (const { data } of hierarchy(codeMapNode)) {
            const building = this.idToBuilding.get(data.id)
            if (building) {
                this.threeSceneService.addBuildingToHighlightingList(building)
            }
        }
        this.threeSceneService.highlightBuildings()
        if (updateStore) {
            this.store.dispatch(setHoveredNodeId({ value: hoveredBuilding.node.id }))
        }
    }
 
    private transformHTMLToSceneCoordinates(): Coordinates {
        const {
            renderer,
            renderer: { domElement }
        } = this.threeRendererService
 
        const pixelRatio = renderer.getPixelRatio()
        const rect = domElement.getBoundingClientRect()
        const x = (this.mouse.x / domElement.width) * pixelRatio * 2 - 1
        const y = -(((this.mouse.y - rect.top) / domElement.height) * pixelRatio) * 2 + 1
        return { x, y }
    }
 
    private unhoverBuilding(updateStore = true) {
        if (!this.isGrabbingOrMoving()) {
            CodeMapMouseEventService.changeCursorIndicator(CursorType.Default)
        }
 
        if (this.threeSceneService.getConstantHighlight().size > 0) {
            this.threeSceneService.clearHoverHighlight()
        } else {
            this.threeSceneService.clearHighlight()
        }
 
        if (updateStore) {
            this.store.dispatch(setHoveredNodeId({ value: null }))
        }
    }
}