Skip to content

feat: port ItemCondition from LustStation#4066

Merged
ThereDrD0 merged 1 commit intospace-sunrise:masterfrom
Soragy-bot:port/interactions-panel-from-lust-station
Mar 19, 2026
Merged

feat: port ItemCondition from LustStation#4066
ThereDrD0 merged 1 commit intospace-sunrise:masterfrom
Soragy-bot:port/interactions-panel-from-lust-station

Conversation

@Soragy-bot
Copy link
Contributor

@Soragy-bot Soragy-bot commented Mar 18, 2026

Кратное описание

Делаю порт, чтобы не было конфликтов по просьбе space-sunrise/lust-station#499

По какой причине

Медиа(Видео/Скриншоты)

Changelog

🆑 Soragy

  • add: Портирован ItemCondition для InteractionsPanel.

Summary by CodeRabbit

New Features

  • Добавлена поддержка условий взаимодействий, основанных на наличии определённых предметов
  • Реализована проверка как вооруженного снаряжения, так и предметов в конкретных слотах экипировки
  • Добавлена возможность использования белого списка предметов для настройки условий появления взаимодействий

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 18, 2026

📝 Walkthrough

Пошаговое описание

Введён новый класс ItemCondition, реализующий интерфейс IAppearCondition для проверки условий видимости на основе предметов. Класс содержит логику проверки наличия предметов у инициатора и/или цели с поддержкой фильтрации по слотам экипировки и белому списку прототипов.

Изменения

Когорта / Файл(ы) Описание
Новый класс условия
Content.Shared/_Sunrise/InteractionsPanel/Data/Conditions/ItemCondition.cs
Добавлен новый класс ItemCondition с логикой проверки предметов инициатора и цели. Включает методы IsMet(), HasRequiredItem() и IsMatchingItem(). Поддерживает проверку как переносимых, так и экипированных предметов с фильтрацией по слотам и белому списку прототипов.

Прогнозируемые затраты на код-ревью

🎯 2 (Простой) | ⏱️ ~10 минут

Предлагаемые метки

🔎 На Рассмотрение 🔎

Стихотворение

🐰 Прыг-скок, в панель условий прибегал,
Проверить предметы и слоты я стал!
ItemCondition новый блеск блеснёт,
Экипировку, инвентарь учтёт! ✨
Белый список надёжно хранит,
Условия встреч волшебство творит! 🎭

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat: port ItemCondition from LustStation' accurately describes the main change—porting a new ItemCondition class from another repository.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
📝 Coding Plan
  • Generate coding plan for human review comments

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
Content.Shared/_Sunrise/InteractionsPanel/Data/Conditions/ItemCondition.cs (2)

57-70: Проверка всех контейнеров может дать неожиданные результаты.

Когда EquipmentSlots пуст, код проверяет все контейнеры сущности, включая хранилища (карманы, сумки и т.д.), а не только экипировку. Это может привести к ложным срабатываниям, если требуется проверить именно надетые предметы.

Рассмотрите возможность:

  • Явно указывать слоты экипировки по умолчанию
  • Добавить в документацию, что пустой список означает "все контейнеры"
  • Или использовать InventorySystem для точной проверки экипировки
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@Content.Shared/_Sunrise/InteractionsPanel/Data/Conditions/ItemCondition.cs`
around lines 57 - 70, The current CheckEquipped block iterates all
ContainerManagerComponent.Containers when EquipmentSlots is empty, which checks
non-equip containers (pockets/bags); change the behavior so an empty
EquipmentSlots triggers checking only actual equipment containers: when
CheckEquipped is true and EquipmentSlots.Count == 0, query the InventorySystem
(or call a helper like
InventorySystem.GetEquipmentContainers/GetEquippedEntities) for the entity and
iterate those containers/entities instead of
ContainerManagerComponent.Containers; alternatively, require callers to supply
explicit EquipmentSlots by throwing or documenting that empty means "all
containers"—update the logic in ItemCondition (the CheckEquipped branch that
uses entityManager.TryGetComponent<ContainerManagerComponent> and
ContainerManagerComponent.Containers) to filter by equipment-only containers via
InventorySystem methods or a container.IsEquipment flag before calling
IsMatchingItem.

12-16: Граничный случай: оба флага проверки false.

Если CheckInitiator = false и CheckTarget = false, метод IsMet всегда вернёт true без выполнения каких-либо проверок. Убедитесь, что это ожидаемое поведение. Если нет — рассмотрите добавление валидации или логирования предупреждения.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@Content.Shared/_Sunrise/InteractionsPanel/Data/Conditions/ItemCondition.cs`
around lines 12 - 16, ItemCondition currently has two flags CheckInitiator and
CheckTarget; if both are false IsMet will always return true which is likely
unintended; update the ItemCondition.IsMet method to handle the both-false case
(e.g., detect if CheckInitiator == false && CheckTarget == false and either
return false or log a warning/error and return false) and additionally add
validation after deserialization (or in the class initialization path) to assert
at least one of CheckInitiator or CheckTarget is true so invalid configs are
caught early; reference CheckInitiator, CheckTarget, IsMet and ItemCondition
when making the change.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@Content.Shared/_Sunrise/InteractionsPanel/Data/Conditions/ItemCondition.cs`:
- Around line 18-19: IsMatchingItem currently treats an empty ItemWhiteList as
non-matching which makes the condition impossible when CheckInitiator is true;
update IsMatchingItem (and any callers) so that if ItemWhiteList is null or
Count == 0 it returns true (treating an empty whitelist as "any item"), or
alternatively add validation in the ItemCondition constructor/OnDeserialize to
log/throw when ItemWhiteList is empty—preferred: implement the early-return
match inside IsMatchingItem to short-circuit and return true when ItemWhiteList
is empty to preserve expected default behavior.

---

Nitpick comments:
In `@Content.Shared/_Sunrise/InteractionsPanel/Data/Conditions/ItemCondition.cs`:
- Around line 57-70: The current CheckEquipped block iterates all
ContainerManagerComponent.Containers when EquipmentSlots is empty, which checks
non-equip containers (pockets/bags); change the behavior so an empty
EquipmentSlots triggers checking only actual equipment containers: when
CheckEquipped is true and EquipmentSlots.Count == 0, query the InventorySystem
(or call a helper like
InventorySystem.GetEquipmentContainers/GetEquippedEntities) for the entity and
iterate those containers/entities instead of
ContainerManagerComponent.Containers; alternatively, require callers to supply
explicit EquipmentSlots by throwing or documenting that empty means "all
containers"—update the logic in ItemCondition (the CheckEquipped branch that
uses entityManager.TryGetComponent<ContainerManagerComponent> and
ContainerManagerComponent.Containers) to filter by equipment-only containers via
InventorySystem methods or a container.IsEquipment flag before calling
IsMatchingItem.
- Around line 12-16: ItemCondition currently has two flags CheckInitiator and
CheckTarget; if both are false IsMet will always return true which is likely
unintended; update the ItemCondition.IsMet method to handle the both-false case
(e.g., detect if CheckInitiator == false && CheckTarget == false and either
return false or log a warning/error and return false) and additionally add
validation after deserialization (or in the class initialization path) to assert
at least one of CheckInitiator or CheckTarget is true so invalid configs are
caught early; reference CheckInitiator, CheckTarget, IsMet and ItemCondition
when making the change.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: e3d96a6c-a1be-4283-b013-a0d0ad8d895f

📥 Commits

Reviewing files that changed from the base of the PR and between 3dc2dc9 and 5e29f8b.

📒 Files selected for processing (1)
  • Content.Shared/_Sunrise/InteractionsPanel/Data/Conditions/ItemCondition.cs

Comment on lines +18 to +19
[DataField]
public List<EntProtoId> ItemWhiteList { get; private set; } = new();
Copy link
Contributor

@coderabbitai coderabbitai bot Mar 18, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Пустой whitelist делает условие невыполнимым.

Если ItemWhiteList пуст (значение по умолчанию), то IsMatchingItem всегда возвращает false, и условие никогда не будет выполнено при CheckInitiator = true (также по умолчанию).

Рассмотрите добавление валидации или раннего возврата true, если whitelist пуст (если это интерпретируется как "любой предмет подходит").

💡 Возможное исправление
 private bool IsMatchingItem(EntityUid entity, EntityManager entityManager)
 {
+    // Пустой whitelist = любой предмет подходит
+    if (ItemWhiteList.Count == 0)
+        return true;
+
     if (!entityManager.TryGetComponent<MetaDataComponent>(entity, out var meta))
         return false;

     return meta.EntityPrototype != null && ItemWhiteList.Contains(meta.EntityPrototype.ID);
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@Content.Shared/_Sunrise/InteractionsPanel/Data/Conditions/ItemCondition.cs`
around lines 18 - 19, IsMatchingItem currently treats an empty ItemWhiteList as
non-matching which makes the condition impossible when CheckInitiator is true;
update IsMatchingItem (and any callers) so that if ItemWhiteList is null or
Count == 0 it returns true (treating an empty whitelist as "any item"), or
alternatively add validation in the ItemCondition constructor/OnDeserialize to
log/throw when ItemWhiteList is empty—preferred: implement the early-return
match inside IsMatchingItem to short-circuit and return true when ItemWhiteList
is empty to preserve expected default behavior.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Поведение намеренное. ItemWhiteList — это вайтлист конкретных предметов, а не "наличие хоть какого-то предмета". Пустой список означает, что предметы для проверки не заданы, поэтому false — корректный результат.
Если CheckInitiator = true и ItemWhiteList пуст — это ошибка конфигурации в YAML, а не баг кода.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Soragy-bot, понял, спасибо за пояснение. Согласен — если ItemWhiteList пуст, это ошибка конфигурации в YAML, а не баг кода. Поведение корректно.

(>‿‿>)


✏️ Learnings added
Learnt from: Soragy-bot
Repo: space-sunrise/sunrise-station PR: 4066
File: Content.Shared/_Sunrise/InteractionsPanel/Data/Conditions/ItemCondition.cs:18-19
Timestamp: 2026-03-18T17:27:20.984Z
Learning: In Content.Shared/_Sunrise/InteractionsPanel/Data/Conditions/ItemCondition.cs, an empty ItemWhiteList intentionally causes IsMatchingItem to return false. It is a whitelist of specific items, not a "any item present" check. An empty ItemWhiteList combined with CheckInitiator=true is considered a YAML configuration error, not a code bug.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


🧠 Learnings used
Learnt from: kanopus952
Repo: space-sunrise/sunrise-station PR: 3973
File: Content.Server/_Sunrise/StationEvents/Components/ResearchPointVirusRuleComponent.cs:1-10
Timestamp: 2026-03-09T11:33:51.097Z
Learning: In C# projects using global using directives, attributes and types from Robust.Shared.Analyzers are accessible without per-file using statements when the corresponding global usings are configured (as in Content.Server/GlobalUsings.cs, Content.Shared/GlobalUsings.cs, Content.Client/GlobalUsings.cs). Do not add an explicit 'using Robust.Shared.Analyzers;' to individual files like Content.Server/_Sunrise/StationEvents/Components/ResearchPointVirusRuleComponent.cs unless a file outside the existing global usings context requires a separate import. Apply this guidance to all C# files; verify global usings cover the needed symbol in any new file.

@ThereDrD0 ThereDrD0 merged commit 34f38c8 into space-sunrise:master Mar 19, 2026
10 of 11 checks passed
@github-project-automation github-project-automation bot moved this from НЕ РАЗОБРАНО to СДЕЛАНО in Разбор PR и Issues Mar 19, 2026
@Soragy-bot Soragy-bot deleted the port/interactions-panel-from-lust-station branch March 19, 2026 14:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

Status: СДЕЛАНО

Development

Successfully merging this pull request may close these issues.

2 participants