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