using Bridge.Html5;
using FrontendRouting;
using System;
using System.Collections.Generic;
using System.Linq;
namespace LearnBridgeNet.Components
{
public class NavigateBar : IDisposable
{
private static readonly string AttrReplace = typeof(NavigateBar).FullName + "_action_replace";
private readonly Dictionary _subElements = new Dictionary();
private Dictionary _items;
public HTMLElement Element { get; }
public bool Hidden { get => Element.Hidden; set => Element.Hidden = value; }
public NavigateBar(Node parent)
{
Element = new HTMLDivElement
{
ClassName = "navbar"
};
parent.AppendChild(Element);
FeRoutingManager.Navigated += FeRouting_Navigated;
}
private void FeRouting_Navigated(object sender, EventArgs e)
{
foreach (var element in _subElements.Values)
{
element.Style.FontWeight = element.GetAttribute("href") == Window.Location.PathName
? "bold"
: "";
}
}
private static HTMLAnchorElement Create(string href, NavigateBarItem item)
{
var element = new HTMLAnchorElement { TextContent = item.Name, Href = href };
element.SetAttribute(AttrReplace, item.Replace.ToString());
element.AddEventListener(EventType.Click, evt =>
{
evt.PreventDefault();
FeRoutingManager.Go(href,element.GetAttribute(AttrReplace)=="True");
});
return element;
}
public Dictionary Items
{
get => _items.ToDictionary(p => p.Key, p => p.Value);
set
{
if (null == Items)
{
foreach (var element in _subElements.Values)
{
element.Remove();
}
_subElements.Clear();
return;
}
_items = value.ToDictionary(p => p.Key, p => p.Value);
foreach (var item in _items)
{
if (_subElements.TryGetValue(item.Key, out var element))
{
element.TextContent = item.Value.Name;
element.SetAttribute(AttrReplace, item.Value.Replace.ToString());
}
else Element.AppendChild(_subElements[item.Key] = Create(item.Key, item.Value));
}
foreach (var key in _subElements.Keys.Where(p => false == _items.ContainsKey(p)).ToArray())
{
_subElements[key].Remove();
_subElements.Remove(key);
}
FeRouting_Navigated(null, null);
}
}
public void Dispose()
{
FeRoutingManager.Navigated -= FeRouting_Navigated;
Element.Remove();
}
}
}