1 /*global window: true, GCN: true, jQuery: true*/ 2 (function (GCN) { 3 4 'use strict'; 5 6 /** 7 * Searches for the an Aloha editable object of the given id. 8 * 9 * @TODO: Once Aloha.getEditableById() is patched to not cause an 10 * JavaScript exception if the element for the given ID is not found 11 * then we can deprecate this function and use Aloha's instead. 12 * 13 * @static 14 * @param {string} id Id of Aloha.Editable object to find. 15 * @return {Aloha.Editable=} The editable object, if wound; otherwise null. 16 */ 17 function getAlohaEditableById(id) { 18 var Aloha = (typeof window !== 'undefined') && window.Aloha; 19 if (!Aloha) { 20 return null; 21 } 22 23 // If the element is a textarea then route to the editable div. 24 var element = jQuery('#' + id); 25 if (element.length && 26 element[0].nodeName.toLowerCase() === 'textarea') { 27 id += '-aloha'; 28 } 29 30 var editables = Aloha.editables; 31 var j = editables.length; 32 while (j) { 33 if (editables[--j].getId() === id) { 34 return editables[j]; 35 } 36 } 37 38 return null; 39 } 40 41 /** 42 * Helper function to normalize the arguments that can be passed to the 43 * `edit()' and `render()' methods. 44 * 45 * @private 46 * @static 47 * @param {arguments} args A list of arguments. 48 * @return {object} Object containing an the properties `element', 49 * `success', `error', `data' and `post'. 50 */ 51 function getRenderOptions(args) { 52 var argv = Array.prototype.slice.call(args); 53 var argc = args.length; 54 var arg; 55 var i; 56 57 var element; 58 var success; 59 var error; 60 var prerenderedData = false; 61 var post = false; 62 63 for (i = 0; i < argc; ++i) { 64 arg = argv[i]; 65 66 switch (jQuery.type(arg)) { 67 case 'string': 68 element = jQuery(arg); 69 break; 70 case 'object': 71 if (element) { 72 prerenderedData = arg; 73 } else { 74 element = arg; 75 } 76 break; 77 case 'function': 78 if (success) { 79 error = arg; 80 } else { 81 success = arg; 82 } 83 break; 84 case 'boolean': 85 post = arg; 86 break; 87 // Descarding all other types of arguments... 88 } 89 } 90 91 return { 92 element : element, 93 success : success, 94 error : error, 95 data : prerenderedData, 96 post : post 97 }; 98 } 99 100 /** 101 * Exposes an API to operate on a Content.Node tag. 102 * 103 * @class 104 * @name TagAPI 105 */ 106 var TagAPI = GCN.defineChainback({ 107 108 __chainbacktype__: 'TagAPI', 109 110 /** 111 * Type of the object 112 * 113 * @type {string} 114 */ 115 _type: 'tag', 116 117 /** 118 * A reference to the object in which this tag is contained. This value 119 * is set during initialization. 120 * 121 * @type {GCN.ContentObject} 122 */ 123 _parent: null, 124 125 /** 126 * Name of this tag. 127 * 128 * @type {string} 129 */ 130 _name: null, 131 132 /** 133 * Gets this tag's information from the object that contains it. 134 * 135 * @param {function(TagAPI)} success Callback to be invoked when this 136 * operation completes normally. 137 * @param {function(GCNError):boolean} error Custom error handler. 138 */ 139 '!_read': function (success, error) { 140 var parent = this.parent(); 141 // Because tags always retrieve their data from a parent object, 142 // this tag is only completely fetched if it's parent is also fetch. 143 // The parent could have been cleared of all it's data using 144 // _clearCache() while this tag was left in a _fetched state, so we 145 // need to check. 146 if (this._fetched && parent._fetched) { 147 if (success) { 148 this._invoke(success, [this]); 149 } 150 return; 151 } 152 153 // Because when loading folders via folder(1).folders() will 154 // fetch them without any tag data. We therefore have to refetch 155 // them wit their tag data. 156 if (parent._fetched && !parent._data.tags) { 157 parent._data.tags = {}; 158 parent.fetch(function (response) { 159 if (GCN.getResponseCode(response) !== 'OK') { 160 GCN.handleResponseError(response); 161 return; 162 } 163 var newTags = {}; 164 jQuery.each( 165 response[parent._type].tags, 166 function (name, data) { 167 if (!GCN.TagContainerAPI.hasTagData(parent, name)) { 168 newTags[name] = data; 169 } 170 } 171 ); 172 GCN.TagContainerAPI.extendTags(parent, newTags); 173 parent._read(success, error); 174 }); 175 return; 176 } 177 178 var that = this; 179 180 // Take the data for this tag from it's container. 181 parent._read(function () { 182 that._data = parent._getTagData(that._name); 183 184 if (!that._data) { 185 var err = GCN.createError('TAG_NOT_FOUND', 186 'Could not find tag "' + that._name + '" in ' + 187 parent._type + " " + parent._data.id, that); 188 GCN.handleError(err, error); 189 return; 190 } 191 192 that._fetched = true; 193 194 if (success) { 195 that._invoke(success, [that]); 196 } 197 }, error); 198 }, 199 200 /** 201 * Retrieve the object in which this tag is contained. It does so by 202 * getting this chainback's "chainlink ancestor" object. 203 * 204 * @function 205 * @name parent 206 * @memberOf TagAPI 207 * @return {GCN.AbstractTagContainer} 208 */ 209 '!parent': function () { 210 return this._ancestor(); 211 }, 212 213 /** 214 * Initialize a tag object. Unlike other chainback objects, tags will 215 * always have a parent. If its parent have been loaded, we will 216 * immediately copy the this tag's data from the parent's `_data' object 217 * to the tag's `_data' object. 218 * 219 * @param {string|object} 220 * settings 221 * @param {function(TagAPI)} 222 * success Callback to be invoked when this operation 223 * completes normally. 224 * @param {function(GCNError):boolean} 225 * error Custom error handler. 226 */ 227 _init: function (settings, success, error) { 228 if (jQuery.type(settings) === 'object') { 229 this._name = settings.name; 230 this._data = settings; 231 this._data.id = settings.id; 232 this._fetched = true; 233 } else { 234 // We don't want to reinitalize the data object when it 235 // has not been fetched yet. 236 if (!this._fetched) { 237 this._data = {}; 238 this._data.id = this._name = settings; 239 } 240 } 241 242 if (success) { 243 var that = this; 244 245 this._read(function (container) { 246 that._read(success, error); 247 }, error); 248 249 // Even if not success callback is given, read this tag's data from 250 // is container, if that container has the data available. 251 // If we are initializing a placeholder tag object (in the process 252 // of creating brand new tag, for example), then its parent 253 // container will not have any data for this tag yet. We know that 254 // we are working with a placeholder tag if no `_data.id' or `_name' 255 // property is set. 256 } else if (!this._fetched && this._name && 257 this.parent()._fetched) { 258 this._data = this.parent()._getTagData(this._name); 259 this._fetched = !!this._data; 260 261 // We are propably initializing a placholder object, we will assign 262 // it its own `_data' and `_fetched' properties so that it is not 263 // accessing the prototype values. 264 } else if (!this._fetched) { 265 this._data = {}; 266 this._data.id = this._name = settings; 267 this._fetched = false; 268 } 269 }, 270 271 /** 272 * Gets or sets a property of this tags. Note that tags do not have a 273 * `_shadow' object, and we update the `_data' object directly. 274 * 275 * @function 276 * @name prop 277 * @memberOf TagAPI 278 * @param {string} 279 * name Name of tag part. 280 * @param {*=} 281 * set Optional value. If provided, the tag part will be 282 * replaced with this value. 283 * @return {*} The value of the accessed tag part. 284 * @throws UNFETCHED_OBJECT_ACCESS 285 */ 286 '!prop': function (name, value) { 287 var parent = this.parent(); 288 289 if (!this._fetched) { 290 GCN.error('UNFETCHED_OBJECT_ACCESS', 291 'Calling method `prop()\' on an unfetched object: ' + 292 parent._type + " " + parent._data.id, this); 293 294 return; 295 } 296 297 if (jQuery.type(value) !== 'undefined') { 298 this._data[name] = value; 299 parent._update('tags.' + GCN.escapePropertyName(this.prop('name')), 300 this._data); 301 } 302 303 return this._data[name]; 304 }, 305 306 /** 307 * <p> 308 * Gets or sets a part of a tag. 309 * 310 * <p> 311 * There exists different types of tag parts, and the possible value of 312 * each kind of tag part may differ. 313 * 314 * <p> 315 * Below is a list of possible kinds of tag parts, and references to 316 * what the possible range their values can take: 317 * 318 * <pre> 319 * STRING : {@link TagParts.STRING} 320 * RICHTEXT : {@link TagParts.RICHTEXT} 321 * BOOLEAN : {@link TagParts.BOOLEAN} 322 * IMAGE : {@link TagParts.IMAGE} 323 * FILE : {@link TagParts.FILE} 324 * FOLDER : {@link TagParts.FOLDER} 325 * PAGE : {@link TagParts.PAGE} 326 * OVERVIEW : {@link TagParts.OVERVIEW} 327 * PAGETAG : {@link TagParts.PAGETAG} 328 * TEMPLATETAG : {@link TagParts.TEMPLATETAG} 329 * SELECT : {@link TagParts.SELECT} 330 * MULTISELECT : {@link TagParts.MULTISELECT} 331 * </pre> 332 * 333 * @function 334 * @name part 335 * @memberOf TagAPI 336 * 337 * @param {string} name Name of tag opart. 338 * @param {*=} value (optional) 339 * If provided, the tag part will be update with this 340 * value. How this happens differs between different type 341 * of tag parts. 342 * @return {*} The value of the accessed tag part. Null if the part 343 * does not exist. 344 * @throws UNFETCHED_OBJECT_ACCESS 345 */ 346 '!part': function (name, value) { 347 if (!this._fetched) { 348 var parent = this.parent(); 349 350 GCN.error( 351 'UNFETCHED_OBJECT_ACCESS', 352 'Calling method `prop()\' on an unfetched object: ' 353 + parent._type + " " + parent._data.id, 354 this 355 ); 356 357 return null; 358 } 359 360 var part = this._data.properties[name]; 361 362 if (!part) { 363 return null; 364 } 365 366 if (jQuery.type(value) === 'undefined') { 367 return GCN.TagParts.get(part); 368 } 369 370 var partValue = GCN.TagParts.set(part, value); 371 372 // Each time we perform a write operation on a tag, we will update 373 // the tag in the tag container's `_shadow' object as well. 374 this.parent()._update( 375 'tags.' + GCN.escapePropertyName(this._name), 376 this._data 377 ); 378 379 return partValue; 380 }, 381 382 /** 383 * Returns a list of all of this tag's parts. 384 * 385 * @function 386 * @memberOf TagAPI 387 * @name parts 388 * @param {string} name 389 * @return {Array.<string>} 390 */ 391 '!parts': function (name) { 392 var parts = []; 393 jQuery.each(this._data.properties, function (key) { 394 parts.push(key); 395 }); 396 return parts; 397 }, 398 399 /** 400 * Remove this tag from its containing object (it's parent). 401 * 402 * @function 403 * @memberOf TagAPI 404 * @name remove 405 * @param {function} callback A function that receive this tag's parent 406 * object as its only arguments. 407 */ 408 remove: function (success, error) { 409 var parent = this.parent(); 410 411 if (!parent.hasOwnProperty('_deletedTags')) { 412 parent._deletedTags = []; 413 } 414 415 GCN.pub('tag.before-deleted', {tag: this}); 416 417 parent._deletedTags.push(this._name); 418 419 if (parent._data.tags && 420 parent._data.tags[this._name]) { 421 delete parent._data.tags[this._name]; 422 } 423 424 if (parent._shadow.tags && 425 parent._shadow.tags[this._name]) { 426 delete parent._shadow.tags[this._name]; 427 } 428 429 parent._removeAssociatedTagData(this._name); 430 431 this._clearCache(); 432 433 if (success) { 434 parent._persist(null, success, error); 435 } 436 }, 437 438 /** 439 * Given a DOM element, will generate a template which represents this 440 * tag as it would be if rendered in the element. 441 * 442 * @param {jQuery.<HTMLElement>} $element DOM element with which to 443 * generate the template. 444 * @return {string} Template string. 445 */ 446 '!_makeTemplate': function ($element) { 447 if (0 === $element.length) { 448 return '<node ' + this._name + '>'; 449 } 450 var placeholder = 451 '-{(' + this.parent().id() + ':' + this._name + ')}-'; 452 var template = jQuery.trim( 453 $element.clone().html(placeholder)[0].outerHTML 454 ); 455 return template.replace(placeholder, '<node ' + this._name + '>'); 456 }, 457 458 /** 459 * Will render this tag in the given render `mode'. If an element is 460 * provided, the content will be placed in that element. If the `mode' 461 * is "edit", any rendered editables will be initialized for Aloha 462 * Editor. Any editable that are rendered into an element will also be 463 * added to the tag's parent object's `_editables' array so that they 464 * can have their changed contents copied back into their corresponding 465 * tags during saving. 466 * 467 * @param {string} mode The rendering mode. Valid values are "view", 468 * and "edit". 469 * @param {jQuery.<HTMLElement>} element DOM element into which the 470 * the rendered content should be 471 * placed. 472 * @param {function(string, TagAPI, object)} Optional success handler. 473 * @param {function(GCNError):boolean} Optional custom error handler. 474 * @param {boolean} post flag to POST the data for rendering 475 */ 476 '!_render': function (mode, $element, success, error, post) { 477 var tag = this._fork(); 478 tag._read(function () { 479 var template = ($element && $element.length) 480 ? tag._makeTemplate($element) 481 : '<node ' + tag._name + '>'; 482 483 var obj = tag.parent(); 484 485 obj._renderTemplate(template, mode, function (data) { 486 487 // Because the parent content object needs to track any 488 // blocks or editables that have been rendered in this tag. 489 obj._processRenderedTags(data); 490 491 GCN._handleContentRendered(data.content, tag, 492 function (html) { 493 if ($element && $element.length) { 494 GCN.renderOnto($element, html); 495 // Because 'content-inserted' is deprecated by 496 // 'tag.inserted'. 497 GCN.pub('content-inserted', [$element, html]); 498 GCN.pub('tag.inserted', [$element, html]); 499 } 500 501 var frontendEditing = function (callback) { 502 if ('edit' === mode) { 503 // Because 'rendered-for-editing' is deprecated by 504 // 'tag.rendered-for-editing'. 505 GCN.pub('rendered-for-editing', { 506 tag: tag, 507 data: data, 508 callback: callback 509 }); 510 GCN.pub('tag.rendered-for-editing', { 511 tag: tag, 512 data: data, 513 callback: callback 514 }); 515 } else if (callback) { 516 callback(); 517 } 518 }; 519 520 // Because the caller of edit() my wish to do things 521 // in addition to, or instead of, our frontend 522 // initialization. 523 if (success) { 524 tag._invoke( 525 success, 526 [html, tag, data, frontendEditing] 527 ); 528 } else { 529 frontendEditing(); 530 } 531 532 tag._merge(); 533 }); 534 }, function () { 535 tag._merge(); 536 }, post); 537 }, error); 538 }, 539 540 /** 541 * <p> 542 * Render the tag based on its settings on the server. Can be called 543 * with the following arguments:<(p> 544 * 545 * <pre> 546 * // Render tag contents into div whose id is "content-div" 547 * render('#content-div') or render(jQuery('#content-div')) 548 * </pre> 549 * 550 * <pre> 551 * // Pass the html rendering of the tag in the given callback 552 * render(function(html, tag) { 553 * // implementation! 554 * }) 555 * </pre> 556 * 557 * Whenever a 2nd argument is provided, it will be taken as as custom 558 * error handler. Invoking render() without any arguments will yield no 559 * results. 560 * 561 * @function 562 * @name render 563 * @memberOf TagAPI 564 * @param {string|jQuery.HTMLElement} 565 * selector jQuery selector or jQuery target element to be 566 * used as render destination 567 * @param {function(string, 568 * GCN.TagAPI)} success success function that will receive 569 * the rendered html as well as the TagAPI object 570 * @param {boolean} post 571 * True, when the tag shall be rendered by POSTing the data to 572 * the REST API. Otherwise the tag is rendered with a GET call 573 */ 574 render: function () { 575 var tag = this; 576 var args = arguments; 577 jQuery(function () { 578 args = getRenderOptions(args); 579 if (args.element || args.success) { 580 tag._render( 581 'view', 582 args.element, 583 args.success, 584 args.error, 585 args.post 586 ); 587 } 588 }); 589 }, 590 591 /** 592 * <p> 593 * Renders this tag for editing. 594 * </p> 595 * 596 * <p> 597 * Differs from the render() method in that it calls this tag to be 598 * rendered in "edit" mode via the REST API so that it is rendered with 599 * any additional content that is appropriate for when this tag is used 600 * in edit mode. 601 * </p> 602 * 603 * <p> 604 * The GCN JS API library will also start keeping track of various 605 * aspects of this tag and its rendered content. 606 * </p> 607 * 608 * <p> 609 * When a jQuery selector is passed to this method, the contents of the 610 * rendered tag will overwrite the element identified by that selector. 611 * All rendered blocks and editables will be automatically placed into 612 * the DOM and initialize for editing. 613 * </p> 614 * 615 * <p> 616 * The behavior is different when this method is called with a function 617 * as its first argument. In this case the rendered contents of the tag 618 * will not be autmatically placed into the DOM, but will be passed onto 619 * the callback function as argmuments. It is then up to the caller to 620 * place the content into the DOM and initialize all rendered blocks and 621 * editables appropriately. 622 * </p> 623 * 624 * @function 625 * @name edit 626 * @memberOf TagAPI 627 * @param {(string|jQuery.HTMLElement)=} element 628 * The element into which this tag is to be rendered. 629 * @param {function(string,TagAPI)=} success 630 * A function that will be called once the tag is rendered. 631 * @param {function(GCNError):boolean=} error 632 * A custom error handler. 633 * @param {boolean} post 634 * True, when the tag shall be rendered by POSTing the data to 635 * the REST API. Otherwise the tag is rendered with a GET call 636 */ 637 edit: function () { 638 var tag = this; 639 var args = getRenderOptions(arguments); 640 if (args.data) { 641 642 // Because the parent content object needs to track any 643 // blocks or editables that have been rendered in this tag. 644 tag.parent()._processRenderedTags(args.data); 645 646 // Because 'rendered-for-editing' is deprecated in favor of 647 // 'tag.rendered-for-editing' 648 GCN.pub('rendered-for-editing', { 649 tag: tag, 650 data: args.data, 651 callback: function () { 652 if (args.success) { 653 tag._invoke( 654 args.success, 655 [args.content, tag, args.data] 656 ); 657 } 658 } 659 }); 660 GCN.pub('tag.rendered-for-editing', { 661 tag: tag, 662 data: args.data, 663 callback: function () { 664 if (args.success) { 665 tag._invoke( 666 args.success, 667 [args.content, tag, args.data] 668 ); 669 } 670 } 671 }); 672 } else { 673 jQuery(function () { 674 if (args.element || args.success) { 675 tag._render( 676 'edit', 677 args.element, 678 args.success, 679 args.error, 680 args.post 681 ); 682 } 683 }); 684 } 685 }, 686 687 /** 688 * Persists the changes to this tag on its container object. Will only 689 * save this one tag and not affect the container object itself. 690 * Important: be careful when dealing with editable contents - these 691 * will be reloaded from Aloha Editor editables when a page is saved 692 * and thus overwrite changes you made to an editable tag. 693 * 694 * @function 695 * @name save 696 * @memberOf TagAPI 697 * @param {object=} settings Optional settings to pass on to the ajax 698 * function. 699 * @param {function(TagAPI)} success Callback to be invoked when this 700 * operation completes normally. 701 * @param {function(GCNError):boolean} error Custom error handler. 702 */ 703 save: function (settings, success, error) { 704 var tag = this; 705 var parent = tag.parent(); 706 var type = parent._type; 707 // to support the optional setting object as first argument we need 708 // to shift the arguments when it is not an object 709 if (jQuery.type(settings) !== 'object') { 710 error = success; 711 success = settings; 712 settings = null; 713 } 714 var json = settings || {}; 715 // create a mockup object to be able to save only one tag 716 // id is needed - REST API won't accept objects without id 717 json[type] = { id: parent.id(), tags: {} }; 718 json[type].tags[tag._name] = tag._data; 719 720 parent._authAjax({ 721 url : GCN.settings.BACKEND_PATH + '/rest/' + type + '/save/' 722 + parent.id() + GCN._getChannelParameter(parent), 723 type : 'POST', 724 error : error, 725 json : json, 726 success : function onTagSaveSuccess(response) { 727 if (GCN.getResponseCode(response) === 'OK') { 728 tag._invoke(success, [tag]); 729 } else { 730 tag._die(GCN.getResponseCode(response)); 731 GCN.handleResponseError(response, error); 732 } 733 } 734 }); 735 }, 736 737 /** 738 * TagAPI Objects are not cached themselves. Their _data object 739 * always references a tag in the _data of their parent, so that 740 * changes made to the TagAPI object will also change the tag in the 741 * _data of the parent. 742 * If the parent is reloaded and the _data refreshed, this would not 743 * clear or refresh the cache of the TagAPI objects. This would lead 744 * to a "broken" references and changes made to the cached TagAPI object 745 * would no longer change the tag in the parent. 746 * 747 * @private 748 * @return {Chainback} This Chainback. 749 */ 750 _addToCache: function () { 751 return this; 752 } 753 }); 754 755 // Unlike content objects, tags do not have unique ids and so we uniquely I 756 // dentify tags by their name, and their parent's id. 757 TagAPI._needsChainedHash = true; 758 759 GCN.tag = GCN.exposeAPI(TagAPI); 760 GCN.TagAPI = TagAPI; 761 762 }(GCN)); 763