/* * Copyright 2022 Peter Han * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using PeterHan.PLib.UI; using UnityEngine; using UnityEngine.Events; namespace PeterHan.PLib.Options { /// /// Handles events for expanding and contracting options categories. /// internal sealed class CategoryExpandHandler { /// /// The realized panel containing the options. /// private GameObject contents; /// /// The initial state of the button. /// private readonly bool initialState; /// /// The realized toggle button. /// private GameObject toggle; /// /// Creates a new options category. /// /// true to start expanded, or false to start collapsed. public CategoryExpandHandler(bool initialState = true) { this.initialState = initialState; } /// /// Fired when the options category is expanded or contracted. /// /// true if the button is on, or false if it is off. public void OnExpandContract(GameObject _, bool on) { var scale = on ? Vector3.one : Vector3.zero; if (contents != null) { var rt = contents.rectTransform(); rt.localScale = scale; if (rt != null) UnityEngine.UI.LayoutRebuilder.MarkLayoutForRebuild(rt); } } /// /// Fired when the header is clicked. /// private void OnHeaderClicked() { if (toggle != null) { bool state = PToggle.GetToggleState(toggle); PToggle.SetToggleState(toggle, !state); } } /// /// Fired when the category label is realized. /// /// The realized header label of the category. public void OnRealizeHeader(GameObject header) { var button = header.AddComponent(); button.onClick.AddListener(new UnityAction(OnHeaderClicked)); button.interactable = true; } /// /// Fired when the body is realized. /// /// The realized body of the category. public void OnRealizePanel(GameObject panel) { contents = panel; OnExpandContract(null, initialState); } /// /// Fired when the toggle button is realized. /// /// The realized expand/contract button. public void OnRealizeToggle(GameObject toggle) { this.toggle = toggle; } } }