yantar/assets/Scripts/ux/ErrorItemButton.ts
Georgy Shive 98e9d62db7 везде где только мог сделал с безопасной подпиской/отпиской через optional chaining
— так компоненты не упадут, даже если кнопка или её node к моменту onDestroy уже не существует
сделал ноды менеджеров списка оборудовани, деталей,
и аварий Persistent Node, чтобы при смене сцены не сбрасывалось
их состояние.
2025-05-11 13:33:08 +07:00

91 lines
3.2 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { _decorator, Component, Label, Button, Node, Event } from 'cc';
import { EquipmentManager } from '../stores/EquipmentManager';
import { PulsatingHighlighter } from '../PulsatingHighlighter';
import { CameraMover } from '../CameraMover';
import { ErrorItemData } from '../stores/ErrorItemData';
const { ccclass, property } = _decorator;
@ccclass('ErrorItemButton')
export class ErrorItemButton extends Component {
@property(Label)
public nameLabel: Label | null = null;
@property(Label)
public timeLabel: Label | null = null;
@property(Button)
public actionButton: Button | null = null; // Первая кнопка – выбирает оборудование
@property(Button)
public disableAlertButton: Button | null = null; // Вторая кнопка – отправляет запрос на API
private itemData: ErrorItemData | null = null;
public initialize(data: ErrorItemData) {
this.itemData = data;
this.nameLabel && (this.nameLabel.string = data.sensorName);
this.timeLabel && (this.timeLabel.string = data.description);
}
onLoad() {
// Подписываемся только если кнопки и их node существуют
this.actionButton?.node?.on('click', this.onActionClick, this);
this.disableAlertButton?.node?.on('click', this.onDisableAlertClick, this);
}
onDestroy() {
// Безопасно отписываемся
this.actionButton?.node?.off('click', this.onActionClick, this);
this.disableAlertButton?.node?.off('click', this.onDisableAlertClick, this);
}
onActionClick(event?: Event) {
if (!this.itemData) return;
const sensors = EquipmentManager.instance.dataList;
const sensorData = sensors.find(s => s.name === this.itemData!.sensorName);
if (!sensorData) return;
let color = '';
switch (sensorData.value) {
case 2: color = 'red'; break;
case 1: color = 'green'; break;
case 0: color = 'yellow'; break;
default: return;
}
const scene = this.node.scene;
if (!scene) return;
const targetNode = this.findNodeByName(scene, this.itemData.sensorName);
if (targetNode) {
targetNode.getComponent(PulsatingHighlighter)?.switchToColor(color);
scene.getComponentInChildren(CameraMover)?.moveToTarget(targetNode);
}
}
async onDisableAlertClick(event?: Event) {
if (!this.itemData) return;
try {
const response = await fetch('http://localhost:3030/api/v2/errors/resolve', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ sensorName: this.itemData.sensorName })
});
console.log('Error resolved:', await response.json());
} catch (error) {
console.error('Error resolving via API:', error);
}
}
private findNodeByName(root: Node, name: string): Node | null {
if (root.name === name) return root;
for (const child of root.children) {
const found = this.findNodeByName(child, name);
if (found) return found;
}
return null;
}
}