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