TextButton.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. using System;
  2. using JetBrains.Annotations;
  3. using Unity.Cloud.Collaborate.UserInterface;
  4. using UnityEditor;
  5. using UnityEngine;
  6. using UnityEngine.UIElements;
  7. namespace Unity.Cloud.Collaborate.Components {
  8. internal class TextButton : TextElement
  9. {
  10. public const string UssClassName = "unity-text-button";
  11. static readonly string k_StylePath = $"{CollaborateWindow.StylePath}/{nameof(TextButton)}.uss";
  12. public event Action Clicked;
  13. [UsedImplicitly]
  14. public TextButton() : this(null)
  15. {
  16. }
  17. public TextButton([CanBeNull] Action clickEvent = null)
  18. {
  19. AddToClassList(UssClassName);
  20. styleSheets.Add(AssetDatabase.LoadAssetAtPath<StyleSheet>(k_StylePath));
  21. Clicked += clickEvent;
  22. this.AddManipulator(new Clickable(OnClick));
  23. }
  24. void OnClick()
  25. {
  26. Clicked?.Invoke();
  27. Blur();
  28. }
  29. public override bool canGrabFocus { get; } = true;
  30. /// <summary>
  31. /// Catch the enter key event to allow for tab & enter UI navigation.
  32. /// </summary>
  33. /// <param name="evt">Event to check.</param>
  34. protected override void ExecuteDefaultActionAtTarget(EventBase evt)
  35. {
  36. base.ExecuteDefaultActionAtTarget(evt);
  37. // Catch enter key being pressed.
  38. if (!(evt is KeyDownEvent downEvent)) return;
  39. if ((downEvent.keyCode != KeyCode.KeypadEnter) && (downEvent.keyCode != KeyCode.Return)) return;
  40. Clicked?.Invoke();
  41. downEvent.StopPropagation();
  42. }
  43. [UsedImplicitly]
  44. public new class UxmlFactory : UxmlFactory<TextButton, UxmlTraits> {}
  45. }
  46. }