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 reloadRoot: function() {
75 var canvasDOM = this.generateCanvasDOM(this.wlxmlDocument.root);
76 //var canvasDOM = this.wlxmlDocument.root.getData('canvasElement') ? this.wlxmlDocument.root.getData('canvasElement').dom() : this.generateCanvasDOM(this.wlxmlDocument.root);
79 this.wrapper.append(canvasDOM);
80 this.d = this.wrapper.children(0);
83 generateCanvasDOM: function(wlxmlNode) {
84 var element = documentElement.DocumentNodeElement.create(wlxmlNode, this);
88 setupEventHandling: function() {
90 this.wrapper.on('keyup keydown keypress', function(e) {
91 keyboard.handleKey(e, this);
95 this.wrapper.on('mousedown', '[document-node-element], [document-text-element]', function(e) {
99 this.wrapper.on('click', '[document-node-element], [document-text-element]', function(e) {
101 if(e.originalEvent.detail === 3) {
103 canvas._moveCaretToTextElement(canvas.getDocumentElement(e.currentTarget), 'whole');
105 if(mouseDown === e.target) {
106 canvas.setCurrentElement(canvas.getDocumentElement(e.currentTarget), {caretTo: false});
111 this.wrapper.on('paste', function(e) {
114 var clipboardData = e.originalEvent.clipboardData;
115 if(!clipboardData || !clipboardData.getData) {
116 return; // TODO: alert
119 var text = clipboardData.getData('text/plain').replace(/\r?\n|\r/g, ' '),
120 cursor = canvas.getCursor(),
121 element = cursor.getPosition().element,
124 if(element && cursor.isWithinElement()) {
125 lhs = element.getText().substr(0, cursor.getSelectionStart().offset);
126 rhs = element.getText().substr(cursor.getSelectionEnd().offset);
127 element.setText(lhs+text+rhs);
128 canvas.setCurrentElement(element, {caretTo: lhs.length + text.length});
130 /* jshint noempty:false */
135 /* globals MutationObserver */
136 var observer = new MutationObserver(function(mutations) {
137 mutations.forEach(function(mutation) {
138 if(documentElement.DocumentTextElement.isContentContainer(mutation.target)) {
139 observer.disconnect();
140 if(mutation.target.data === '') {
141 mutation.target.data = utils.unicode.ZWS;
143 else if(mutation.oldValue === utils.unicode.ZWS) {
144 mutation.target.data = mutation.target.data.replace(utils.unicode.ZWS, '');
145 canvas._moveCaretToTextElement(canvas.getDocumentElement(mutation.target), 'end');
147 observer.observe(canvas.wrapper[0], config);
149 var textElement = canvas.getDocumentElement(mutation.target),
150 toSet = mutation.target.data !== utils.unicode.ZWS ? mutation.target.data : '';
152 //textElement.data('wlxmlNode').setText(toSet);
153 //textElement.data('wlxmlNode').document.transform('setText', {node: textElement.data('wlxmlNode'), text: toSet});
154 if(textElement.data('wlxmlNode').getText() !== toSet) {
155 canvas.textHandler.handle(textElement.data('wlxmlNode'), toSet);
160 var config = { attributes: false, childList: false, characterData: true, subtree: true, characterDataOldValue: true};
161 observer.observe(this.wrapper[0], config);
164 this.wrapper.on('mouseover', '[document-node-element], [document-text-element]', function(e) {
165 var el = canvas.getDocumentElement(e.currentTarget);
170 if(el instanceof documentElement.DocumentTextElement) {
173 el.toggleLabel(true);
175 this.wrapper.on('mouseout', '[document-node-element], [document-text-element]', function(e) {
176 var el = canvas.getDocumentElement(e.currentTarget);
181 if(el instanceof documentElement.DocumentTextElement) {
184 el.toggleLabel(false);
187 this.eventBus.on('elementToggled', function(toggle, element) {
189 canvas.setCurrentElement(element.getPreviousTextElement());
199 if(this.d === null) {
202 return documentElement.DocumentNodeElement.fromHTMLElement(this.d.get(0), this); //{wlxmlTag: this.d.prop('tagName')};
205 toggleElementHighlight: function(node, toggle) {
206 var element = utils.findCanvasElement(node);
207 element.toggleHighlight(toggle);
210 createNodeElement: function(params) {
211 return documentElement.DocumentNodeElement.create(params, this);
214 getDocumentElement: function(from) {
215 /* globals HTMLElement, Text */
216 if(from instanceof HTMLElement || from instanceof Text) {
217 return documentElement.DocumentElement.fromHTMLElement(from, this);
220 getCursor: function() {
221 return new Cursor(this);
225 getCurrentNodeElement: function() {
226 return this.getDocumentElement(this.wrapper.find('.current-node-element').parent()[0]);
229 getCurrentTextElement: function() {
230 return this.getDocumentElement(this.wrapper.find('.current-text-element')[0]);
233 contains: function(element) {
234 return element.dom().parents().index(this.wrapper) !== -1;
237 setCurrentElement: function(element, params) {
238 if(!(element instanceof documentElement.DocumentElement)) {
239 element = utils.findCanvasElement(element);
242 if(!element || !this.contains(element)) {
243 logger.warning('Cannot set current element: element doesn\'t exist on canvas');
247 params = _.extend({caretTo: 'end'}, params);
248 var findFirstDirectTextChild = function(e, nodeToLand) {
249 var byBrowser = this.getCursor().getPosition().element;
250 if(byBrowser && byBrowser.parent().sameNode(nodeToLand)) {
253 var children = e.children();
254 for(var i = 0; i < children.length; i++) {
255 if(children[i] instanceof documentElement.DocumentTextElement) {
261 var _markAsCurrent = function(element) {
262 if(element instanceof documentElement.DocumentTextElement) {
263 this.wrapper.find('.current-text-element').removeClass('current-text-element');
264 element.dom().addClass('current-text-element');
266 this.wrapper.find('.current-node-element').removeClass('current-node-element');
267 element._container().addClass('current-node-element');
272 var isTextElement = element instanceof documentElement.DocumentTextElement,
273 nodeElementToLand = isTextElement ? element.parent() : element,
274 textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
275 currentTextElement = this.getCurrentTextElement(),
276 currentNodeElement = this.getCurrentNodeElement();
278 if(currentTextElement && !(currentTextElement.sameNode(textElementToLand))) {
279 this.wrapper.find('.current-text-element').removeClass('current-text-element');
282 if(textElementToLand) {
283 _markAsCurrent(textElementToLand);
284 if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element)) {
285 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
287 if(!(textElementToLand.sameNode(currentTextElement))) {
288 this.publisher('currentTextElementSet', textElementToLand.data('wlxmlNode'));
291 document.getSelection().removeAllRanges();
294 if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
295 _markAsCurrent(nodeElementToLand);
297 this.publisher('currentNodeElementSet', nodeElementToLand.data('wlxmlNode'));
301 _moveCaretToTextElement: function(element, where) {
302 var range = document.createRange(),
303 node = element.dom().contents()[0];
305 if(typeof where !== 'number') {
306 range.selectNodeContents(node);
308 range.setStart(node, where);
311 if(where !== 'whole') {
312 var collapseArg = true;
313 if(where === 'end') {
316 range.collapse(collapseArg);
318 var selection = document.getSelection();
320 selection.removeAllRanges();
321 selection.addRange(range);
322 this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
325 setCursorPosition: function(position) {
326 if(position.element) {
327 this._moveCaretToTextElement(position.element, position.offset);
333 var Cursor = function(canvas) {
334 this.canvas = canvas;
337 $.extend(Cursor.prototype, {
338 isSelecting: function() {
339 var selection = window.getSelection();
340 return !selection.isCollapsed;
342 isSelectingWithinElement: function() {
343 return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
345 isWithinElement: function() {
346 return !this.isSelecting() || this.isSelectingWithinElement();
348 isSelectingSiblings: function() {
349 return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
351 getPosition: function() {
352 return this.getSelectionAnchor();
354 getSelectionStart: function() {
355 return this.getSelectionBoundry('start');
357 getSelectionEnd: function() {
358 return this.getSelectionBoundry('end');
360 getSelectionAnchor: function() {
361 return this.getSelectionBoundry('anchor');
363 getSelectionFocus: function() {
364 return this.getSelectionBoundry('focus');
366 getSelectionBoundry: function(which) {
368 var selection = window.getSelection(),
369 anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
370 focusElement = this.canvas.getDocumentElement(selection.focusNode);
372 if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement) {
376 if(which === 'anchor') {
378 element: anchorElement,
379 offset: selection.anchorOffset,
380 offsetAtBeginning: selection.anchorOffset === 0 || anchorElement.getText() === '',
381 offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset || anchorElement.getText() === ''
384 if(which === 'focus') {
386 element: focusElement,
387 offset: selection.focusOffset,
388 offsetAtBeginning: selection.focusOffset === 0 || focusElement.getText() === '',
389 offsetAtEnd: selection.focusNode.data.length === selection.focusOffset || focusElement.getText() === '',
393 var getPlaceData = function(anchorFirst) {
396 if(which === 'start') {
397 element = anchorElement;
398 offset = selection.anchorOffset;
400 else if(which === 'end') {
401 element = focusElement;
402 offset = selection.focusOffset;
405 if(which === 'start') {
406 element = focusElement;
407 offset = selection.focusOffset;
409 else if(which === 'end') {
410 element = anchorElement;
411 offset = selection.anchorOffset;
414 return {element: element, offset: offset};
417 var anchorFirst, placeData, parent;
419 if(anchorElement.parent().sameNode(focusElement.parent())) {
420 parent = anchorElement.parent();
421 if(selection.anchorNode === selection.focusNode) {
422 anchorFirst = selection.anchorOffset <= selection.focusOffset;
424 anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
426 placeData = getPlaceData(anchorFirst);
428 /*jshint bitwise: false*/
429 anchorFirst = selection.anchorNode.compareDocumentPosition(selection.focusNode) & Node.DOCUMENT_POSITION_FOLLOWING;
430 placeData = getPlaceData(anchorFirst);
433 var nodeLen = (placeData.element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
435 element: placeData.element,
436 offset: placeData.offset,
437 offsetAtBeginning: placeData.offset === 0 || focusElement.getText() === '',
438 offsetAtEnd: nodeLen === placeData.offset || focusElement.getText() === ''
444 fromXMLDocument: function(wlxmlDocument, publisher) {
445 return new Canvas(wlxmlDocument, publisher);