a607d86033a47bd42514c667a1fb03e15d39fb90
[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('click', '.rng-visualEditor-editPaneSurrouding a', function(e) {\r
261                 var target = $(e.target);\r
262                 mediator.nodeDimmedById(target.attr('data-id'));\r
263                 mediator.nodeSelectedById(target.attr('data-id'));\r
264             });\r
265             \r
266             view.node.on('mouseenter', '.rng-visualEditor-editPaneSurrouding a', function(e) {\r
267                 var target = $(e.target);\r
268                 mediator.nodeHighlightedById(target.attr('data-id')); \r
269             });\r
270             view.node.on('mouseleave', '.rng-visualEditor-editPaneSurrouding a', function(e) {\r
271                 var target = $(e.target);\r
272                 mediator.nodeDimmedById(target.attr('data-id')); \r
273             });\r
274         },\r
275         selectTab: function(id) {\r
276            this.node.find('.rng-visualEditor-sidebarContentItem').hide();\r
277            this.node.find('#'+id).show();\r
278            this.node.find('#rng-visualEditor-sidebarButtons li').removeClass('active');\r
279            this.node.find('#rng-visualEditor-sidebarButtons li a[data-content-id=' + id + ']').parent().addClass('active');\r
280         \r
281         },\r
282         updateEditPane: function(node) {\r
283             var pane = this.node.find('#rng-visualEditor-edit');\r
284             pane.html( $(sandbox.getTemplate('editPane')({tag: node.attr('wlxml-tag'), klass: node.attr('wlxml-class')})));\r
285             \r
286             var parent = node.parent('[wlxml-tag]').length ? {\r
287                 repr: node.parent().attr('wlxml-tag') + ' / ' + (node.parent().attr('wlxml-class') || '[[no class]]'),\r
288                 id: node.parent().attr('id')\r
289             } : undefined;\r
290             var children = [];\r
291             node.children('[wlxml-tag]').each(function() {\r
292                 var child = $(this);\r
293                 children.push({repr: child.attr('wlxml-tag') + ' / ' + (child.attr('wlxml-class') || '[[no class]]'), id: child.attr('id')});\r
294             });\r
295             var naviTemplate = sandbox.getTemplate('editPaneNavigation')({parent: parent, children: children});\r
296             pane.find('.rng-visualEditor-editPaneSurrouding > div').html($(naviTemplate));\r
297         },\r
298         highlightNode: function(id) {\r
299             var pane = this.node.find('#rng-visualEditor-edit');\r
300             pane.find('a[data-id="'+id+'"]').addClass('rng-hover');\r
301         },\r
302         dimNode: function(id) {\r
303             var pane = this.node.find('#rng-visualEditor-edit');\r
304             pane.find('a[data-id="' +id+'"]').removeClass('rng-hover');\r
305         }\r
306     }\r
307     \r
308     var toolbarView = {\r
309         node: view.node.find('#rng-visualEditor-toolbar'),\r
310         setup: function() {\r
311             var view = this;\r
312             \r
313             view.node.find('button').click(function(e) {\r
314                 var btn = $(e.currentTarget);\r
315                 if(btn.attr('data-btn-type') === 'toggle') {\r
316                     btn.toggleClass('active')\r
317                     mediator.toolbarButtonToggled(btn.attr('data-btn'), btn.hasClass('active'));\r
318                 }\r
319                 if(btn.attr('data-btn-type') === 'cmd') {\r
320                     mediator.toolbarButtonCmd(btn.attr('data-btn'));\r
321                 }\r
322             });\r
323         },\r
324         getOption: function(option) {\r
325             return this.node.find('.rng-visualEditor-toolbarOption[data-option=' + option +']').val();\r
326         }\r
327     }\r
328     \r
329     view.setup();\r
330     sideBarView.setup();\r
331     toolbarView.setup();\r
332     \r
333     var mediator = {\r
334         getCurrentNode: function() {\r
335             return view.currentNode;\r
336         },\r
337         nodeCreated: function(node) {\r
338             view.selectNode(node);\r
339         },\r
340         nodeSelected: function(node) {\r
341             sideBarView.updateEditPane(node);\r
342         },\r
343         nodeSelectedById: function(id) {\r
344             view.selectNodeById(id);\r
345         },\r
346         nodeHighlightedById: function(id) {\r
347             view.highlightNodeById(id);\r
348         },\r
349         nodeDimmedById: function(id) {\r
350             view.dimNodeById(id);\r
351         },\r
352         toolbarButtonToggled: function(btn, toggle) {\r
353             if(btn === 'grid')\r
354                 view.toggleGrid(toggle);\r
355             if(btn === 'tags')\r
356                 view.toggleTags(toggle);\r
357         },\r
358         toolbarButtonCmd: function(btn) {\r
359             if(btn === 'new-node') {\r
360                 if(window.getSelection().isCollapsed)\r
361                     view.insertNewNode(toolbarView.getOption('newTag-tag'), toolbarView.getOption('newTag-class'));\r
362                 else {\r
363                     this.wrapWithNodeRequest(toolbarView.getOption('newTag-tag'), toolbarView.getOption('newTag-class'));\r
364                 }\r
365                     \r
366                     \r
367             }\r
368         },\r
369         nodeHovered: function(node) {\r
370             view.highlightNode(node);\r
371             sideBarView.highlightNode(node.attr('id'));\r
372         },\r
373         nodeBlured: function(node) {\r
374             view.dimNode(node);\r
375             sideBarView.dimNode(node.attr('id'));\r
376         },\r
377         wrapWithNodeRequest: function(wlxmlTag, wlxmlClass) {\r
378             view.wrapSelectionWithNewNode(wlxmlTag, wlxmlClass);\r
379         }\r
380         \r
381     }\r
382     \r
383     var isDirty = false;\r
384     var wasShownAlready = false;\r
385     \r
386     \r
387     return {\r
388         start: function() {\r
389             sandbox.publish('ready');\r
390         },\r
391         getView: function() {\r
392             return view.node;\r
393         },\r
394         setDocument: function(xml) {\r
395             var transformed = transformations.fromXML.getDocumentDescription(xml);\r
396             view.setBody(transformed.HTMLTree);\r
397             view.setMetaData(transformed.metadata);\r
398             isDirty = false;\r
399         },\r
400         getDocument: function() {\r
401             return transformations.toXML.getXML({HTMLTree: view.getBody(), metadata: view.getMetaData()});\r
402         },\r
403         isDirty: function() {\r
404             return isDirty;\r
405         },\r
406         setDirty: function(dirty) {\r
407             isDirty = dirty;\r
408         },\r
409         onShowed: function() {\r
410             if(!wasShownAlready) {\r
411                 wasShownAlready = true;\r
412                 view.selectFirstNode();\r
413             }\r
414         }\r
415     \r
416     }\r
417 };