Files
TheVVaS-Assets/RPGCoreCommon/Helpers/Editor/UIElements/SearchFieldPopup.cs
T

94 lines
2.7 KiB
C#

using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;
namespace RPGCoreCommon.Helpers.Editor.UIElements
{
public class SearchFieldPopup : PopupWindowContent
{
// Elements
private VisualElement _root;
private ToolbarSearchField _searchField;
private ScrollView _scrollView;
// Runtime
private VisualElement _boundTo;
private Dictionary<string, Action> _menuItems;
public SearchFieldPopup(VisualElement boundTo, Dictionary<string, Action> menuItems)
{
_boundTo = boundTo;
_menuItems = menuItems;
}
public override VisualElement CreateGUI()
{
_root = new VisualElement();
_root.style.maxHeight = 500;
_root.style.maxWidth = _boundTo.worldBound.width;
_searchField = new ToolbarSearchField();
_searchField.style.left = _searchField.style.right = 0;
_searchField.style.width = StyleKeyword.Auto;
_root.Add(_searchField);
_scrollView = new ScrollView();
_root.Add(_scrollView);
// Show all options
_menuItems.DictSelect((name, action) => new Button(() =>
{
action();
Close();
}) { text = name }).ForEach(_scrollView.Add);
// Do auto focus when appear
_root.RegisterCallback<AttachToPanelEvent>(_ => _searchField.Focus());
// ESC - close
// ENTER - select first visible
_root.RegisterCallback<KeyDownEvent>(ev =>
{
switch (ev.keyCode)
{
case KeyCode.Escape:
Close();
break;
case KeyCode.Return:
SelectFirst();
break;
default:
ApplyFilter();
break;
}
}, TrickleDown.TrickleDown);
return _root;
}
public void Show()
{
UnityEditor.PopupWindow.Show(_boundTo.worldBound, this);
}
public void Close()
{
editorWindow.Close();
}
private void SelectFirst()
{
_scrollView.Query<Button>().Visible().First().Click();
}
private void ApplyFilter()
{
_scrollView.Query<Button>()
.ForEach(b => b.style.display = b.text.Contains(_searchField.value) ? DisplayStyle.Flex : DisplayStyle.None);
}
}
}