Car/Assets/Scripts/UI/SearchView.cs

114 lines
3.4 KiB
C#
Raw Normal View History

2024-12-31 07:57:41 +08:00
using System;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
using YogiGameCore.Utils;
using Action = Newtonsoft.Json.Serialization.Action;
public class SearchView : MonoBehaviour
{
[SerializeField] private TMP_InputField searchInputField;
[SerializeField] private Button searchBtn;
[SerializeField] private Transform searchContainer;
[SerializeField] private GameObject searchScrollView;
[SerializeField] private Button selectBtnPrefab;
private List<object> searchObjs;
private List<string> searchStrings;
private List<Button> selectBtns;
private void Awake()
{
Reset();
searchBtn.onClick.AddListener(Search);
// this.searchInputField.onDeselect.AddListener((v) =>
// {
// Clear();
// });
}
private void Reset()
{
this.selectBtns = null;
this.searchObjs = null;
this.searchStrings = null;
this.searchContainer.DestroyChildren();
this.searchScrollView.SetActive(false);
}
public void Clear()
{
this.searchScrollView.SetActive(false);
this.searchInputField.SetTextWithoutNotify(String.Empty);
}
public void SetUp(List<object> searchObjs, List<string> searchStrings, Action<object> onSearchSuccess = null)
{
this.searchObjs = searchObjs;
this.searchStrings = searchStrings;
this.selectBtns = new List<Button>();
for (var i = 0; i < this.searchStrings.Count; i++)
{
var searchString = this.searchStrings[i];
var searchObj = this.searchObjs[i];
var spawnSelectBtn = SpawnSelectBtn(searchString, () =>
{
onSearchSuccess?.Invoke(searchObj);
searchScrollView.SetActive(false);
});
this.selectBtns.Add(spawnSelectBtn);
}
}
public void SetUp(List<object> searchObjs, Func<object, string> parseToSearchStringsFunc,
Action<object> onSearchSuccess = null)
{
searchStrings = new List<string>();
for (var i = 0; i < searchObjs.Count; i++)
{
var searchObj = searchObjs[i];
var searchStr = parseToSearchStringsFunc?.Invoke(searchObj);
searchStrings.Add(searchStr);
}
SetUp(searchObjs, searchStrings, onSearchSuccess);
}
public void Search()
{
searchScrollView.SetActive(true);
string text = searchInputField.text;
var searchStrArr = text.Split(' ');
for (var index = 0; index < searchStrings.Count; index++)
{
var searchStr = searchStrings[index];
var selectBtn = selectBtns[index];
var hasSearchStr = HasSearchStr();
selectBtn.gameObject.SetActive(hasSearchStr);
bool HasSearchStr()
{
foreach (var str in searchStrArr)
{
if (searchStr.Contains(str))
{
return true;
}
}
return false;
}
}
}
private Button SpawnSelectBtn(string displayName, Action selectAction)
{
Button btn = GameObject.Instantiate(selectBtnPrefab, searchContainer);
btn.onClick.AddListener(() => { selectAction?.Invoke(); });
btn.GetComponentInChildren<TextMeshProUGUI>().text = displayName;
return btn;
}
}