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) {
248 if(!(element instanceof documentElement.DocumentElement)) {
249 element = utils.findCanvasElement(element);
252 if(!element || !this.contains(element)) {
253 logger.warning('Cannot set current element: element doesn\'t exist on canvas');
257 params = _.extend({caretTo: 'end'}, params);
258 var findFirstDirectTextChild = function(e, nodeToLand) {
259 var byBrowser = this.getCursor().getPosition().element;
260 if(byBrowser && byBrowser.parent().sameNode(nodeToLand)) {
263 var children = e.children();
264 for(var i = 0; i < children.length; i++) {
265 if(children[i] instanceof documentElement.DocumentTextElement) {
271 var _markAsCurrent = function(element) {
272 if(element instanceof documentElement.DocumentTextElement) {
273 this.wrapper.find('.current-text-element').removeClass('current-text-element');
274 element.dom().addClass('current-text-element');
276 this.wrapper.find('.current-node-element').removeClass('current-node-element');
277 element._container().addClass('current-node-element');
282 var isTextElement = element instanceof documentElement.DocumentTextElement,
283 nodeElementToLand = isTextElement ? element.parent() : element,
284 textElementToLand = isTextElement ? element : findFirstDirectTextChild(element, nodeElementToLand),
285 currentTextElement = this.getCurrentTextElement(),
286 currentNodeElement = this.getCurrentNodeElement();
288 if(currentTextElement && !(currentTextElement.sameNode(textElementToLand))) {
289 this.wrapper.find('.current-text-element').removeClass('current-text-element');
292 if(textElementToLand) {
293 _markAsCurrent(textElementToLand);
294 if(params.caretTo || !textElementToLand.sameNode(this.getCursor().getPosition().element)) {
295 this._moveCaretToTextElement(textElementToLand, params.caretTo); // as method on element?
297 if(!(textElementToLand.sameNode(currentTextElement))) {
298 this.publisher('currentTextElementSet', textElementToLand.wlxmlNode);
301 document.getSelection().removeAllRanges();
304 if(!(currentNodeElement && currentNodeElement.sameNode(nodeElementToLand))) {
305 _markAsCurrent(nodeElementToLand);
307 this.publisher('currentNodeElementSet', nodeElementToLand.wlxmlNode);
311 _moveCaretToTextElement: function(element, where) {
312 var range = document.createRange(),
313 node = element.dom().contents()[0];
315 if(typeof where !== 'number') {
316 range.selectNodeContents(node);
318 range.setStart(node, where);
321 if(where !== 'whole') {
322 var collapseArg = true;
323 if(where === 'end') {
326 range.collapse(collapseArg);
328 var selection = document.getSelection();
330 selection.removeAllRanges();
331 selection.addRange(range);
332 this.wrapper.focus(); // FF requires this for caret to be put where range colllapses, Chrome doesn't.
335 setCursorPosition: function(position) {
336 if(position.element) {
337 this._moveCaretToTextElement(position.element, position.offset);
343 var Cursor = function(canvas) {
344 this.canvas = canvas;
347 $.extend(Cursor.prototype, {
348 isSelecting: function() {
349 var selection = window.getSelection();
350 return !selection.isCollapsed;
352 isSelectingWithinElement: function() {
353 return this.isSelecting() && this.getSelectionStart().element.sameNode(this.getSelectionEnd().element);
355 isWithinElement: function() {
356 return !this.isSelecting() || this.isSelectingWithinElement();
358 isSelectingSiblings: function() {
359 return this.isSelecting() && this.getSelectionStart().element.parent().sameNode(this.getSelectionEnd().element.parent());
361 getPosition: function() {
362 return this.getSelectionAnchor();
364 getSelectionStart: function() {
365 return this.getSelectionBoundry('start');
367 getSelectionEnd: function() {
368 return this.getSelectionBoundry('end');
370 getSelectionAnchor: function() {
371 return this.getSelectionBoundry('anchor');
373 getSelectionFocus: function() {
374 return this.getSelectionBoundry('focus');
376 getSelectionBoundry: function(which) {
378 var selection = window.getSelection(),
379 anchorElement = this.canvas.getDocumentElement(selection.anchorNode),
380 focusElement = this.canvas.getDocumentElement(selection.focusNode);
382 if((!anchorElement) || (anchorElement instanceof documentElement.DocumentNodeElement) || (!focusElement) || focusElement instanceof documentElement.DocumentNodeElement) {
386 if(which === 'anchor') {
388 element: anchorElement,
389 offset: selection.anchorOffset,
390 offsetAtBeginning: selection.anchorOffset === 0 || anchorElement.getText() === '',
391 offsetAtEnd: selection.anchorNode.data.length === selection.anchorOffset || anchorElement.getText() === ''
394 if(which === 'focus') {
396 element: focusElement,
397 offset: selection.focusOffset,
398 offsetAtBeginning: selection.focusOffset === 0 || focusElement.getText() === '',
399 offsetAtEnd: selection.focusNode.data.length === selection.focusOffset || focusElement.getText() === '',
403 var getPlaceData = function(anchorFirst) {
406 if(which === 'start') {
407 element = anchorElement;
408 offset = selection.anchorOffset;
410 else if(which === 'end') {
411 element = focusElement;
412 offset = selection.focusOffset;
415 if(which === 'start') {
416 element = focusElement;
417 offset = selection.focusOffset;
419 else if(which === 'end') {
420 element = anchorElement;
421 offset = selection.anchorOffset;
424 return {element: element, offset: offset};
427 var anchorFirst, placeData, parent;
429 if(anchorElement.parent().sameNode(focusElement.parent())) {
430 parent = anchorElement.parent();
431 if(selection.anchorNode === selection.focusNode) {
432 anchorFirst = selection.anchorOffset <= selection.focusOffset;
434 anchorFirst = parent.childIndex(anchorElement) < parent.childIndex(focusElement);
436 placeData = getPlaceData(anchorFirst);
438 /*jshint bitwise: false*/
439 anchorFirst = selection.anchorNode.compareDocumentPosition(selection.focusNode) & Node.DOCUMENT_POSITION_FOLLOWING;
440 placeData = getPlaceData(anchorFirst);
443 var nodeLen = (placeData.element.sameNode(focusElement) ? selection.focusNode : selection.anchorNode).length;
445 element: placeData.element,
446 offset: placeData.offset,
447 offsetAtBeginning: placeData.offset === 0 || focusElement.getText() === '',
448 offsetAtEnd: nodeLen === placeData.offset || focusElement.getText() === ''
454 fromXMLDocument: function(wlxmlDocument, publisher) {
455 return new Canvas(wlxmlDocument, publisher);