FloatingMenuItem.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. using System;
  2. using Unity.Cloud.Collaborate.UserInterface;
  3. using UnityEditor;
  4. using UnityEngine;
  5. using UnityEngine.UIElements;
  6. namespace Unity.Cloud.Collaborate.Components.Menus
  7. {
  8. internal class FloatingMenuItem : VisualElement
  9. {
  10. const string k_UssClassName = "unity-floating-menu-item";
  11. /// <summary>
  12. /// Location the uss file for this element is stored.
  13. /// </summary>
  14. static readonly string k_StylePath = $"{CollaborateWindow.StylePath}/{nameof(FloatingMenuItem)}.uss";
  15. public override bool canGrabFocus { get; } = true;
  16. readonly Action m_Action;
  17. public FloatingMenuItem(string text, Action action, bool enabled, float height)
  18. {
  19. AddToClassList(k_UssClassName);
  20. styleSheets.Add(AssetDatabase.LoadAssetAtPath<StyleSheet>(k_StylePath));
  21. m_Action = action;
  22. focusable = true;
  23. this.AddManipulator(new Clickable(OnExec));
  24. SetEnabled(enabled);
  25. Add(new Label(text));
  26. style.height = height;
  27. }
  28. void OnExec()
  29. {
  30. m_Action();
  31. }
  32. /// <summary>
  33. /// Catch the enter key event to allow for tab & enter UI navigation.
  34. /// </summary>
  35. /// <param name="evt">Event to check.</param>
  36. protected override void ExecuteDefaultActionAtTarget(EventBase evt)
  37. {
  38. base.ExecuteDefaultActionAtTarget(evt);
  39. // Catch enter key being pressed.
  40. if (!(evt is KeyDownEvent downEvent)) return;
  41. if (downEvent.keyCode != KeyCode.KeypadEnter && downEvent.keyCode != KeyCode.Return) return;
  42. OnExec();
  43. downEvent.StopPropagation();
  44. }
  45. }
  46. }