5 'fnpjs/logging/logging',
6 'modules/documentCanvas/canvas/documentElement',
7 'modules/documentCanvas/canvas/keyboard',
8 'modules/documentCanvas/canvas/utils',
9 'modules/documentCanvas/canvas/wlxmlListener'
10 ], function($, _, Backbone, logging, documentElement, keyboard, utils, wlxmlListener) {
13 /* global document:false, window:false, Node:false */
15 var logger = logging.getLogger('canvas');
17 var TextHandler = function(canvas) {this.canvas = canvas; this.buffer = null;};
18 $.extend(TextHandler.prototype, {
19 handle: function(node, text) {
20 this.setText(text, node);
25 // if(this.node.sameNode(node)) {
33 _ping: _.throttle(function(text) {
38 if(this.buffer !== null) {
39 this.setText(this.buffer, this.node);
43 setText: function(text, node) {
44 //this.canvas.wlxmlDocument.transform('setText', {node:node, text: text});
52 var Canvas = function(wlxmlDocument, publisher) {
53 this.eventBus = _.extend({}, Backbone.Events);
54 this.wrapper = $('<div>').addClass('canvas-wrapper').attr('contenteditable', true);
55 this.wlxmlListener = wlxmlListener.create(this);
56 this.loadWlxmlDocument(wlxmlDocument);
57 this.setupEventHandling();
58 this.publisher = publisher ? publisher : function() {};
59 this.textHandler = new TextHandler(this);
62 $.extend(Canvas.prototype, {
64 loadWlxmlDocument: function(wlxmlDocument) {
69 this.wlxmlListener.listenTo(wlxmlDocument);
70 this.wlxmlDocument = wlxmlDocument;
74 createElement: function(wlxmlNode) {
75 var Factory = wlxmlNode.nodeType === Node.TEXT_NODE ? documentElement.DocumentTextElement : documentElement.DocumentNodeElement;
76 return new Factory(wlxmlNode, this);
79 getDocumentElement: function(htmlElement) {
80 /* globals HTMLElement, Text */
81 if(!htmlElement || !(htmlElement instanceof HTMLElement || htmlElement instanceof Text)) {
84 var $element = $(htmlElement);
85 if(htmlElement.nodeType === Node.ELEMENT_NODE && $element.attr('document-node-element') !== undefined) {
86 return $element.data('canvas-element');
89 if(htmlElement.nodeType === Node.TEXT_NODE && $element.parent().attr('document-text-element') !== undefined) {
90 $element = $element.parent();
93 if($element.attr('document-text-element') !== undefined || (htmlElement.nodeType === Node.TEXT_NODE && $element.parent().attr('document-text-element') !== undefined)) {
94 //return DocumentTextElement.fromHTMLElement(htmlElement, canvas);
95 return $element.data('canvas-element');
99 reloadRoot: function() {
100 this.rootElement = this.createElement(this.wlxmlDocument.root);
101 this.wrapper.empty();
102 this.wrapper.append(this.rootElement.dom());
105 setupEventHandling: function() {
107 this.wrapper.on('keyup keydown keypress', function(e) {
108 keyboard.handleKey(e, this);
112 this.wrapper.on('mousedown', '[document-node-element], [document-text-element]', function(e) {
113 mouseDown = e.target;
116 this.wrapper.on('click', '[document-node-element], [document-text-element]', function(e) {
118 if(e.originalEvent.detail === 3) {
120 canvas._moveCaretToTextElement(canvas.getDocumentElement(e.currentTarget), 'whole');
122 if(mouseDown === e.target) {
123 canvas.setCurrentElement(canvas.getDocumentElement(e.currentTarget), {caretTo: false});
128 this.wrapper.on('paste', function(e) {
131 var clipboardData = e.originalEvent.clipboardData;
132 if(!clipboardData || !clipboardData.getData) {
133 return; // TODO: alert
136 var text = clipboardData.getData('text/plain').replace(/\r?\n|\r/g, ' '),
137 cursor = canvas.getCursor(),
138 element = cursor.getPosition().element,
141 if(element && cursor.isWithinElement()) {
142 lhs = element.getText().substr(0, cursor.getSelectionStart().offset);
143 rhs = element.getText().substr(cursor.getSelectionEnd().offset);
144 element.setText(lhs+text+rhs);
145 canvas.setCurrentElement(element, {caretTo: lhs.length + text.length});
147 /* jshint noempty:false */
152 /* globals MutationObserver */
153 var observer = new MutationObserver(function(mutations) {
154 mutations.forEach(function(mutation) {
155 if(documentElement.DocumentTextElement.isContentContainer(mutation.target)) {
156 observer.disconnect();
157 if(mutation.target.data === '') {
158 mutation.target.data = utils.unicode.ZWS;
160 else if(mutation.oldValue === utils.unicode.ZWS) {
161 mutation.target.data = mutation.target.data.replace(utils.unicode.ZWS, '');
162 canvas._moveCaretToTextElement(canvas.getDocumentElement(mutation.target), 'end');
164 observer.observe(canvas.wrapper[0], config);
166 var textElement = canvas.getDocumentElement(mutation.target),
167 toSet = mutation.target.data !== utils.unicode.ZWS ? mutation.target.data : '';
169 //textElement.data('wlxmlNode').setText(toSet);
170 //textElement.data('wlxmlNode').document.transform('setText', {node: textElement.data('wlxmlNode'), text: toSet});
171 if(textElement.wlxmlNode.getText() !== toSet) {
172 canvas.textHandler.handle(textElement.wlxmlNode, toSet);
177 var config = { attributes: false, childList: false, characterData: true, subtree: true, characterDataOldValue: true};
178 observer.observe(this.wrapper[0], config);
181 this.wrapper.on('mouseover', '[document-node-element], [document-text-element]', function(e) {
182 var el = canvas.getDocumentElement(e.currentTarget);
187 if(el instanceof documentElement.DocumentTextElement) {
190 el.toggleLabel(true);
192 this.wrapper.on('mouseout', '[document-node-element], [document-text-element]', function(e) {
193 var el = canvas.getDocumentElement(e.currentTarget);
198 if(el instanceof documentElement.DocumentTextElement) {
201 el.toggleLabel(false);
204 this.eventBus.on('elementToggled', function(toggle, element) {
206 canvas.setCurrentElement(element.getPreviousTextElement());
216 return this.rootElement;
219 toggleElementHighlight: function(node, toggle) {
220 var element = utils.findCanvasElement(node);
221 element.toggleHighlight(toggle);
224 getCursor: function() {
225 return new Cursor(this);
229 getCurrentNodeElement: function() {
230 var htmlElement = this.wrapper.find('.current-node-element').parent()[0];
232 return this.getDocumentElement(htmlElement);
236 getCurrentTextElement: function() {
237 var htmlElement = this.wrapper.find('.current-text-element')[0];
239 return this.getDocumentElement(htmlElement);
243 contains: function(element) {
244 return element.dom().parents().index(this.wrapper) !== -1;
247 setCurrentElement: function(element, params) {
249 logger.debug('Invalid element passed to setCurrentElement: ' + element);
253 if(!(element instanceof documentElement.DocumentElement)) {
254 element = utils.findCanvasElement(element);
257 if(!element || !this.contains(element)) {
258 logger.warning('Cannot set current element: element doesn\'t exist on canvas');
262 params = _.extend({caretTo: 'end'}, params);
263 var findFirstDirectTextChild = function(e, nodeToLand) {
264 var byBrowser = this.getCursor().getPosition().element;
265 if(byBrowser && byBrowser.parent().sameNode(nodeToLand)) {
268 var children = e.children();
269 for(var i = 0; i < children.length; i++) {
270 if(children[i] instanceof documentElement.DocumentTextElement) {
276 var _markAsCurrent = function(element) {
277 if(element instanceof documentElement.DocumentTextElement) {
278 this.wrapper.find('.current-text-element').removeClass('current-text-element');
279 element.dom().addClass('current-text-element');
281 this.wrapper.find('.current-node-element').removeClass('current-node-element');
282 element._container().addClass('current-node-element');
287 var isTextElement = element instanceof documentElement.DocumentTextElement,
288 nodeElementToLand = isTextElement ? element.parent() : element,
289 textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
290 currentTextElement = this.getCurrentTextElement(),
291 currentNodeElement = this.getCurrentNodeElement();
293 if(currentTextElement && !(currentTextElement.sameNode(textElementToLand))) {
294 this.wrapper.find('.current-text-element').removeClass('current-text-element');
297 if(textElementToLand) {
298 _markAsCurrent(textElementToLand);
299 if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element)) {
300 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
302 if(!(textElementToLand.sameNode(currentTextElement))) {
303 this.publisher('currentTextElementSet', textElementToLand.wlxmlNode);
306 document.getSelection().removeAllRanges();
309 if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
310 _markAsCurrent(nodeElementToLand);
312 this.publisher('currentNodeElementSet', nodeElementToLand.wlxmlNode);
316 _moveCaretToTextElement: function(element, where) {
317 var range = document.createRange(),
318 node = element.dom().contents()[0];
320 if(typeof where !== 'number') {
321 range.selectNodeContents(node);
323 range.setStart(node, where);
326 if(where !== 'whole') {
327 var collapseArg = true;
328 if(where === 'end') {
331 range.collapse(collapseArg);
333 var selection = document.getSelection();
335 selection.removeAllRanges();
336 selection.addRange(range);
337 this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
340 setCursorPosition: function(position) {
341 if(position.element) {
342 this._moveCaretToTextElement(position.element, position.offset);
348 var Cursor = function(canvas) {
349 this.canvas = canvas;
352 $.extend(Cursor.prototype, {
353 isSelecting: function() {
354 var selection = window.getSelection();
355 return !selection.isCollapsed;
357 isSelectingWithinElement: function() {
358 return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
360 isWithinElement: function() {
361 return !this.isSelecting() || this.isSelectingWithinElement();
363 isSelectingSiblings: function() {
364 return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
366 getPosition: function() {
367 return this.getSelectionAnchor();
369 getSelectionStart: function() {
370 return this.getSelectionBoundry('start');
372 getSelectionEnd: function() {
373 return this.getSelectionBoundry('end');
375 getSelectionAnchor: function() {
376 return this.getSelectionBoundry('anchor');
378 getSelectionFocus: function() {
379 return this.getSelectionBoundry('focus');
381 getSelectionBoundry: function(which) {
383 var selection = window.getSelection(),
384 anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
385 focusElement = this.canvas.getDocumentElement(selection.focusNode);
387 if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement) {
391 if(which === 'anchor') {
393 element: anchorElement,
394 offset: selection.anchorOffset,
395 offsetAtBeginning: selection.anchorOffset === 0 || anchorElement.getText() === '',
396 offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset || anchorElement.getText() === ''
399 if(which === 'focus') {
401 element: focusElement,
402 offset: selection.focusOffset,
403 offsetAtBeginning: selection.focusOffset === 0 || focusElement.getText() === '',
404 offsetAtEnd: selection.focusNode.data.length === selection.focusOffset || focusElement.getText() === '',
408 var getPlaceData = function(anchorFirst) {
411 if(which === 'start') {
412 element = anchorElement;
413 offset = selection.anchorOffset;
415 else if(which === 'end') {
416 element = focusElement;
417 offset = selection.focusOffset;
420 if(which === 'start') {
421 element = focusElement;
422 offset = selection.focusOffset;
424 else if(which === 'end') {
425 element = anchorElement;
426 offset = selection.anchorOffset;
429 return {element: element, offset: offset};
432 var anchorFirst, placeData, parent;
434 if(anchorElement.parent().sameNode(focusElement.parent())) {
435 parent = anchorElement.parent();
436 if(selection.anchorNode === selection.focusNode) {
437 anchorFirst = selection.anchorOffset <= selection.focusOffset;
439 anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
441 placeData = getPlaceData(anchorFirst);
443 /*jshint bitwise: false*/
444 anchorFirst = selection.anchorNode.compareDocumentPosition(selection.focusNode) & Node.DOCUMENT_POSITION_FOLLOWING;
445 placeData = getPlaceData(anchorFirst);
448 var nodeLen = (placeData.element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
450 element: placeData.element,
451 offset: placeData.offset,
452 offsetAtBeginning: placeData.offset === 0 || focusElement.getText() === '',
453 offsetAtEnd: nodeLen === placeData.offset || focusElement.getText() === ''
459 fromXMLDocument: function(wlxmlDocument, publisher) {
460 return new Canvas(wlxmlDocument, publisher);