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