Cleaning up files structure
[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                 var target = $(e.currentTarget);\r
282                 if(!target.attr('data-content-id'))\r
283                     return;\r
284                 view.selectTab(target.attr('data-content-id'));\r
285             });\r
286             view.selectTab('rng-visualEditor-edit');\r
287             \r
288             view.node.on('change', '.rng-visualEditor-editPaneNodeForm select', function(e) {\r
289                 var target = $(e.target);\r
290                 var attr = target.attr('id').split('-')[2].split('editPane')[1].substr(0,3) === 'Tag' ? 'tag' : 'class';\r
291                 mediator.getCurrentNode().attr('wlxml-'+attr, target.val());\r
292                 isDirty = true;\r
293             });\r
294                        \r
295             view.node.on('click', '.rng-visualEditor-editPaneSurrouding a', function(e) {\r
296                 var target = $(e.target);\r
297                 mediator.nodeDimmedById(target.attr('data-id'));\r
298                 mediator.nodeSelectedById(target.attr('data-id'));\r
299             });\r
300             \r
301             view.node.on('mouseenter', '.rng-visualEditor-editPaneSurrouding a', function(e) {\r
302                 var target = $(e.target);\r
303                 mediator.nodeHighlightedById(target.attr('data-id')); \r
304             });\r
305             view.node.on('mouseleave', '.rng-visualEditor-editPaneSurrouding a', function(e) {\r
306                 var target = $(e.target);\r
307                 mediator.nodeDimmedById(target.attr('data-id')); \r
308             });\r
309         },\r
310         selectTab: function(id) {\r
311            this.node.find('.rng-visualEditor-sidebarContentItem').hide();\r
312            this.node.find('#'+id).show();\r
313            this.node.find('#rng-visualEditor-sidebarButtons li').removeClass('active');\r
314            this.node.find('#rng-visualEditor-sidebarButtons li a[data-content-id=' + id + ']').parent().addClass('active');\r
315         \r
316         },\r
317         updateEditPane: function(node) {\r
318             var pane = this.node.find('#rng-visualEditor-edit');\r
319             var parentClass = node.parent().attr('wlxml-class');\r
320             pane.html( $(sandbox.getTemplate('editPane')({tag: node.attr('wlxml-tag'), klass: node.attr('wlxml-class')})));\r
321             \r
322             var parent = node.parent('[wlxml-tag]').length ? {\r
323                 repr: node.parent().attr('wlxml-tag') + (parentClass ? ' / ' + parentClass : ''),\r
324                 id: node.parent().attr('id')\r
325             } : undefined;\r
326             var children = [];\r
327             node.children('[wlxml-tag]').each(function() {\r
328                 var child = $(this);\r
329                 var childClass = child.attr('wlxml-class');\r
330                 children.push({repr: child.attr('wlxml-tag') + (childClass ? ' / ' + childClass : ''), id: child.attr('id')});\r
331             });\r
332             var naviTemplate = sandbox.getTemplate('editPaneNavigation')({parent: parent, children: children});\r
333             pane.find('.rng-visualEditor-editPaneSurrouding > div').html($(naviTemplate));\r
334         },\r
335         highlightNode: function(id) {\r
336             var pane = this.node.find('#rng-visualEditor-edit');\r
337             pane.find('a[data-id="'+id+'"]').addClass('rng-hover');\r
338         },\r
339         dimNode: function(id) {\r
340             var pane = this.node.find('#rng-visualEditor-edit');\r
341             pane.find('a[data-id="' +id+'"]').removeClass('rng-hover');\r
342         }\r
343     }\r
344     \r
345     var toolbarView = {\r
346         node: view.node.find('#rng-visualEditor-toolbar'),\r
347         setup: function() {\r
348             var view = this;\r
349             \r
350             view.node.find('button').click(function(e) {\r
351                 var btn = $(e.currentTarget);\r
352                 if(btn.attr('data-btn-type') === 'toggle') {\r
353                     btn.toggleClass('active')\r
354                     mediator.toolbarButtonToggled(btn.attr('data-btn'), btn.hasClass('active'));\r
355                 }\r
356                 if(btn.attr('data-btn-type') === 'cmd') {\r
357                     mediator.toolbarButtonCmd(btn.attr('data-btn'), btn.attr('data-meta'));\r
358                 }\r
359             });\r
360         },\r
361         getOption: function(option) {\r
362             return this.node.find('.rng-visualEditor-toolbarOption[data-option=' + option +']').val();\r
363         }\r
364     }\r
365     \r
366     var statusBarView = {\r
367         node: view.node.find('#rng-visualEditor-statusbar'),\r
368         setup: function() {\r
369             var view = this;\r
370             view.node.on('mouseenter', 'a', function(e) {\r
371                 var target = $(e.target);\r
372                 mediator.nodeHighlightedById(target.attr('data-id')); \r
373             });\r
374             view.node.on('mouseleave', 'a', function(e) {\r
375                 var target = $(e.target);\r
376                 mediator.nodeDimmedById(target.attr('data-id')); \r
377             });\r
378             view.node.on('click', 'a', function(e) {\r
379                 e.preventDefault();\r
380                 mediator.nodeSelectedById($(e.target).attr('data-id'));\r
381             });\r
382         },\r
383         \r
384         showNode: function(node) {\r
385             this.node.empty();\r
386             this.node.html(sandbox.getTemplate('statusBarNodeDisplay')({node: node, parents: node.parents('[wlxml-tag]')}));\r
387             //node.parents('[wlxml-tag]')\r
388         },\r
389         \r
390         highlightNode: function(id) {\r
391             this.node.find('a[data-id="'+id+'"]').addClass('rng-hover');\r
392         },\r
393         dimNode: function(id) {\r
394             this.node.find('a[data-id="' +id+'"]').removeClass('rng-hover');\r
395         }\r
396     }\r
397     \r
398     view.setup();\r
399     sideBarView.setup();\r
400     toolbarView.setup();\r
401     statusBarView.setup();\r
402     \r
403     var mediator = {\r
404         getCurrentNode: function() {\r
405             return view.currentNode;\r
406         },\r
407         nodeCreated: function(node) {\r
408             view.selectNode(node);\r
409         },\r
410         nodeSelected: function(node) {\r
411             sideBarView.updateEditPane(node);\r
412             statusBarView.showNode(node);\r
413         },\r
414         nodeSelectedById: function(id) {\r
415             view.selectNodeById(id);\r
416         },\r
417         nodeHighlightedById: function(id) {\r
418             view.highlightNodeById(id);\r
419         },\r
420         nodeDimmedById: function(id) {\r
421             view.dimNodeById(id);\r
422         },\r
423         toolbarButtonToggled: function(btn, toggle) {\r
424             if(btn === 'grid')\r
425                 view.toggleGrid(toggle);\r
426             if(btn === 'tags')\r
427                 view.toggleTags(toggle);\r
428         },\r
429         toolbarButtonCmd: function(btn, meta) {\r
430             if(btn === 'new-node') {\r
431                 var wlxmlTag = toolbarView.getOption('newTag-tag');\r
432                 var wlxmlClass = toolbarView.getOption('newTag-class');\r
433                 if(meta) {\r
434                     var split = meta.split('/');\r
435                     wlxmlTag = split[0];\r
436                     wlxmlClass = split[1];\r
437                 }\r
438                 if(window.getSelection().isCollapsed)\r
439                     view.insertNewNode(wlxmlTag, wlxmlClass);\r
440                 else {\r
441                     this.wrapWithNodeRequest(wlxmlTag, wlxmlClass);\r
442                 }\r
443                     \r
444                     \r
445             }\r
446         },\r
447         nodeHovered: function(node) {\r
448             view.highlightNode(node);\r
449             sideBarView.highlightNode(node.attr('id'));\r
450             statusBarView.highlightNode(node.attr('id'));\r
451         },\r
452         nodeBlured: function(node) {\r
453             view.dimNode(node);\r
454             sideBarView.dimNode(node.attr('id'));\r
455             statusBarView.dimNode(node.attr('id'));\r
456         },\r
457         wrapWithNodeRequest: function(wlxmlTag, wlxmlClass) {\r
458             view.wrapSelectionWithNewNode(wlxmlTag, wlxmlClass);\r
459         }\r
460         \r
461     }\r
462     \r
463     var isDirty = false;\r
464     var wasShownAlready = false;\r
465     \r
466     \r
467     return {\r
468         start: function() {\r
469             sandbox.publish('ready');\r
470         },\r
471         getView: function() {\r
472             return view.node;\r
473         },\r
474         setDocument: function(xml) {\r
475             var transformed = transformations.fromXML.getDocumentDescription(xml);\r
476             view.setBody(transformed.HTMLTree);\r
477             view.setMetaData(transformed.metadata);\r
478             isDirty = false;\r
479         },\r
480         getDocument: function() {\r
481             return transformations.toXML.getXML({HTMLTree: view.getBody(), metadata: view.getMetaData()});\r
482         },\r
483         isDirty: function() {\r
484             return isDirty;\r
485         },\r
486         setDirty: function(dirty) {\r
487             isDirty = dirty;\r
488         },\r
489         onShowed: function() {\r
490             if(!wasShownAlready) {\r
491                 wasShownAlready = true;\r
492                 view.selectFirstNode();\r
493             }\r
494         }\r
495     \r
496     }\r
497 };\r
498 \r
499 });