39859a85f9d401377cf8c126791ebfe224c6315c
[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) { mediator.nodeHovered($(e.target));});\r
19             this.node.on('mouseout', '[wlxml-tag]', function(e) { mediator.nodeBlured($(e.target));});\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);\r
95             \r
96             this.gridToggled = false;
97         },\r
98         getMetaData: function() {\r
99             var toret = {};\r
100             this.metaTable.find('tr').each(function() {\r
101                 var tr = $(this);\r
102                 var inputs = $(this).find('td [contenteditable]');\r
103                 var key = $(inputs[0]).text();\r
104                 var value = $(inputs[1]).text();\r
105                 toret[key] = value;\r
106             });\r
107             console.log(toret);\r
108             return toret;\r
109         },\r
110         setMetaData: function(metadata) {\r
111             var view = this;\r
112             this.metaTable.find('tr').remove();\r
113             _.each(_.keys(metadata), function(key) {    \r
114                 view._addMetaRow(key, metadata[key]);\r
115             });\r
116         },\r
117         setBody: function(HTMLTree) {\r
118             this.node.find('#rng-visualEditor-content').html(HTMLTree);\r
119         },\r
120         getBody: function() {\r
121             return this.node.find('#rng-visualEditor-content').html();\r
122         }, \r
123         _markSelected: function(node) {\r
124             this.node.find('.rng-current').removeClass('rng-current');\r
125             node.addClass('rng-current');\r
126             this.currentNode = node;\r
127             mediator.nodeSelected(node);\r
128         },\r
129         selectNode: function(node) {\r
130             view._markSelected(node);\r
131             var range = document.createRange();\r
132             range.selectNodeContents(node[0]);\r
133             range.collapse(false);\r
134 \r
135             var selection = document.getSelection();\r
136             selection.removeAllRanges()\r
137             selection.addRange(range);\r
138         },\r
139         selectNodeById: function(id) {\r
140             var node = this.node.find('#'+id);\r
141             if(node)\r
142                 this.selectNode(node);\r
143         },\r
144         highlightNode: function(node) {\r
145             if(!this.gridToggled)\r
146                 node.addClass('rng-hover');\r
147         },\r
148         dimNode: function(node) {\r
149             if(!this.gridToggled)\r
150                 node.removeClass('rng-hover');\r
151         },\r
152         highlightNodeById: function(id) {\r
153             var node = this.node.find('#'+id);\r
154             if(node)\r
155                 this.highlightNode(node);\r
156         },\r
157         dimNodeById: function(id) {\r
158             var node = this.node.find('#'+id);\r
159             if(node)\r
160                 this.dimNode(node);\r
161         },\r
162         selectFirstNode: function() {\r
163             var firstNodeWithText = this.node.find('[wlxml-tag]').filter(function() {\r
164                 return $(this).clone().children().remove().end().text().trim() !== '';\r
165             }).first();\r
166             var node;\r
167             if(firstNodeWithText.length)\r
168                 node = $(firstNodeWithText[0])\r
169             else {\r
170                 node = this.node.find('[wlxml-class|="p"]')\r
171             }\r
172             this.selectNode(node);\r
173         },\r
174         _addMetaRow: function(key, value) {\r
175             var newRow = $(sandbox.getTemplate('metaItem')({key: key || '', value: value || ''}));\r
176             newRow.appendTo(this.metaTable);\r
177             return newRow;\r
178         },\r
179         toggleGrid: function(toggle) {\r
180             this.node.find('[wlxml-tag]').toggleClass('rng-hover', toggle);\r
181             this.gridToggled = toggle;\r
182         }\r
183     };\r
184     \r
185     \r
186     var sideBarView = {\r
187         node: view.node.find('#rng-visualEditor-sidebar'),\r
188         setup: function() {\r
189             var view = this;\r
190             this.node.find('#rng-visualEditor-sidebarButtons a').click(function(e) {\r
191                 e.preventDefault();\r
192                 var target = $(e.currentTarget);\r
193                 if(!target.attr('data-content-id'))\r
194                     return;\r
195                 view.selectTab(target.attr('data-content-id'));\r
196             });\r
197             view.selectTab('rng-visualEditor-edit');\r
198             \r
199             view.node.on('change', '.rng-visualEditor-editPaneNodeForm select', function(e) {\r
200                 var target = $(e.target);\r
201                 var attr = target.attr('id').split('-')[2].split('editPane')[1].substr(0,3) === 'Tag' ? 'tag' : 'class';\r
202                 mediator.getCurrentNode().attr('wlxml-'+attr, target.val());\r
203                 isDirty = true;\r
204             });\r
205             \r
206             view.node.on('change', '.rng-visualEditor-editPaneSelectionForm select', function(e) {\r
207                 var target = $(e.target);\r
208                 var selection = window.getSelection();\r
209                 if(selection.anchorNode === selection.focusNode && selection.anchorNode.nodeType === Node.TEXT_NODE) {\r
210                     var startOffset = selection.anchorOffset;\r
211                     var endOffset = selection.focusOffset;\r
212                     if(startOffset > endOffset) {\r
213                         var tmp = startOffset;\r
214                         startOffset = endOffset;\r
215                         endOffset = tmp;\r
216                     }\r
217                     var node = selection.anchorNode;\r
218                     var prefix = node.data.substr(0, startOffset);\r
219                     var suffix = node.data.substr(endOffset);\r
220                     var core = node.data.substr(startOffset, endOffset - startOffset);\r
221                     var newNode = $('<span wlxml-tag="' + target.val() + '">' + core + '</span>');\r
222                     $(node).replaceWith(newNode);\r
223                     newNode.before(prefix);\r
224                     newNode.after(suffix);\r
225                     mediator.nodeCreated(newNode);\r
226                     isDirty = true;\r
227                 }\r
228             });\r
229             \r
230             view.node.on('click', '.rng-visualEditor-editPaneSurrouding a', function(e) {\r
231                 var target = $(e.target);\r
232                 mediator.nodeDimmedById(target.attr('data-id'));\r
233                 mediator.nodeSelectedById(target.attr('data-id'));\r
234             });\r
235             \r
236             view.node.on('mouseenter', '.rng-visualEditor-editPaneSurrouding a', function(e) {\r
237                 var target = $(e.target);\r
238                 mediator.nodeHighlightedById(target.attr('data-id')); \r
239             });\r
240             view.node.on('mouseleave', '.rng-visualEditor-editPaneSurrouding a', function(e) {\r
241                 var target = $(e.target);\r
242                 mediator.nodeDimmedById(target.attr('data-id')); \r
243             });\r
244         },\r
245         selectTab: function(id) {\r
246            this.node.find('.rng-visualEditor-sidebarContentItem').hide();\r
247            this.node.find('#'+id).show();\r
248            this.node.find('#rng-visualEditor-sidebarButtons li').removeClass('active');\r
249            this.node.find('#rng-visualEditor-sidebarButtons li a[data-content-id=' + id + ']').parent().addClass('active');\r
250         \r
251         },\r
252         updateEditPane: function(node) {\r
253             var pane = this.node.find('#rng-visualEditor-edit');\r
254             pane.html( $(sandbox.getTemplate('editPane')({tag: node.attr('wlxml-tag'), klass: node.attr('wlxml-class')})));\r
255             \r
256             var parent = {\r
257                 repr: node.parent().attr('wlxml-tag') + ' / ' + (node.parent().attr('wlxml-class') || '[[no class]]'),\r
258                 id: node.parent().attr('id')\r
259             }\r
260             var children = [];\r
261             node.children().each(function() {\r
262                 var child = $(this);\r
263                 children.push({repr: child.attr('wlxml-tag') + ' / ' + (child.attr('wlxml-class') || '[[no class]]'), id: child.attr('id')});\r
264             });\r
265             var naviTemplate = sandbox.getTemplate('editPaneNavigation')({parent: parent, children: children});\r
266             pane.find('.rng-visualEditor-editPaneSurrouding > div').html($(naviTemplate));\r
267         },\r
268         highlightNode: function(id) {\r
269             var pane = this.node.find('#rng-visualEditor-edit');\r
270             pane.find('a[data-id="'+id+'"]').addClass('rng-hover');\r
271         },\r
272         dimNode: function(id) {\r
273             var pane = this.node.find('#rng-visualEditor-edit');\r
274             pane.find('a[data-id="' +id+'"]').removeClass('rng-hover');\r
275         }\r
276     }\r
277     \r
278     var toolbarView = {\r
279         node: view.node.find('#rng-visualEditor-toolbar'),\r
280         setup: function() {\r
281             var view = this;\r
282             \r
283             view.node.find('button').click(function(e) {\r
284                 var btn = $(e.currentTarget);\r
285                 if(btn.attr('data-btn-type') === 'toggle') {\r
286                     btn.toggleClass('active')\r
287                     mediator.toolbarButtonToggled(btn.attr('data-btn'), btn.hasClass('active'));\r
288                 }\r
289             });\r
290         }\r
291     }\r
292     \r
293     view.setup();\r
294     sideBarView.setup();\r
295     toolbarView.setup();\r
296     \r
297     var mediator = {\r
298         getCurrentNode: function() {\r
299             return view.currentNode;\r
300         },\r
301         nodeCreated: function(node) {\r
302             view.selectNode(node);\r
303             \r
304         },\r
305         nodeSelected: function(node) {\r
306             sideBarView.updateEditPane(node);\r
307         },\r
308         nodeSelectedById: function(id) {\r
309             view.selectNodeById(id);\r
310         },\r
311         nodeHighlightedById: function(id) {\r
312             view.highlightNodeById(id);\r
313         },\r
314         nodeDimmedById: function(id) {\r
315             view.dimNodeById(id);\r
316         },\r
317         toolbarButtonToggled: function(btn, toggle) {\r
318             if(btn === 'grid')\r
319                 view.toggleGrid(toggle);\r
320         },\r
321         nodeHovered: function(node) {\r
322             view.highlightNode(node);\r
323             sideBarView.highlightNode(node.attr('id'));\r
324         },\r
325         nodeBlured: function(node) {\r
326             view.dimNode(node);\r
327             sideBarView.dimNode(node.attr('id'));\r
328         }\r
329         \r
330     }\r
331     \r
332     var isDirty = false;\r
333     var wasShownAlready = false;\r
334     \r
335     \r
336     return {\r
337         start: function() {\r
338             sandbox.publish('ready');\r
339         },\r
340         getView: function() {\r
341             return view.node;\r
342         },\r
343         setDocument: function(xml) {\r
344             var transformed = transformations.fromXML.getDocumentDescription(xml);\r
345             view.setBody(transformed.HTMLTree);\r
346             view.setMetaData(transformed.metadata);\r
347             isDirty = false;\r
348         },\r
349         getDocument: function() {\r
350             return transformations.toXML.getXML({HTMLTree: view.getBody(), metadata: view.getMetaData()});\r
351         },\r
352         isDirty: function() {\r
353             return isDirty;\r
354         },\r
355         setDirty: function(dirty) {\r
356             isDirty = dirty;\r
357         },\r
358         onShowed: function() {\r
359             if(!wasShownAlready) {\r
360                 wasShownAlready = true;\r
361                 view.selectFirstNode();\r
362             }\r
363         }\r
364     \r
365     }\r
366 };