5e269789fcf6f03a4533e03b436c40cb60762f53
[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         toggleTags: function(toggle) {\r
184         \r
185         }\r
186     };\r
187     \r
188     \r
189     var sideBarView = {\r
190         node: view.node.find('#rng-visualEditor-sidebar'),\r
191         setup: function() {\r
192             var view = this;\r
193             this.node.find('#rng-visualEditor-sidebarButtons a').click(function(e) {\r
194                 e.preventDefault();\r
195                 var target = $(e.currentTarget);\r
196                 if(!target.attr('data-content-id'))\r
197                     return;\r
198                 view.selectTab(target.attr('data-content-id'));\r
199             });\r
200             view.selectTab('rng-visualEditor-edit');\r
201             \r
202             view.node.on('change', '.rng-visualEditor-editPaneNodeForm select', function(e) {\r
203                 var target = $(e.target);\r
204                 var attr = target.attr('id').split('-')[2].split('editPane')[1].substr(0,3) === 'Tag' ? 'tag' : 'class';\r
205                 mediator.getCurrentNode().attr('wlxml-'+attr, target.val());\r
206                 isDirty = true;\r
207             });\r
208             \r
209             view.node.on('change', '.rng-visualEditor-editPaneSelectionForm select', function(e) {\r
210                 var target = $(e.target);\r
211                 var selection = window.getSelection();\r
212                 if(selection.anchorNode === selection.focusNode && selection.anchorNode.nodeType === Node.TEXT_NODE) {\r
213                     var startOffset = selection.anchorOffset;\r
214                     var endOffset = selection.focusOffset;\r
215                     if(startOffset > endOffset) {\r
216                         var tmp = startOffset;\r
217                         startOffset = endOffset;\r
218                         endOffset = tmp;\r
219                     }\r
220                     var node = selection.anchorNode;\r
221                     var prefix = node.data.substr(0, startOffset);\r
222                     var suffix = node.data.substr(endOffset);\r
223                     var core = node.data.substr(startOffset, endOffset - startOffset);\r
224                     var newNode = $('<span wlxml-tag="' + target.val() + '">' + core + '</span>');\r
225                     $(node).replaceWith(newNode);\r
226                     newNode.before(prefix);\r
227                     newNode.after(suffix);\r
228                     mediator.nodeCreated(newNode);\r
229                     isDirty = true;\r
230                 }\r
231             });\r
232             \r
233             view.node.on('click', '.rng-visualEditor-editPaneSurrouding a', function(e) {\r
234                 var target = $(e.target);\r
235                 mediator.nodeDimmedById(target.attr('data-id'));\r
236                 mediator.nodeSelectedById(target.attr('data-id'));\r
237             });\r
238             \r
239             view.node.on('mouseenter', '.rng-visualEditor-editPaneSurrouding a', function(e) {\r
240                 var target = $(e.target);\r
241                 mediator.nodeHighlightedById(target.attr('data-id')); \r
242             });\r
243             view.node.on('mouseleave', '.rng-visualEditor-editPaneSurrouding a', function(e) {\r
244                 var target = $(e.target);\r
245                 mediator.nodeDimmedById(target.attr('data-id')); \r
246             });\r
247         },\r
248         selectTab: function(id) {\r
249            this.node.find('.rng-visualEditor-sidebarContentItem').hide();\r
250            this.node.find('#'+id).show();\r
251            this.node.find('#rng-visualEditor-sidebarButtons li').removeClass('active');\r
252            this.node.find('#rng-visualEditor-sidebarButtons li a[data-content-id=' + id + ']').parent().addClass('active');\r
253         \r
254         },\r
255         updateEditPane: function(node) {\r
256             var pane = this.node.find('#rng-visualEditor-edit');\r
257             pane.html( $(sandbox.getTemplate('editPane')({tag: node.attr('wlxml-tag'), klass: node.attr('wlxml-class')})));\r
258             \r
259             var parent = {\r
260                 repr: node.parent().attr('wlxml-tag') + ' / ' + (node.parent().attr('wlxml-class') || '[[no class]]'),\r
261                 id: node.parent().attr('id')\r
262             }\r
263             var children = [];\r
264             node.children().each(function() {\r
265                 var child = $(this);\r
266                 children.push({repr: child.attr('wlxml-tag') + ' / ' + (child.attr('wlxml-class') || '[[no class]]'), id: child.attr('id')});\r
267             });\r
268             var naviTemplate = sandbox.getTemplate('editPaneNavigation')({parent: parent, children: children});\r
269             pane.find('.rng-visualEditor-editPaneSurrouding > div').html($(naviTemplate));\r
270         },\r
271         highlightNode: function(id) {\r
272             var pane = this.node.find('#rng-visualEditor-edit');\r
273             pane.find('a[data-id="'+id+'"]').addClass('rng-hover');\r
274         },\r
275         dimNode: function(id) {\r
276             var pane = this.node.find('#rng-visualEditor-edit');\r
277             pane.find('a[data-id="' +id+'"]').removeClass('rng-hover');\r
278         }\r
279     }\r
280     \r
281     var toolbarView = {\r
282         node: view.node.find('#rng-visualEditor-toolbar'),\r
283         setup: function() {\r
284             var view = this;\r
285             \r
286             view.node.find('button').click(function(e) {\r
287                 var btn = $(e.currentTarget);\r
288                 if(btn.attr('data-btn-type') === 'toggle') {\r
289                     btn.toggleClass('active')\r
290                     mediator.toolbarButtonToggled(btn.attr('data-btn'), btn.hasClass('active'));\r
291                 }\r
292             });\r
293         }\r
294     }\r
295     \r
296     view.setup();\r
297     sideBarView.setup();\r
298     toolbarView.setup();\r
299     \r
300     var mediator = {\r
301         getCurrentNode: function() {\r
302             return view.currentNode;\r
303         },\r
304         nodeCreated: function(node) {\r
305             view.selectNode(node);\r
306             \r
307         },\r
308         nodeSelected: function(node) {\r
309             sideBarView.updateEditPane(node);\r
310         },\r
311         nodeSelectedById: function(id) {\r
312             view.selectNodeById(id);\r
313         },\r
314         nodeHighlightedById: function(id) {\r
315             view.highlightNodeById(id);\r
316         },\r
317         nodeDimmedById: function(id) {\r
318             view.dimNodeById(id);\r
319         },\r
320         toolbarButtonToggled: function(btn, toggle) {\r
321             if(btn === 'grid')\r
322                 view.toggleGrid(toggle);\r
323             if(btn === 'tags')\r
324                 view.toggleTags(toggle);\r
325         },\r
326         nodeHovered: function(node) {\r
327             view.highlightNode(node);\r
328             sideBarView.highlightNode(node.attr('id'));\r
329         },\r
330         nodeBlured: function(node) {\r
331             view.dimNode(node);\r
332             sideBarView.dimNode(node.attr('id'));\r
333         }\r
334         \r
335     }\r
336     \r
337     var isDirty = false;\r
338     var wasShownAlready = false;\r
339     \r
340     \r
341     return {\r
342         start: function() {\r
343             sandbox.publish('ready');\r
344         },\r
345         getView: function() {\r
346             return view.node;\r
347         },\r
348         setDocument: function(xml) {\r
349             var transformed = transformations.fromXML.getDocumentDescription(xml);\r
350             view.setBody(transformed.HTMLTree);\r
351             view.setMetaData(transformed.metadata);\r
352             isDirty = false;\r
353         },\r
354         getDocument: function() {\r
355             return transformations.toXML.getXML({HTMLTree: view.getBody(), metadata: view.getMetaData()});\r
356         },\r
357         isDirty: function() {\r
358             return isDirty;\r
359         },\r
360         setDirty: function(dirty) {\r
361             isDirty = dirty;\r
362         },\r
363         onShowed: function() {\r
364             if(!wasShownAlready) {\r
365                 wasShownAlready = true;\r
366                 view.selectFirstNode();\r
367             }\r
368         }\r
369     \r
370     }\r
371 };