Ooui-tws-port/Ooui/Node.cs

91 lines
2.6 KiB
C#
Raw Normal View History

2017-06-12 20:45:27 +00:00
using System;
using System.Collections.Generic;
using System.Linq;
namespace Ooui
{
2017-06-15 01:24:59 +00:00
public abstract class Node : EventTarget
2017-06-12 20:45:27 +00:00
{
readonly List<Node> children = new List<Node> ();
2017-06-15 09:39:19 +00:00
public IEnumerable<Node> Children => children;
2017-06-13 03:31:47 +00:00
2017-06-14 04:17:50 +00:00
public virtual string Text {
get { return String.Join ("", from c in children select c.Text); }
2017-06-13 07:51:24 +00:00
set {
2017-06-14 04:17:50 +00:00
ReplaceAll (new TextNode (value ?? ""));
2017-06-13 07:51:24 +00:00
}
}
2017-06-15 06:20:51 +00:00
protected Node (string tagName)
: base (tagName)
{
2017-06-12 20:45:27 +00:00
}
2017-06-15 09:39:19 +00:00
public override EventTarget GetElementById (string id)
{
if (id == Id) return this;
foreach (var c in Children) {
if (c is Element e) {
var r = e.GetElementById (id);
if (r != null)
return r;
}
}
return null;
}
2017-06-12 20:45:27 +00:00
public Node AppendChild (Node newChild)
{
return InsertBefore (newChild, null);
}
public Node InsertBefore (Node newChild, Node referenceChild)
{
if (referenceChild == null) {
children.Add (newChild);
}
else {
var index = children.IndexOf (referenceChild);
if (index < 0) {
throw new ArgumentException ("Reference must be a child of this element", nameof(referenceChild));
}
children.Insert (index, newChild);
}
2017-06-15 01:24:59 +00:00
SendCall ("insertBefore", newChild, referenceChild);
2017-06-12 20:45:27 +00:00
return newChild;
}
public Node RemoveChild (Node child)
{
if (!children.Remove (child)) {
throw new ArgumentException ("Child not contained in this element", nameof(child));
}
2017-06-15 01:24:59 +00:00
SendCall ("removeChild", child);
2017-06-12 20:45:27 +00:00
return child;
}
2017-06-13 07:51:24 +00:00
protected void ReplaceAll (Node newNode)
{
var toRemove = new List<Node> (children);
foreach (var c in toRemove)
RemoveChild (c);
InsertBefore (newNode, null);
}
2017-06-15 09:39:19 +00:00
protected override void SaveStateMessageIfNeeded (Message message)
{
switch (message.MessageType) {
case MessageType.Call when
message.Key == "insertBefore" ||
message.Key == "removeChild":
SaveStateMessage (message);
break;
default:
base.SaveStateMessageIfNeeded (message);
break;
}
}
2017-06-12 20:45:27 +00:00
}
}