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