comparing nodes
[fnpeditor.git] / modules / documentCanvas / canvas / documentElement.js
1 define([
2 'libs/jquery-1.9.1.min'
3 ], function($) {
4     
5 'use strict';
6
7 // DocumentElement represents a node from WLXML document rendered inside Canvas
8 var DocumentElement = function(htmlElement) {
9     if(arguments.length === 0)
10         return;
11     this.$element = $(htmlElement);
12     this.wlxmlTag = this.$element.prop('tagName');
13 };
14
15 $.extend(DocumentElement.prototype, {
16     children: function() {
17         var toret = [];
18         if(this instanceof DocumentTextElement)
19             return toret;
20
21
22         var elementContent = this.$element.contents();
23         elementContent.each(function(idx) {
24             var element = documentElementFromHTMLElement(this);
25             if(idx === 0 && elementContent.length > 1 && elementContent[1].nodeType === Node.ELEMENT_NODE && (element instanceof DocumentTextElement) && $.trim($(this).text()) === '')
26                 return true;
27             if(idx > 0 && element instanceof DocumentTextElement) {
28                 if(toret[toret.length-1] instanceof DocumentNodeElement && $.trim($(this).text()) === '')
29                     return true;
30             }
31             toret.push(element);
32         });
33         return toret;
34     },
35
36     sameNode: function(other) {
37         return other && (typeof other === typeof this) && other.$element[0] === this.$element[0];
38     }
39 });
40
41 var DocumentNodeElement = function(htmlElement) {
42     DocumentElement.call(this, htmlElement);
43 };
44
45 var DocumentTextElement = function(htmlElement) {
46     DocumentElement.call(this, htmlElement);  
47 };
48
49 DocumentNodeElement.prototype = new DocumentElement();
50 DocumentTextElement.prototype = new DocumentElement();
51
52 var documentElementFromHTMLElement = function(htmlElement) {
53     if(htmlElement.nodeType === Node.ELEMENT_NODE)
54         return new DocumentNodeElement(htmlElement);
55     if(htmlElement.nodeType === Node.TEXT_NODE)
56         return new DocumentTextElement(htmlElement);
57 }
58
59 return {
60     wrap: function(htmlElement) {
61         return documentElementFromHTMLElement(htmlElement);
62     },
63     DocumentElement: DocumentElement,
64     DocumentNodeElement: DocumentNodeElement,
65     DocumentTextElement: DocumentTextElement
66 };
67
68 });