KSP-Conformal-Decals/Source/ConformalDecals/UI/FontMenuController.cs

63 lines
2.2 KiB
C#
Raw Normal View History

2020-07-20 04:12:48 +00:00
using System;
using System.Collections.Generic;
using ConformalDecals.Text;
using UniLinq;
using UnityEngine;
2020-07-21 07:07:18 +00:00
using UnityEngine.Events;
2020-07-20 04:12:48 +00:00
using UnityEngine.UI;
namespace ConformalDecals.UI {
public class FontMenuController : MonoBehaviour {
2020-07-21 07:07:18 +00:00
[Serializable]
public class FontUpdateEvent : UnityEvent<DecalFont> { }
2020-07-23 05:37:16 +00:00
[SerializeField] public FontUpdateEvent onFontChanged = new FontUpdateEvent();
2020-07-21 07:07:18 +00:00
2020-07-20 04:12:48 +00:00
[SerializeField] private GameObject _menuItem;
[SerializeField] private GameObject _menuList;
2020-07-21 07:07:18 +00:00
private DecalFont _currentFont;
2020-07-20 04:12:48 +00:00
2020-07-21 07:07:18 +00:00
public static FontMenuController Create(IEnumerable<DecalFont> fonts, DecalFont currentFont, UnityAction<DecalFont> fontUpdateCallback) {
2020-07-20 04:12:48 +00:00
var menu = Instantiate(UILoader.FontMenuPrefab, MainCanvasUtil.MainCanvas.transform, true);
menu.AddComponent<DragPanel>();
MenuNavigation.SpawnMenuNavigation(menu, Navigation.Mode.Automatic, true);
var controller = menu.GetComponent<FontMenuController>();
2020-07-21 07:07:18 +00:00
controller._currentFont = currentFont;
2020-07-23 05:37:16 +00:00
controller.onFontChanged.AddListener(fontUpdateCallback);
2020-07-21 07:07:18 +00:00
2020-07-20 04:12:48 +00:00
controller.Populate(fonts);
return controller;
}
2020-08-22 06:45:10 +00:00
public void Close() {
2020-07-20 04:12:48 +00:00
Destroy(gameObject);
}
public void OnFontSelected(DecalFont font) {
2020-07-21 07:07:18 +00:00
_currentFont = font ?? throw new ArgumentNullException(nameof(font));
2020-07-23 05:37:16 +00:00
onFontChanged.Invoke(_currentFont);
2020-07-20 04:12:48 +00:00
}
public void Populate(IEnumerable<DecalFont> fonts) {
if (fonts == null) throw new ArgumentNullException(nameof(fonts));
Toggle active = null;
foreach (var font in fonts.OrderBy(x => x.Title)) {
2020-07-20 04:12:48 +00:00
var listItem = GameObject.Instantiate(_menuItem, _menuList.transform);
listItem.name = font.Title;
2020-07-20 04:12:48 +00:00
listItem.SetActive(true);
var fontItem = listItem.AddComponent<FontMenuItem>();
fontItem.Font = font;
fontItem.fontSelectionCallback = OnFontSelected;
2020-07-21 07:07:18 +00:00
if (font == _currentFont) active = fontItem.toggle;
2020-07-20 04:12:48 +00:00
}
if (active != null) active.isOn = true;
}
}
}