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