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