f7ae32caaa28b083c884e265eab1bbd2b12b610c
[fnpeditor.git] / modules / visualEditor.js
1 rng.modules.visualEditor = function(sandbox) {\r
2     var transformations = rng.modules.visualEditor.transformations;\r
3 \r
4     var view = {\r
5         node: $(sandbox.getTemplate('main')()),\r
6         currentNode: null,\r
7         setup: function() {\r
8             var view = this;\r
9
10             this.node.find('#rng-visualEditor-content').on('keyup', function() {\r
11                 isDirty = true;\r
12             });\r
13             \r
14             this.node.find('#rng-visualEditor-meta').on('keyup', function() {\r
15                 isDirty = true;\r
16             });\r
17
18             this.node.on('mouseover', '[wlxml-tag]', function(e) { $(e.target).addClass('rng-hover')});\r
19             this.node.on('mouseout', '[wlxml-tag]', function(e) { $(e.target).removeClass('rng-hover')});\r
20             this.node.on('click', '[wlxml-tag]', function(e) {\r
21                 console.log('clicked node type: '+e.target.nodeType);\r
22                 view._markSelected($(e.target));\r
23             });\r
24 \r
25             this.node.on('keyup', '#rng-visualEditor-contentWrapper', function(e) {\r
26                 var anchor = $(window.getSelection().anchorNode);\r
27                 if(anchor[0].nodeType === Node.TEXT_NODE)\r
28                     anchor = anchor.parent();\r
29                 if(!anchor.is('[wlxml-tag]'))\r
30                     return;\r
31                 view._markSelected(anchor);\r
32             });\r
33             \r
34             this.node.on('keydown', '#rng-visualEditor-contentWrapper', function(e) {\r
35                 if(e.which === 13) { \r
36                     e.preventDefault();\r
37                     var anchor = $(window.getSelection().anchorNode);\r
38                     if(anchor[0].nodeType === Node.TEXT_NODE)\r
39                         anchor = anchor.parent();\r
40                     var newNode = anchor.clone().empty();\r
41                     newNode.attr('id', '');\r
42                     anchor.after(newNode);\r
43                     view.selectNode(newNode);\r
44                 }\r
45             });\r
46             \r
47             \r
48             var metaTable = this.metaTable = this.node.find('#rng-visualEditor-meta table');\r
49             \r
50             this.node.find('.rng-visualEditor-metaAddBtn').click(function() {\r
51                 var newRow = view._addMetaRow('', '');\r
52                 $(newRow.find('td div')[0]).focus();\r
53                 isDirty = true;\r
54             });\r
55             \r
56             this.metaTable.on('click', '.rng-visualEditor-metaRemoveBtn', function(e) {\r
57                 $(e.target).closest('tr').remove();\r
58                 isDirty = true;\r
59             });\r
60             \r
61             this.metaTable.on('keydown', '[contenteditable]', function(e) {\r
62                 console.log(e.which);\r
63                 if(e.which === 13) { \r
64                     if($(document.activeElement).hasClass('rng-visualEditor-metaItemKey')) {\r
65                         metaTable.find('.rng-visualEditor-metaItemValue').focus();\r
66                     } else {\r
67                         var input = $('<input>');\r
68                         input.appendTo('body').focus()\r
69                         view.node.find('.rng-visualEditor-metaAddBtn').focus();\r
70                         input.remove();\r
71                     }\r
72                     e.preventDefault();\r
73                 }\r
74                 \r
75             });\r
76             \r
77             \r
78             var observer = new MutationObserver(function(mutations) {\r
79               mutations.forEach(function(mutation) {\r
80                 if(mutation.addedNodes.length > 0) {\r
81                     console.log(mutation.addedNodes);\r
82                 }\r
83                 _.each(mutation.addedNodes, function(node) {\r
84                     node = $(node);\r
85                     node.parent().find('[wlxml-tag]').each(function() {\r
86                         tag = $(this);\r
87                         if(!tag.attr('id'))\r
88                             tag.attr('id', 'xxxxxxxx-xxxx-xxxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {var r = Math.random()*16|0,v=c=='x'?r:r&0x3|0x8;return v.toString(16);}));\r
89                     });\r
90                 });\r
91               });    \r
92             });\r
93             var config = { attributes: true, childList: true, characterData: true, subtree: true };\r
94             observer.observe(this.node.find('#rng-visualEditor-contentWrapper')[0], config);
95         },\r
96         getMetaData: function() {\r
97             var toret = {};\r
98             this.metaTable.find('tr').each(function() {\r
99                 var tr = $(this);\r
100                 var inputs = $(this).find('td [contenteditable]');\r
101                 var key = $(inputs[0]).text();\r
102                 var value = $(inputs[1]).text();\r
103                 toret[key] = value;\r
104             });\r
105             console.log(toret);\r
106             return toret;\r
107         },\r
108         setMetaData: function(metadata) {\r
109             var view = this;\r
110             this.metaTable.find('tr').remove();\r
111             _.each(_.keys(metadata), function(key) {    \r
112                 view._addMetaRow(key, metadata[key]);\r
113             });\r
114         },\r
115         setBody: function(HTMLTree) {\r
116             this.node.find('#rng-visualEditor-content').html(HTMLTree);\r
117         },\r
118         getBody: function() {\r
119             return this.node.find('#rng-visualEditor-content').html();\r
120         }, \r
121         _markSelected: function(node) {\r
122             this.node.find('.rng-current').removeClass('rng-current');\r
123             node.addClass('rng-current');\r
124             this.currentNode = node;\r
125             mediator.nodeSelected(node);\r
126         },\r
127         selectNode: function(node) {\r
128             view._markSelected(node);\r
129             var range = document.createRange();\r
130             range.selectNodeContents(node[0]);\r
131             range.collapse(false);\r
132 \r
133             var selection = document.getSelection();\r
134             selection.removeAllRanges()\r
135             selection.addRange(range);\r
136         },\r
137         selectNodeById: function(id) {\r
138             var node = this.node.find('#'+id);\r
139             if(node)\r
140                 this.selectNode(node);\r
141         },\r
142         selectFirstNode: function() {\r
143             var firstNodeWithText = this.node.find('[wlxml-tag]').filter(function() {\r
144                 return $(this).clone().children().remove().end().text().trim() !== '';\r
145             }).first();\r
146             var node;\r
147             if(firstNodeWithText.length)\r
148                 node = $(firstNodeWithText[0])\r
149             else {\r
150                 node = this.node.find('[wlxml-class|="p"]')\r
151             }\r
152             this.selectNode(node);\r
153         },\r
154         _addMetaRow: function(key, value) {\r
155             var newRow = $(sandbox.getTemplate('metaItem')({key: key || '', value: value || ''}));\r
156             newRow.appendTo(this.metaTable);\r
157             return newRow;\r
158         }\r
159     };\r
160     \r
161     \r
162     var sideBarView = {\r
163         node: view.node.find('#rng-visualEditor-sidebar'),\r
164         setup: function() {\r
165             var view = this;\r
166             this.node.find('#rng-visualEditor-sidebarButtons a').click(function(e) {\r
167                 e.preventDefault();\r
168                 var target = $(e.currentTarget);\r
169                 if(!target.attr('data-content-id'))\r
170                     return;\r
171                 view.selectTab(target.attr('data-content-id'));\r
172             });\r
173             view.selectTab('rng-visualEditor-edit');\r
174             \r
175             view.node.on('change', '.rng-visualEditor-editPaneNodeForm select', function(e) {\r
176                 var target = $(e.target);\r
177                 var attr = target.attr('id').split('-')[2].split('editPane')[1].substr(0,3) === 'Tag' ? 'tag' : 'class';\r
178                 mediator.getCurrentNode().attr('wlxml-'+attr, target.val());\r
179                 isDirty = true;\r
180             });\r
181             \r
182             view.node.on('change', '.rng-visualEditor-editPaneSelectionForm select', function(e) {\r
183                 var target = $(e.target);\r
184                 var selection = window.getSelection();\r
185                 if(selection.anchorNode === selection.focusNode && selection.anchorNode.nodeType === Node.TEXT_NODE) {\r
186                     var startOffset = selection.anchorOffset;\r
187                     var endOffset = selection.focusOffset;\r
188                     if(startOffset > endOffset) {\r
189                         var tmp = startOffset;\r
190                         startOffset = endOffset;\r
191                         endOffset = tmp;\r
192                     }\r
193                     var node = selection.anchorNode;\r
194                     var prefix = node.data.substr(0, startOffset);\r
195                     var suffix = node.data.substr(endOffset);\r
196                     var core = node.data.substr(startOffset, endOffset - startOffset);\r
197                     var newNode = $('<span wlxml-tag="' + target.val() + '">' + core + '</span>');\r
198                     $(node).replaceWith(newNode);\r
199                     newNode.before(prefix);\r
200                     newNode.after(suffix);\r
201                     mediator.nodeCreated(newNode);\r
202                     isDirty = true;\r
203                 }\r
204             });\r
205             \r
206             view.node.on('click', '.rng-visualEditor-editPaneSurrouding a', function(e) {\r
207                 var target = $(e.target);\r
208                 mediator.nodeSelectedById(target.attr('data-id'));\r
209             });\r
210         },\r
211         selectTab: function(id) {\r
212            this.node.find('.rng-visualEditor-sidebarContentItem').hide();\r
213            this.node.find('#'+id).show();\r
214            this.node.find('#rng-visualEditor-sidebarButtons li').removeClass('active');\r
215            this.node.find('#rng-visualEditor-sidebarButtons li a[data-content-id=' + id + ']').parent().addClass('active');\r
216         \r
217         },\r
218         updateEditPane: function(node) {\r
219             var pane = this.node.find('#rng-visualEditor-edit');\r
220             pane.html( $(sandbox.getTemplate('editPane')({tag: node.attr('wlxml-tag'), klass: node.attr('wlxml-class')})));\r
221             \r
222             var parent = {\r
223                 repr: node.parent().attr('wlxml-tag') + ' / ' + (node.parent().attr('wlxml-class') || '[[no class]]'),\r
224                 id: node.parent().attr('id')\r
225             }\r
226             var children = [];\r
227             node.children().each(function() {\r
228                 var child = $(this);\r
229                 children.push({repr: child.attr('wlxml-tag') + ' / ' + (child.attr('wlxml-class') || '[[no class]]'), id: child.attr('id')});\r
230             });\r
231             var naviTemplate = sandbox.getTemplate('editPaneNavigation')({parent: parent, children: children});\r
232             pane.find('.rng-visualEditor-editPaneSurrouding > div').html($(naviTemplate));\r
233         }\r
234     }\r
235     \r
236     view.setup();\r
237     sideBarView.setup();\r
238     \r
239     var mediator = {\r
240         getCurrentNode: function() {\r
241             return view.currentNode;\r
242         },\r
243         nodeCreated: function(node) {\r
244             view.selectNode(node);\r
245             \r
246         },\r
247         nodeSelected: function(node) {\r
248             sideBarView.updateEditPane(node);\r
249         },\r
250         nodeSelectedById: function(id) {\r
251             view.selectNodeById(id);\r
252         }\r
253     }\r
254     \r
255     var isDirty = false;\r
256     var wasShownAlready = false;\r
257     \r
258     \r
259     return {\r
260         start: function() {\r
261             sandbox.publish('ready');\r
262         },\r
263         getView: function() {\r
264             return view.node;\r
265         },\r
266         setDocument: function(xml) {\r
267             var transformed = transformations.fromXML.getDocumentDescription(xml);\r
268             view.setBody(transformed.HTMLTree);\r
269             view.setMetaData(transformed.metadata);\r
270             isDirty = false;\r
271         },\r
272         getDocument: function() {\r
273             return transformations.toXML.getXML({HTMLTree: view.getBody(), metadata: view.getMetaData()});\r
274         },\r
275         isDirty: function() {\r
276             return isDirty;\r
277         },\r
278         setDirty: function(dirty) {\r
279             isDirty = dirty;\r
280         },\r
281         onShowed: function() {\r
282             if(!wasShownAlready) {\r
283                 wasShownAlready = true;\r
284                 view.selectFirstNode();\r
285             }\r
286         }\r
287     \r
288     }\r
289 };