Last active
September 19, 2016 15:23
-
-
Save mobinni/c49d3c383569fb1db3cf to your computer and use it in GitHub Desktop.
Swift - DOM implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import cocoa; | |
// Base DOM interface | |
protocol Node { | |
var childNodes: [AnyObject]{get set}; | |
var nodeName: NodeType{get set}; | |
} | |
enum NodeType { | |
case Text(String) | |
case Element(ElementData) | |
} | |
struct ElementData { | |
var tag_name: String; | |
var attributes: [String: String]; | |
} | |
// Our HTML superset | |
class HTMLElement:Node { | |
var attributes = [String: String](); | |
var childNodes: [AnyObject] = [HTMLElement](); | |
var nodeName: NodeType; | |
func addAttribute(name:String, value:String) { | |
attributes[name] = value; | |
} | |
func appendChild(newNode: HTMLElement) { | |
childNodes.append(newNode); | |
} | |
init() { | |
nodeName = NodeType.Element(ElementData(tag_name: "HTMLElement", attributes: self.attributes)); | |
} | |
} | |
class HTMLDivElement:HTMLElement { | |
override init() { | |
super.init(); | |
nodeName = NodeType.Element(ElementData(tag_name: "HTMLDivElement", attributes: self.attributes)); | |
} | |
} | |
// DOM API | |
class Document { | |
var body = HTMLElement(); | |
init() { | |
} | |
func createElement(tagName: String) -> HTMLElement { | |
switch(tagName) { | |
case "HTMLDivElement": | |
return HTMLDivElement(); | |
default: | |
return HTMLElement(); | |
} | |
} | |
} | |
var document = Document(); | |
// create new div | |
var exampleDiv = document.createElement("HTMLDivElement"); | |
exampleDiv.addAttribute("id", value: "div 1"); | |
var exampleDiv2 = document.createElement("HTMLDivElement"); | |
exampleDiv2.addAttribute("id", value: "div 2"); | |
// append to body | |
document.body.appendChild(exampleDiv); | |
document.body.appendChild(exampleDiv2); | |
// sub div | |
var subDiv = document.createElement("HTMLDivElement"); | |
subDiv.addAttribute("id", value: "subDiv 1"); | |
// insert in example div | |
exampleDiv.appendChild(subDiv); | |
print(document.body.childNodes.count); | |
print(exampleDiv.attributes); | |
print(exampleDiv.childNodes.count); | |
print((exampleDiv.childNodes[0] as! HTMLDivElement).attributes); | |
print(exampleDiv2.attributes); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment