теперь поведение кнопки с отображением описания

не протекает в другие приборы
This commit is contained in:
Georgy Shive 2025-05-27 22:10:21 +07:00
parent 1851b2d959
commit adbf4faed0
3 changed files with 234 additions and 69 deletions

View File

@ -175,6 +175,33 @@ export class ErrorLazyLoadList extends Component {
}
}
/**
* Полностью очищает все пулы и уничтожает элементы
*/
private clearAllPools() {
console.log('[ErrorLazyLoadList] Clearing all pools');
// Очищаем и уничтожаем элементы в пулах
if (this._errorItemPool) {
this._errorItemPool.clear();
this._errorItemPool = null;
}
if (this._namedErrorItemPool) {
this._namedErrorItemPool.clear();
this._namedErrorItemPool = null;
}
// Очищаем пулы датчиков
this._sensorFieldItemPools.forEach(pool => {
pool.clear();
});
this._sensorFieldItemPools.clear();
this._activeSensorNames.clear();
this._activeSensorFieldItems.clear();
}
private waitForErrorManager() {
if (!ErrorManager.instance) {
this.scheduleOnce(() => { this.waitForErrorManager(); }, 0.1);
@ -294,16 +321,23 @@ export class ErrorLazyLoadList extends Component {
} else if (item.getComponent(ErrorItemNamedButton)) {
this.getOrCreateNamedErrorItemPool().put(item);
} else if (item.getComponent(SensorFieldItem)) {
// Для датчиков возвращаем в общий пул
// Для датчиков НЕ возвращаем в пул, а уничтожаем для гарантии чистого состояния
console.log(`[ErrorLazyLoadList] Destroying SensorFieldItem instead of pooling`);
// Удаляем из активных элементов
const sensorFieldItem = item.getComponent(SensorFieldItem);
if (sensorFieldItem) {
// Сбрасываем состояние перед возвратом в пул
sensorFieldItem.resetState();
// Возвращаем в общий пул
const pool = this.getOrCreateSensorFieldItemPool('');
pool.put(item);
if (sensorFieldItem && sensorFieldItem.sensorName) {
const activeItems = this._activeSensorFieldItems.get(sensorFieldItem.sensorName);
if (activeItems) {
activeItems.delete(item);
console.log(`[ErrorLazyLoadList] Removed item from active items for ${sensorFieldItem.sensorName}, remaining: ${activeItems.size}`);
}
}
if (sensorFieldItem) {
sensorFieldItem.resetState(); // Сбрасываем состояние перед уничтожением
}
item.destroy(); // Полностью уничтожаем элемент
}
}
@ -331,6 +365,11 @@ export class ErrorLazyLoadList extends Component {
currentPool = this.getOrCreateSensorFieldItemPool(sensorName);
expectedComponentType = "SensorFieldItem";
this._activeSensorNames.add(sensorName);
// Инициализируем Set для активных элементов этого датчика, если его нет
if (!this._activeSensorFieldItems.has(sensorName)) {
this._activeSensorFieldItems.set(sensorName, new Set());
}
} else {
return;
}
@ -366,9 +405,15 @@ export class ErrorLazyLoadList extends Component {
// Если элементов меньше чем нужно - добавляем новые
while (this._activeItems.length < targetActiveCount) {
const item = this._mode === "details"
? this.createItemForCurrentMode()
: currentPool.get() || this.createItemForCurrentMode();
let item: Node | null = null;
if (this._mode === "details") {
// Для датчиков всегда создаем новые элементы
item = this.createItemForCurrentMode();
} else {
// Для ошибок используем пул
item = currentPool.get() || this.createItemForCurrentMode();
}
if (!item) break;
@ -380,10 +425,13 @@ export class ErrorLazyLoadList extends Component {
// Если это элемент датчика, добавляем его в активные элементы
if (this._mode === "details") {
const sensorName = this._sensorDescription.sensorName;
const activeItems = this._activeSensorFieldItems.get(sensorName);
if (activeItems) {
activeItems.add(item);
let activeItems = this._activeSensorFieldItems.get(sensorName);
if (!activeItems) {
activeItems = new Set();
this._activeSensorFieldItems.set(sensorName, activeItems);
}
activeItems.add(item);
console.log(`[ErrorLazyLoadList] Added SensorFieldItem to active items for ${sensorName}, total: ${activeItems.size}`);
}
}
@ -396,8 +444,21 @@ export class ErrorLazyLoadList extends Component {
const newData = currentData[dataIndex];
const oldData = this._activeItemsData[i];
// Сравниваем данные - обновляем только если изменились
const needsUpdate = !oldData ||
// Для новых элементов датчиков всегда обновляем данные
// Для остальных - сравниваем данные и обновляем только если изменились
const isNewSensorItem = this._mode === "details" && !oldData;
// Для датчиков проверяем изменения в значениях полей более детально
let dataChanged = false;
if (this._mode === "details" && oldData && newData) {
dataChanged = oldData.name !== newData.name ||
oldData.value !== newData.value ||
oldData.unit !== newData.unit ||
oldData.description !== newData.description;
}
const needsUpdate = isNewSensorItem || !oldData ||
dataChanged ||
JSON.stringify(oldData) !== JSON.stringify(newData) ||
dataIndex !== this._activeItemsData[i]?.lastDataIndex;
@ -413,7 +474,14 @@ export class ErrorLazyLoadList extends Component {
break;
case "details":
if (component && 'setData' in component && typeof component.setData === 'function') {
(component as SensorFieldItem).setData(newData);
console.log(`[ErrorLazyLoadList] Updating SensorFieldItem data: ${newData.name}`);
// Для новых элементов используем setData (полная инициализация)
// Для существующих элементов используем updateData (сохранение состояния UI)
if (isNewSensorItem) {
(component as SensorFieldItem).setData(newData);
} else {
(component as SensorFieldItem).updateData(newData);
}
}
break;
}
@ -450,14 +518,11 @@ export class ErrorLazyLoadList extends Component {
return instantiate(this.errorItemPrefab);
}
} else if (this._mode === "details") {
// Для датчиков берем из пула или создаем новый
// Для датчиков всегда создаем новые элементы для гарантии чистого состояния
if (this._sensorDescription && this._sensorDescription.sensorName) {
const pool = this.getOrCreateSensorFieldItemPool(this._sensorDescription.sensorName);
let item = pool.get();
if (!item) {
item = instantiate(this.sensorFieldItemPrefab);
}
// ВАЖНО: всегда сбрасываем состояние при получении из пула
console.log(`[ErrorLazyLoadList] Creating fresh SensorFieldItem for ${this._sensorDescription.sensorName}`);
const item = instantiate(this.sensorFieldItemPrefab);
// Сбрасываем состояние нового элемента
this.resetSensorFieldItemState(item);
return item;
}
@ -516,9 +581,10 @@ export class ErrorLazyLoadList extends Component {
this._filteredData[0].sensorName !== sensorName;
this.preserveScrollPosition(() => {
// Уничтожаем элементы только если меняется фильтр
// Уничтожаем элементы и очищаем пулы если меняется фильтр
if (isNewFilter) {
this.hideAllItems();
this.clearAllPools(); // Полностью очищаем пулы
}
this._mode = "errors";
@ -539,9 +605,10 @@ export class ErrorLazyLoadList extends Component {
const hasActiveFilter = this._filteredData !== null;
this.preserveScrollPosition(() => {
// Уничтожаем элементы только если был активный фильтр
// Уничтожаем элементы и очищаем пулы если был активный фильтр
if (hasActiveFilter) {
this.hideAllItems();
this.clearAllPools(); // Полностью очищаем пулы
}
this.header.string = "Список всех аварий";
@ -559,15 +626,15 @@ export class ErrorLazyLoadList extends Component {
* @param data Объект с деталями датчика.
*/
public showSensorDetails(data: { sensorName: string, fields: any[] }) {
// Проверяем, действительно ли меняется датчик
// Проверяем, действительно ли меняется датчик или режим
const isNewSensor = !this._sensorDescription || this._sensorDescription.sensorName !== data.sensorName;
const isModeChange = this._mode !== "details";
this.preserveScrollPosition(() => {
// Уничтожаем элементы только если меняется датчик
if (isNewSensor) {
// Уничтожаем элементы и очищаем пулы если меняется датчик или режим
if (isNewSensor || isModeChange) {
this.hideAllItems();
// Очищаем пулы неактивных датчиков при смене
this.cleanupUnusedSensorPools();
this.clearAllPools(); // Полностью очищаем все пулы
}
this._mode = "details";
@ -593,16 +660,54 @@ export class ErrorLazyLoadList extends Component {
return;
}
// Просто обновляем данные без сброса UI
console.log(`[ErrorLazyLoadList] updateSensorDetails: ${data.sensorName}, fields count: ${data.fields?.length || 0}`);
// Обновляем данные
this._sensorDescription = {
sensorName: data.sensorName,
fields: data.fields || []
};
// Обновляем видимые элементы без принудительного сброса
// Принудительно сбрасываем данные отслеживания для принудительного обновления
this._activeItemsData = this._activeItemsData.map(() => null);
// Принудительно обновляем все активные элементы датчика
this.forceUpdateActiveSensorItems(data.sensorName, data.fields);
// Обновляем видимые элементы с принудительным обновлением данных
this.updateVisibleItems(false);
}
/**
* Принудительно обновляет все активные элементы конкретного датчика
*/
private forceUpdateActiveSensorItems(sensorName: string, fields: any[]) {
const activeItems = this._activeSensorFieldItems.get(sensorName);
if (!activeItems || activeItems.size === 0) {
console.log(`[ErrorLazyLoadList] No active items found for sensor ${sensorName}`);
return;
}
console.log(`[ErrorLazyLoadList] Force updating ${activeItems.size} active items for sensor ${sensorName}`);
// Обновляем каждый активный элемент
let itemIndex = 0;
for (const item of activeItems) {
if (!item.isValid || !item.active) {
continue;
}
const component = item.getComponent(SensorFieldItem);
if (component && itemIndex < fields.length) {
const fieldData = fields[itemIndex];
console.log(`[ErrorLazyLoadList] Force updating item ${itemIndex}: ${fieldData.name} = ${fieldData.value}`);
// Используем updateData() вместо setData() для сохранения состояния UI
component.updateData(fieldData);
itemIndex++;
}
}
}
/**
* Возвращает в режим отображения ошибок (например, при переключении вкладок).
*/
@ -611,9 +716,10 @@ export class ErrorLazyLoadList extends Component {
const isModeChange = this._mode !== "errors";
this.preserveScrollPosition(() => {
// Уничтожаем элементы только если меняется режим
// Уничтожаем элементы и очищаем пулы если меняется режим
if (isModeChange) {
this.hideAllItems();
this.clearAllPools(); // Полностью очищаем все пулы
}
this._mode = "errors";

View File

@ -73,16 +73,24 @@ export class SensorFieldItem extends Component {
private onMorphButtonClick(): void {
if (!this.hasDescription || !this.morphButton) return;
// Ждем немного, чтобы анимация кнопки началась
// Ждем завершения анимации кнопки (2 кадра по 0.055 = 0.11 + небольшой запас)
this.scheduleOnce(() => {
// Проверяем состояние кнопки после клика
const isShowingDescription = !this.morphButton!.getIsQuestion();
console.log(`[SensorFieldItem] onMorphButtonClick: showing description = ${isShowingDescription}`);
if (this.descriptionContainer) {
this.descriptionContainer.active = isShowingDescription;
}
}, 0.1);
this.syncDescriptionWithButton();
}, 0.15);
}
/**
* Синхронизирует видимость описания с состоянием кнопки
*/
private syncDescriptionWithButton(): void {
if (!this.morphButton || !this.hasDescription) return;
const isShowingDescription = !this.morphButton.getIsQuestion();
console.log(`[SensorFieldItem] syncDescriptionWithButton: button state = ${this.morphButton.getIsQuestion() ? 'question' : 'cross'}, showing description = ${isShowingDescription}`);
if (this.descriptionContainer) {
this.descriptionContainer.active = isShowingDescription;
}
}
/**
@ -90,32 +98,78 @@ export class SensorFieldItem extends Component {
* @param field Объект поля датчика (name, value, unit, description)
*/
public setData(field: SensorDescriptionField): void {
console.log(`[SensorFieldItem] setData: ${this.node.name} (${this.node.uuid}), field: ${field.name}, buttonId: ${this.buttonId}`);
this.setDataInternal(field, true); // Полная инициализация с сбросом состояния
}
/**
* Обновить только данные без сброса состояния UI (для обновлений в реальном времени).
* @param field Объект поля датчика (name, value, unit, description)
*/
public updateData(field: SensorDescriptionField): void {
this.setDataInternal(field, false); // Обновление без сброса состояния
}
/**
* Внутренний метод для установки данных с возможностью сохранения состояния UI
* @param field Объект поля датчика
* @param resetUIState Нужно ли сбрасывать состояние UI (кнопки и описания)
*/
private setDataInternal(field: SensorDescriptionField, resetUIState: boolean): void {
console.log(`[SensorFieldItem] ${resetUIState ? 'setData' : 'updateData'}: ${this.node.name} (${this.node.uuid}), field: ${field.name}, buttonId: ${this.buttonId}`);
// Обновляем основные данные (это всегда нужно делать)
if (this.nameLabel) this.nameLabel.string = field.name;
if (this.valueLabel) this.valueLabel.string = String(field.value);
if (this.unitLabel) this.unitLabel.string = field.unit ?? "????";
this.hasDescription = !!field.description?.trim();
console.log(`[SensorFieldItem] Has description: ${this.hasDescription}, buttonId: ${this.buttonId}`);
console.log(`[SensorFieldItem] Has description: ${this.hasDescription}, resetUIState: ${resetUIState}, buttonId: ${this.buttonId}`);
// Работаем с описанием
if (this.descriptionLabel) {
this.descriptionLabel.string = this.hasDescription ? field.description! : "";
}
// Всегда начинаем с скрытого описания (кнопка в состоянии question)
// Это гарантирует, что состояние не "протечет" между датчиками
if (this.descriptionContainer) {
this.descriptionContainer.active = false;
}
// Morph: показываем кнопку только при наличии описания
if (this.Morph) {
this.Morph.active = this.hasDescription;
// Убеждаемся, что кнопка в состоянии question при первом показе
if (this.morphButton && this.morphButton.getIsQuestion() === false) {
console.log(`[SensorFieldItem] Resetting button to question state for: ${this.Morph.name} (${this.Morph.uuid}), buttonId: ${this.buttonId}`);
this.morphButton.resetState();
if (resetUIState) {
// Полная инициализация - сбрасываем состояние UI
// Всегда начинаем с скрытого описания (кнопка в состоянии question)
if (this.descriptionContainer) {
this.descriptionContainer.active = false;
}
// Morph: показываем кнопку только при наличии описания
if (this.Morph) {
this.Morph.active = this.hasDescription;
// Убеждаемся, что кнопка в состоянии question при первом показе
if (this.morphButton && this.morphButton.getIsQuestion() === false) {
console.log(`[SensorFieldItem] Fully reinitializing button to question state for: ${this.Morph.name} (${this.Morph.uuid}), buttonId: ${this.buttonId}`);
this.morphButton.fullReinitialize();
this.buttonId = this.morphButton.getButtonId(); // Обновляем buttonId после полной переинициализации
}
// Принудительно синхронизируем состояние после небольшой задержки
this.scheduleOnce(() => {
this.syncDescriptionWithButton();
}, 0.05);
}
} else {
// Обновление данных - сохраняем текущее состояние UI
if (this.Morph) {
// Показываем/скрываем кнопку в зависимости от наличия описания
this.Morph.active = this.hasDescription;
// НЕ сбрасываем состояние кнопки, сохраняем текущее
// Только синхронизируем видимость описания с текущим состоянием кнопки
if (this.hasDescription) {
this.scheduleOnce(() => {
this.syncDescriptionWithButton();
}, 0.05);
} else {
// Если описания нет, скрываем контейнер
if (this.descriptionContainer) {
this.descriptionContainer.active = false;
}
}
}
}
}
@ -145,8 +199,9 @@ export class SensorFieldItem extends Component {
if (this.Morph) {
this.Morph.active = false;
if (this.morphButton) {
console.log(`[SensorFieldItem] Resetting MorphButton state in resetState: ${this.Morph.name} (${this.Morph.uuid}), buttonId: ${this.buttonId}`);
this.morphButton.resetState();
console.log(`[SensorFieldItem] Fully reinitializing MorphButton state in resetState: ${this.Morph.name} (${this.Morph.uuid}), buttonId: ${this.buttonId}`);
this.morphButton.fullReinitialize();
this.buttonId = this.morphButton.getButtonId(); // Обновляем buttonId после полной переинициализации
}
}
}
@ -165,14 +220,14 @@ export class SensorFieldItem extends Component {
// Получаем компонент заново
this.morphButton = this.Morph.getComponent(MorphButtonWithButton);
if (this.morphButton) {
console.log(`[SensorFieldItem] Before reset - button state: ${this.morphButton.getIsQuestion() ? 'question' : 'cross'}`);
console.log(`[SensorFieldItem] Before fullReinitialize - button state: ${this.morphButton.getIsQuestion() ? 'question' : 'cross'}`);
// Всегда сбрасываем состояние кнопки при переинициализации
this.morphButton.resetState();
// Используем полную переинициализацию вместо простого resetState
this.morphButton.fullReinitialize();
this.buttonId = this.morphButton.getButtonId();
console.log(`[SensorFieldItem] After reset - button state: ${this.morphButton.getIsQuestion() ? 'question' : 'cross'}`);
console.log(`[SensorFieldItem] Reinitialized MorphButton: ${this.Morph.name} (${this.Morph.uuid}), buttonId: ${this.buttonId}`);
console.log(`[SensorFieldItem] After fullReinitialize - button state: ${this.morphButton.getIsQuestion() ? 'question' : 'cross'}`);
console.log(`[SensorFieldItem] Fully reinitialized MorphButton: ${this.Morph.name} (${this.Morph.uuid}), buttonId: ${this.buttonId}`);
} else {
console.warn(`[SensorFieldItem] MorphButton component not found on ${this.Morph.name}`);
}

View File

@ -28,7 +28,7 @@ export class MorphButtonWithButton extends Component {
}
public fullReinitialize() {
console.log(`[MorphButton] fullReinitialize: ${this.node.name} (${this.node.uuid})`);
console.log(`[MorphButton] fullReinitialize START: ${this.node.name} (${this.node.uuid}), current state: ${this.isQuestion ? 'question' : 'cross'}`);
// Останавливаем все анимации
if (this.currentTween) {
@ -46,7 +46,7 @@ export class MorphButtonWithButton extends Component {
// Генерируем новый ID для отладки
this.buttonId = `${this.node.name}_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
console.log(`[MorphButton] New buttonId after reinit: ${this.buttonId}`);
console.log(`[MorphButton] fullReinitialize COMPLETE: ${this.node.name}, new state: ${this.isQuestion ? 'question' : 'cross'}, buttonId: ${this.buttonId}`);
}
onDestroy() {
@ -82,11 +82,15 @@ export class MorphButtonWithButton extends Component {
});
}
// Меняем состояние только после завершения анимации
tw = tw.call(() => {
this.isQuestion = !this.isQuestion;
console.log(`[MorphButton] Animation complete, new state: ${this.isQuestion ? 'question' : 'cross'}`);
});
// Сохраняем ссылку на текущий tween
this.currentTween = tw;
tw.start();
this.isQuestion = !this.isQuestion;
}
public resetState() {