|
| 1 | +import { Component, CUSTOM_ELEMENTS_SCHEMA, inject, Input, OnInit } from '@angular/core'; |
| 2 | +import { extend, injectNgtRef, NgtRxStore } from 'angular-three'; |
| 3 | +import { combineLatest } from 'rxjs'; |
| 4 | +import { Group } from 'three'; |
| 5 | +import { NGTP_SELECTION_API } from './selection'; |
| 6 | + |
| 7 | +extend({ Group }); |
| 8 | + |
| 9 | +@Component({ |
| 10 | + selector: 'ngtp-select', |
| 11 | + standalone: true, |
| 12 | + template: ` |
| 13 | + <ngt-group ngtCompound [ref]="groupRef"> |
| 14 | + <ng-content /> |
| 15 | + </ngt-group> |
| 16 | + `, |
| 17 | + schemas: [CUSTOM_ELEMENTS_SCHEMA], |
| 18 | +}) |
| 19 | +export class NgtpSelect extends NgtRxStore implements OnInit { |
| 20 | + readonly groupRef = injectNgtRef<THREE.Group>(); |
| 21 | + |
| 22 | + private readonly selectionApi = inject(NGTP_SELECTION_API); |
| 23 | + |
| 24 | + @Input() set enabled(enabled: boolean) { |
| 25 | + this.set({ enabled }); |
| 26 | + } |
| 27 | + |
| 28 | + override initialize(): void { |
| 29 | + super.initialize(); |
| 30 | + this.set({ enabled: false }); |
| 31 | + } |
| 32 | + |
| 33 | + ngOnInit() { |
| 34 | + this.setSelectEffect(); |
| 35 | + } |
| 36 | + |
| 37 | + private setSelectEffect() { |
| 38 | + this.effect(combineLatest([this.select('enabled'), this.groupRef.children$()]), ([enabled]) => { |
| 39 | + if (enabled) { |
| 40 | + let changed = false; |
| 41 | + const current: THREE.Object3D[] = []; |
| 42 | + this.groupRef.nativeElement.traverse((obj) => { |
| 43 | + if (obj.type === 'Mesh') current.push(obj); |
| 44 | + if (this.selectionApi.selected.indexOf(obj) === -1) changed = true; |
| 45 | + }); |
| 46 | + if (changed) { |
| 47 | + this.selectionApi.select((state) => ({ selected: [...state.selected, ...current] })); |
| 48 | + return () => { |
| 49 | + this.selectionApi.select((state) => ({ |
| 50 | + selected: state.selected.filter((selected) => !current.includes(selected)), |
| 51 | + })); |
| 52 | + }; |
| 53 | + } |
| 54 | + } |
| 55 | + }); |
| 56 | + } |
| 57 | +} |
0 commit comments