# HG changeset patch # User veltr # Date 1365008194 -7200 # Node ID 1fa074d646627714000febb84072b77b363ddb2f # Parent 4aec3f00ea876aa3d67672333033b17de7d4cb19 Added Renkan to Cinecard diff -r 4aec3f00ea87 -r 1fa074d64662 integ/css/iri.css --- a/integ/css/iri.css Wed Apr 03 16:19:25 2013 +0200 +++ b/integ/css/iri.css Wed Apr 03 18:56:34 2013 +0200 @@ -36,11 +36,16 @@ .renkan .wrap-top{width: 100%; height: 56px; background-color:rgba(0,0,0,.4);} .renkan .wrap-top h2{ font-size: 30px; padding-left: 18px; line-height: 56px; display: inline-block;} +.Rk-ZoomButtons, .zoom{width: 30px; margin: 18px 0 0 16px;-webkit-box-shadow: 0px 2px 1px rgba(0, 0, 0, 0.1);-moz-box-shadow: 0px 2px 1px rgba(0, 0, 0, 0.1);box-shadow: 0px 2px 1px rgba(0, 0, 0, 0.1);} .zoom li{padding: 0;width: 30px; height: 30px;} +.Rk-ZoomIn, .Rk-ZoomOut, .zoom a{margin: 0;width: 30px; height: 30px; display: inline-block; background: url(../img/zoom.png) center top no-repeat;} +.Rk-ZoomIn:hover, .Rk-ZoomOut:hover, .zoom a:hover{background-color: #191919;} +.Rk-ZoomIn, .zoom .in{background-color: #929292; background-position: center 8px;} +.Rk-ZoomOut, .zoom .out{background-color: #fff; background-position: center -22px;} .renkan .actions{width: 194px; float: right; margin: 12px 12px 0 0;} @@ -62,4 +67,8 @@ } a.send:hover{ background: #1899e1;background: -moz-linear-gradient(top, #1899e1 0%, #126ae3 100%);background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#1899e1), color-stop(100%,#126ae3));background: -webkit-linear-gradient(top, #1899e1 0%,#126ae3 100%);background: -o-linear-gradient(top, #1899e1 0%,#126ae3 100%);background: -ms-linear-gradient(top, #1899e1 0%,#126ae3 100%);background: linear-gradient(to bottom, #1899e1 0%,#126ae3 100%);filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#1899e1', endColorstr='#126ae3',GradientType=0 ); -} \ No newline at end of file +} + +.edit-cinecard { + position: relative; +} diff -r 4aec3f00ea87 -r 1fa074d64662 integ/iri-creation-cinecard.html --- a/integ/iri-creation-cinecard.html Wed Apr 03 16:19:25 2013 +0200 +++ b/integ/iri-creation-cinecard.html Wed Apr 03 18:56:34 2013 +0200 @@ -14,6 +14,8 @@ + + @@ -139,23 +141,10 @@ - +
+ - - - - - - - - - - - - + @@ -187,5 +176,34 @@ + + + + + + + + + + + + + + \ No newline at end of file diff -r 4aec3f00ea87 -r 1fa074d64662 integ/renkan/css/renkan.css --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/integ/renkan/css/renkan.css Wed Apr 03 18:56:34 2013 +0200 @@ -0,0 +1,159 @@ + +.Rk-Render { + position: absolute; left: 0; top: 0; right: 0; bottom: 0; +} + +/* Canvas */ + +.Rk-Canvas { + position: absolute; left: 0; top: 0; right: 0; bottom: 0; z-index: 1; +} + +/* Editors */ + +.Rk-Editor { + position: absolute; left: 0; top: 0; right: 0; z-index: 2; color: #000000; +} + +.Rk-Notifications { + position: absolute; right: 15px; top: 15px; width: 200px; + padding: 10px; border-radius: 8px; display: none; + color: #ffffff; font-size: 13px; text-align: center; font-weight: bold; + background: rgba(20,20,20,.7); + background: -moz-linear-gradient(top, rgba(40,40,40,.7) 20%, rgba(0,0,0,.7) 80%); + background: -webkit-linear-gradient(top, rgba(40,40,40,.7) 20%, rgba(0,0,0,.7) 80%); + background: -ms-linear-gradient(top, rgba(40,40,40,.7) 20%, rgba(0,0,0,.7) 80%); + filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#202020', endColorstr='#000000',GradientType=0 ); +} + +.Rk-CloseX { + float: right; cursor: pointer; +} + +.Rk-Editor h2 { + font-size: 16px; font-weight: bold; +} + +.Rk-Editor p, .Rk-Editor-p { + margin: 5px 0; font-size: 12px; clear: both; +} + +.Rk-Editor-Label { + float: left; width: 80px; +} + +a.Rk-Edit-Goto { + display: block; float: right; width: 18px; height: 17px; margin: 1px 0; border: none; background: url(../img/goto.png); +} + +.Rk-Edit-Title, .Rk-Edit-URI, .Rk-Edit-Image, .Rk-Edit-Image-File, .Rk-Edit-Vocabulary { + font-size: 12px; width: 250px; +} + +.Rk-Edit-URI { + font-size: 12px; width: 230px; +} + +.Rk-Edit-ImgPreview { + border: 1px solid #666; margin: 5px auto; display: block; + max-width: 253px !important; max-height: 100px !important; +} + +.Rk-Editor textarea { + width: 250px; height: 120px; resize: none; +} + +.Rk-UserColor { + display: inline-block; width: 12px; height: 12px; border: 1px solid #666666; margin: -2px 2px; +} + +.Rk-Edit-Color { + display: inline-block; width: 10px; height: 10px; border: 2px solid #333333; margin: -2px 2px; +} + +.Rk-Edit-ColorTip { + display: block; width: 3px; height: 3px; background: #fff; margin: 7px 0 0 7px; cursor: pointer; +} + +.Rk-Edit-ColorPicker-Wrapper { + display: inline-block; position: relative; +} + +.Rk-Edit-ColorPicker { + position: absolute; top: -2px; left: 15px; width: 96px; height: 96px; border: 1px solid #CCCCCC; + padding: 5px 4px 4px 5px; background: #ffffff; border-radius: 5px; display: none; +} + +.Rk-Edit-ColorPicker-Text { + color: #303080; font-weight: bold; +} + +.Rk-Edit-ColorPicker li { + float: left; width: 11px; height: 11px; margin: 0 1px 1px 0; cursor: pointer; +} + +.Rk-Edit-Size-Up, .Rk-Edit-Size-Down { + font-size: 13px; font-weight: bold; padding: 0 4px; background: #ffffff; color: #000000; border: 1px solid #cccccc; + text-decoration: none; +} + +.Rk-Edit-Size-Up:hover, .Rk-Edit-Size-Down:hover { + background: #666666; +} + +.Rk-Edit-Size-Value { + display: inline-block; + padding: 0 5px; + text-align: center; + width: 20px; +} + +.Rk-Edit-Vocabulary-Class { + color: #999999; font-style: italic; font-weight: bold; +} + +.Rk-Edit-Vocabulary-Property { + padding-left: 20px; +} + +.Rk-Edit-Direction { + border: 1px solid #666; padding: 3px 5px; line-height: 20px; border-radius: 3px; background: #f0f0f0; cursor: pointer; +} + +.Rk-Edit-Direction:hover { + background: #c0c0c0; +} + +.Rk-Display-Title a { + text-decoration: none; color: #000000; +} + +.Rk-Display-Title a:hover { + text-decoration: underline; +} + +.Rk-Display-URI { + font-style: italic; +} + +.Rk-Fold-Bins { + position: absolute; top: 5px; width: 12px; text-align: center; font-size: 16px; cursor: pointer; + line-height: 16px; padding: 4px; color: #ffffff; background: #666666; border-radius: 0 6px 6px 0; + font-weight: bold; +} + +.Rk-Fold-Bins:hover { + background: #333333; +} + +.Rk-ZoomButtons { + position: absolute; +} + +.Rk-ZoomIn, .Rk-ZoomOut { + display: block; +} + +.Rk-Clear { + clear: both; +} diff -r 4aec3f00ea87 -r 1fa074d64662 integ/renkan/img/edit.png Binary file integ/renkan/img/edit.png has changed diff -r 4aec3f00ea87 -r 1fa074d64662 integ/renkan/img/goto.png Binary file integ/renkan/img/goto.png has changed diff -r 4aec3f00ea87 -r 1fa074d64662 integ/renkan/img/image-placeholder.png Binary file integ/renkan/img/image-placeholder.png has changed diff -r 4aec3f00ea87 -r 1fa074d64662 integ/renkan/img/link.png Binary file integ/renkan/img/link.png has changed diff -r 4aec3f00ea87 -r 1fa074d64662 integ/renkan/img/remove.png Binary file integ/renkan/img/remove.png has changed diff -r 4aec3f00ea87 -r 1fa074d64662 integ/renkan/img/zoombuttons.png Binary file integ/renkan/img/zoombuttons.png has changed diff -r 4aec3f00ea87 -r 1fa074d64662 integ/renkan/js/defaults.js --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/integ/renkan/js/defaults.js Wed Apr 03 18:56:34 2013 +0200 @@ -0,0 +1,86 @@ +Rkns.defaults = { + + language: (navigator.language || navigator.userLanguage || "en"), + /* GUI Language */ + container: "renkan", + /* GUI Container DOM element ID */ + search: [], + /* List of Search Engines */ + bins: [], + /* List of Bins */ + static_url: "", + /* URL for static resources */ + show_bins: true, + /* Show bins in left column */ + properties: [], + /* Semantic properties for edges */ + read_only: false, + /* Allows editing of renkan without changing the rest of the GUI. Can be switched on/off on the fly to block/enable editing */ + editor_mode: true, + /* Switch for Publish/Edit GUI. If editor_mode is false, read_only will be true. */ + snapshot_mode: false, + /* In snapshot mode, clicking on the floppy will save a snapshot. Otherwise, it will show the connection status */ + show_top_bar: true, + /* Show the top bar, (title, buttons, users) */ + + /* MINI-MAP OPTIONS */ + + show_minimap: true, + /* Show a small map at the bottom right */ + minimap_width: 160, + minimap_height: 120, + minimap_background_color: "#ffffff", + minimap_border_color: "#cccccc", + minimap_highlight_color: "#ffff00", + minimap_highlight_weight: 5, + + /* EDGE/NODE COMMON OPTIONS */ + + buttons_background: "#202020", + buttons_label_color: "#c000c0", + buttons_label_font_size: 9, + + /* NODE DISPLAY OPTIONS */ + + show_node_circles: true, + /* Show circles for nodes */ + clip_node_images: true, + /* Constraint node images to circles */ + node_stroke_width: 2, + selected_node_stroke_width: 4, + node_fill_color: "#ffffff", + highlighted_node_fill_color: "#ffff00", + node_label_color: "#000000", + node_label_font_size: 10, + node_label_font: 'Helvetica, Arial, sans-serif', + node_label_distance: 5, + /* Vertical distance between node and label */ + node_label_max_length: 40, + /* Maximum displayed text length */ + + /* EDGE DISPLAY OPTIONS */ + + edge_stroke_width: 2, + selected_edge_stroke_width: 4, + edge_label_color: "#000000", + edge_label_font_size: 9, + edge_label_font: 'Helvetica, Arial, sans-serif', + edge_label_distance: -3, + edge_label_max_length: 20, + edge_arrow_length: 18, + edge_arrow_width: 12, + edge_gap_in_bundles: 12, + + /* CONTEXTUAL DISPLAY (TOOLTIP OR EDITOR) OPTIONS */ + + tooltip_width: 275, + tooltip_padding: 10, + tooltip_margin: 15, + tooltip_arrow_length : 20, + tooltip_arrow_width : 40, + tooltip_top_color: "#f0f0f0", + tooltip_bottom_color: "#d0d0d0", + tooltip_border_color: "#808080", + tooltip_border_width: 1 + +} diff -r 4aec3f00ea87 -r 1fa074d64662 integ/renkan/js/i18n.js --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/integ/renkan/js/i18n.js Wed Apr 03 18:56:34 2013 +0200 @@ -0,0 +1,74 @@ +Rkns.i18n = { + fr: { + "Edit Node": "Édition d’un nœud", + "Edit Edge": "Édition d’un lien", + "Title:": "Titre :", + "URI:": "URI :", + "Description:": "Description :", + "From:": "De :", + "To:": "Vers :", + "Image": "Image", + "Image URL:": "URL d'Image", + "Choose Image File:": "Choisir un fichier image", + "Full Screen": "Mode plein écran", + "Add Node": "Ajouter un nœud", + "Add Edge": "Ajouter un lien", + "Archive Project": "Archiver le projet", + "Auto-save enabled": "Enregistrement automatique activé", + "Connection lost": "Connexion perdue", + "Created by:": "Créé par :", + "Zoom In": "Agrandir l’échelle", + "Zoom Out": "Rapetisser l’échelle", + "Edit": "Éditer", + "Remove": "Supprimer", + "Link to another node": "Créer un lien", + "Click on the background canvas to add a node": "Cliquer sur le fond du graphe pour rajouter un nœud", + "Click on a first node to start the edge": "Cliquer sur un premier nœud pour commencer le lien", + "Click on a second node to complete the edge": "Cliquer sur un second nœud pour terminer le lien", + "Twitter": "Twitter", + "Wikipedia": "Wikipédia", + "Wikipedia in ": "Wikipédia en ", + "French": "Français", + "English": "Anglais", + "Japanese": "Japonais", + "Untitled project": "Projet sans titre", + "Lignes de Temps": "Lignes de Temps", + "Loading, please wait": "Chargement en cours, merci de patienter", + "Edge color:": "Couleur :", + "Node color:": "Couleur :", + "Choose color": "Choisir une couleur", + "Change edge direction": "Changer le sens du lien", + "Do you really wish to remove node ": "Voulez-vous réellement supprimer le nœud ", + "Do you really wish to remove edge ": "Voulez-vous réellement supprimer le lien ", + "This file is not an image": "Ce fichier n'est pas une image", + "Image size must be under ": "L'image doit peser moins de ", + "Size:": "Taille :", + "KB": "ko", + "Choose from vocabulary:": "Choisir dans un vocabulaire :", + "SKOS Documentation properties": "SKOS: Propriétés documentaires", + "has note": "a pour note", + "has example": "a pour exemple", + "has definition": "a pour définition", + "SKOS Semantic relations": "SKOS: Relations sémantiques", + "has broader": "a pour concept plus large", + "has narrower": "a pour concept plus étroit", + "has related": "a pour concept apparenté", + "Dublin Core Metadata": "Métadonnées Dublin Core", + "has contributor": "a pour contributeur", + "covers": "couvre", + "created by": "créé par", + "has date": "a pour date", + "published by": "édité par", + "has source": "a pour source", + "has subject": "a pour sujet", + "Dragged resource": "Ressource glisée-déposée", + "Search the Web": "Rechercher en ligne", + "Search in Bins": "Rechercher dans les chutiers", + "Close bin": "Fermer le chutier", + "Refresh bin": "Rafraîchir le chutier", + "(untitled)": "(sans titre)", + "Select contents:": "Sélectionner des contenus :", + "Drag items from this website, drop them in Renkan": "Glissez des éléments de ce site web vers Renkan", + "Drag this button to your bookmark bar. When on a third-party website, click it to enable drag-and-drop from the website to Renkan.": "Glissez ce bouton vers votre barre de favoris. Ensuite, depuis un site tiers, cliquez dessus pour activer 'Drag-to-Add' puis glissez des éléments de ce site vers Renkan" + } +} diff -r 4aec3f00ea87 -r 1fa074d64662 integ/renkan/js/main.js --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/integ/renkan/js/main.js Wed Apr 03 18:56:34 2013 +0200 @@ -0,0 +1,304 @@ +/* + * Copyright 2012 Institut de recherche et d'innovation + * contributor(s) : Yves-Marie Haussonne, Raphael Velt, Samuel Huron + * + * contact@iri.centrepompidou.fr + * http://www.iri.centrepompidou.fr + * + * This software is a computer program whose purpose is to show and add annotations on a video . + * This software is governed by the CeCILL-C license under French law and + * abiding by the rules of distribution of free software. You can use, + * modify and/ or redistribute the software under the terms of the CeCILL-C + * license as circulated by CEA, CNRS and INRIA at the following URL + * "http://www.cecill.info". + * + * The fact that you are presently reading this means that you have had + * knowledge of the CeCILL-C license and that you accept its terms. +*/ + +/* Declaring the Renkan Namespace Rkns and Default values */ + +if (typeof Rkns !== "object") { + Rkns = {} +} + +Rkns.$ = jQuery; + +Rkns._ = _; + +Rkns.VERSION = '0.2'; + +Rkns.pickerColors = ["#8f1919", "#a80000", "#d82626", "#ff0000", "#e87c7c", "#ff6565", "#f7d3d3", "#fecccc", + "#8f5419", "#a85400", "#d87f26", "#ff7f00", "#e8b27c", "#ffb265", "#f7e5d3", "#fee5cc", + "#8f8f19", "#a8a800", "#d8d826", "#feff00", "#e8e87c", "#feff65", "#f7f7d3", "#fefecc", + "#198f19", "#00a800", "#26d826", "#00ff00", "#7ce87c", "#65ff65", "#d3f7d3", "#ccfecc", + "#198f8f", "#00a8a8", "#26d8d8", "#00feff", "#7ce8e8", "#65feff", "#d3f7f7", "#ccfefe", + "#19198f", "#0000a8", "#2626d8", "#0000ff", "#7c7ce8", "#6565ff", "#d3d3f7", "#ccccfe", + "#8f198f", "#a800a8", "#d826d8", "#ff00fe", "#e87ce8", "#ff65fe", "#f7d3f7", "#feccfe", + "#000000", "#242424", "#484848", "#6d6d6d", "#919191", "#b6b6b6", "#dadada", "#ffffff"]; + +Rkns._BaseBin = function(_renkan, _opts) { + if (typeof _renkan !== "undefined") { + this.renkan = _renkan; + this.renkan.$.find(".Rk-Bin-Main").hide(); + this.$ = Rkns.$('
  • ') + .addClass("Rk-Bin") + .appendTo(_renkan.$.find(".Rk-Bin-List")); + this.title_icon_$ = Rkns.$('') + .addClass("Rk-Bin-Title-Icon") + .appendTo(this.$); + + var _this = this; + + Rkns.$('') + .attr({ + href: "#", + title: _renkan.translate("Close bin") + }) + .addClass("Rk-Bin-Close") + .html('×') + .appendTo(this.$) + .click(function() { + _this.destroy(); + if (!_renkan.$.find(".Rk-Bin-Main:visible").length) { + _renkan.$.find(".Rk-Bin-Main:last").slideDown(); + } + _renkan.resizeBins(); + return false; + }); + Rkns.$('') + .attr({ + href: "#", + title: _renkan.translate("Refresh bin") + }) + .addClass("Rk-Bin-Refresh") + .appendTo(this.$) + .click(function() { + _this.refresh(); + return false; + }); + this.count_$ = Rkns.$('
    ') + .addClass("Rk-Bin-Count") + .appendTo(this.$); + this.title_$ = Rkns.$('

    ') + .addClass("Rk-Bin-Title") + .appendTo(this.$); + this.main_$ = Rkns.$('
    ') + .addClass("Rk-Bin-Main") + .appendTo(this.$) + .html('

    ' + _renkan.translate("Loading, please wait") + '

    '); + this.title_$.html(_opts.title || '(new bin)'); + this.renkan.resizeBins(); + + if (_opts.auto_refresh) { + window.setInterval(function() { + _this.refresh(); + },_opts.auto_refresh) + } + } +} + +Rkns._BaseBin.prototype.destroy = function() { + this.$.detach(); + this.renkan.resizeBins(); +} + +/* Point of entry */ + +Rkns.Renkan = function(_opts) { + var _this = this; + + this.options = _.defaults(_opts, Rkns.defaults); + + Rkns._(this.options.property_files).each(function(f) { + Rkns.$.getJSON(f, function(data) { + _this.options.properties = _this.options.properties.concat(data); + }); + }); + + this.read_only = this.options.read_only || !this.options.editor_mode; + + this.project = new Rkns.Models.Project(); + + this.translate = function(_text) { + return (Rkns.i18n[_this.options.language] || Rkns.i18n[_this.options.language.substr(0,2)] || {})[_text] || _text; + } + if (typeof this.options.user_id !== "undefined") { + this.current_user = this.options.user_id; + } + this.$ = Rkns.$("#" + this.options.container); + this.$ + .addClass("Rk-Main") + .html(this.template(this)); + this.renderer = new Rkns.Renderer.Scene(this); + this.tabs = []; + this.search_engines = []; + + this.current_user_list = new Rkns.Models.UsersList(); + + if (!this.options.search.length) { + this.$.find(".Rk-Web-Search-Form").detach(); + } else { + var _tmpl = Rkns._.template('
  • <%= title %>
  • '), + _select = this.$.find(".Rk-Search-List"), + _input = this.$.find(".Rk-Web-Search-Input") + _form = this.$.find(".Rk-Web-Search-Form"); + Rkns._(this.options.search).each(function(_search, _key) { + if (Rkns[_search.type] && Rkns[_search.type].Search) { + _this.search_engines.push(new Rkns[_search.type].Search(_this, _search)); + } + }); + _select.html( + Rkns._(this.search_engines).map(function(_search, _key) { + return _tmpl({ + key: _key, + title: _search.getSearchTitle(), + className: _search.getBgClass() + }); + }).join("") + ); + _select.find("li").click(function() { + var _el = Rkns.$(this); + _this.setSearchEngine(_el.attr("data-key")); + _form.submit(); + }); + _form.submit(function() { + if (_input.val()) { + var _search = _this.search_engine; + _search.search(_input.val()); + } + return false; + }); + this.$.find(".Rk-Search-Current").mouseenter( + function() { _select.slideDown(); } + ); + this.$.find(".Rk-Search-Select").mouseleave( + function() { _select.hide(); } + ); + this.setSearchEngine(0); + } + Rkns._(this.options.bins).each(function(_bin) { + if (Rkns[_bin.type] && Rkns[_bin.type].Bin) { + _this.tabs.push(new Rkns[_bin.type].Bin(_this, _bin)); + } + }); + + this.$.find(".Rk-Bins") + .on("click",".Rk-Bin-Title,.Rk-Bin-Title-Icon", function() { + var _mainDiv = Rkns.$(this).siblings(".Rk-Bin-Main"); + if (_mainDiv.is(":hidden")) { + _this.$.find(".Rk-Bin-Main").slideUp(); + _mainDiv.slideDown(); + } + }).on("mouseover", ".Rk-Bin-Item", function(_e) { + var _t = Rkns.$(this); + if (_t && $(_t).attr("data-uri")) { + var _models = _this.project.get("nodes").where({ + uri: $(_t).attr("data-uri") + }); + Rkns._(_models).each(function(_model) { + _this.renderer.highlightModel(_model); + }); + } + }).mouseout(function() { + _this.renderer.unhighlightAll(); + }).on("mousemove", ".Rk-Bin-Item", function(e) { + try { + this.dragDrop(); + } + catch(err) {} + }).on("dragstart", ".Rk-Bin-Item", function(e) { + var div = document.createElement('div'); + div.appendChild(this.cloneNode(true)); + try { + e.originalEvent.dataTransfer.setData("text/html",div.innerHTML); + } + catch(err) { + e.originalEvent.dataTransfer.setData("text",div.innerHTML); + } + }); + Rkns.$(window).resize(function() { + _this.resizeBins(); + }); + + this.$.find(".Rk-Bins-Search-Input").on("change keyup paste input", function() { + var val = Rkns.$(this).val(); + Rkns._(_this.tabs).each(function(tab) { + tab.render(val); + }); + }); + this.$.find(".Rk-Bins-Search-Form").submit(function() { + return false + }); +} + +Rkns.Renkan.prototype.template = Rkns._.template( + '<% if (options.show_bins) { %>

    <%- translate("Select contents:")%>

    ' + + '
    " />' + + '
      ' + + '" />
      ' + + '
      " />' + + '" />
      ' + + '
        <% } %>
        ' +); + +Rkns.Renkan.prototype.onStatusChange = function() { + this.renderer.onStatusChange(); +} + + +Rkns.Renkan.prototype.setSearchEngine = function(_key) { + this.search_engine = this.search_engines[_key]; + this.$.find(".Rk-Search-Current").attr("class","Rk-Search-Current " + this.search_engine.getBgClass()); +} + +Rkns.Renkan.prototype.resizeBins = function() { + var _d = + this.$.find(".Rk-Bins-Head").outerHeight(); + this.$.find(".Rk-Bin-Title:visible").each(function() { + _d += Rkns.$(this).outerHeight(); + }); + this.$.find(".Rk-Bin-Main").css({ + height: this.$.find(".Rk-Bins").height() - _d + }); +} + +/* Utility functions */ + +Rkns.Utils = { + _ID_AUTO_INCREMENT : 0, + _ID_BASE : (function(_d) { + function pad(n){return n<10 ? '0'+n : n} + function fillrand(n) { + var _res = '' + for (var i=0; i" + + _renkan.translate("Drag items from this website, drop them in Renkan").replace(/ /g,"_") + + "

        '.replace(/_/g,String.fromCharCode(32));b.appendChild(d);e=[{r:/https?:\\/\\/[^\\/]*twitter\\.com\\//,s:'.tweet',n:'twitter'},{r:/https?:\\/\\/[^\\/]*google\\.[^\\/]+\\//,s:'.g',n:'google'},{r:/https?:\\/\\/[^\\/]*lemonde\\.fr\\//,s:'[data-vr-contentbox]',n:'lemonde'}];f=false;e.forEach(function(g){if(g.r.test(c)){f=g;}});if(f){h=function(){Array.prototype.forEach.call(a.querySelectorAll(f.s),function(i){i[j]=true;k=i.style;k.borderWidth='2px';k.borderColor='#909';k.borderStyle='solid';k.backgroundColor='rgba(200,0,180,.1)';})};window.setInterval(h,500);h();};a.addEventListener('dragstart',function(k){l=k.dataTransfer;l.setData(m+'source-uri',c);l.setData(m+'source-title',a.title);n=k.target;if(f){o=n;while(!o.attributes[j]){o=o.parentNode;if(o==b){break;}}}if(f&&o.attributes[j]){p=o.cloneNode(true);l.setData(m+'specific-site',f.n)}else{q=a.getSelection();if(q.type==='Range'||!q.type){p=q.getRangeAt(0).cloneContents();}else{p=n.cloneNode();}}r=a.createElement('div');r.appendChild(p);l.setData('text/x-iri-selected-text',r.textContent.trim());l.setData('text/x-iri-selected-html',r.innerHTML);},false);})();" + } +} + +Rkns.Renderer.Utils = { + shortenText : function(_text, _maxlength) { + return (_text.length > _maxlength ? (_text.substr(0,_maxlength) + '…') : _text); + }, + drawEditBox : function(_options, _coords, _path, _xmargin, _selector) { + _selector.css({ + width: ( _options.tooltip_width - 2* _options.tooltip_padding ), + }) + var _height = _selector.outerHeight() + 2* _options.tooltip_padding, + _isLeft = (_coords.x < paper.view.center.x ? 1 : -1), + _left = _coords.x + _isLeft * ( _xmargin + _options.tooltip_arrow_length ), + _right = _coords.x + _isLeft * ( _xmargin + _options.tooltip_arrow_length + _options.tooltip_width ), + _top = _coords.y - _height / 2; + if (_top < _options.tooltip_margin) { + _top = Math.min( _options.tooltip_margin, _coords.y - _options.tooltip_arrow_width / 2 ); + } + var _bottom = _top + _height; + if (_bottom > (paper.view.size.height - _options.tooltip_margin)) { + _bottom = Math.max( paper.view.size.height - _options.tooltip_margin, _coords.y + _options.tooltip_arrow_width / 2 ); + _top = _bottom - _height; + } + _path.segments[0].point + = _path.segments[7].point + = _coords.add([_isLeft * _xmargin, 0]); + _path.segments[1].point.x + = _path.segments[2].point.x + = _path.segments[5].point.x + = _path.segments[6].point.x + = _left; + _path.segments[3].point.x + = _path.segments[4].point.x + = _right; + _path.segments[2].point.y + = _path.segments[3].point.y + = _top; + _path.segments[4].point.y + = _path.segments[5].point.y + = _bottom; + _path.segments[1].point.y = _coords.y - _options.tooltip_arrow_width / 2; + _path.segments[6].point.y = _coords.y + _options.tooltip_arrow_width / 2; + _path.closed = true; + _path.fillColor = new paper.GradientColor(new paper.Gradient([_options.tooltip_top_color, _options.tooltip_bottom_color]), [0,_top], [0, _bottom]); + _selector.css({ + left: (_options.tooltip_padding + Math.min(_left, _right)), + top: (_options.tooltip_padding + _top) + }); + }, + sector : function(_repr, _inR, _outR, _startAngle, _endAngle, _padding, _imgsrc, _caption) { + var _options = _repr.renderer.renkan.options, + _startRads = _startAngle * Math.PI / 180, + _endRads = _endAngle * Math.PI / 180, + _img = new Image(), + _span = _endRads - _startRads, + _k = .0879 * _span, + _kin = _k * _inR, + _kout = _k * _outR, + _startdx = - Math.sin(_startRads), + _startdy = Math.cos(_startRads), + _startXIn = Math.cos(_startRads) * _inR + _padding * _startdx, + _startYIn = Math.sin(_startRads) * _inR + _padding * _startdy, + _startXOut = Math.cos(_startRads) * _outR + _padding * _startdx, + _startYOut = Math.sin(_startRads) * _outR + _padding * _startdy, + _enddx = - Math.sin(_endRads), + _enddy = Math.cos(_endRads), + _endXIn = Math.cos(_endRads) * _inR - _padding * _enddx, + _endYIn = Math.sin(_endRads) * _inR - _padding * _enddy, + _endXOut = Math.cos(_endRads) * _outR - _padding * _enddx, + _endYOut = Math.sin(_endRads) * _outR - _padding * _enddy, + _centerR = (_inR + _outR)/2, + _centerRads = (_startRads + _endRads) / 2, + _centerX = Math.cos(_centerRads) * _centerR, + _centerY = Math.sin(_centerRads) * _centerR, + _centerXIn = Math.cos(_centerRads) * _inR, + _centerXOut = Math.cos(_centerRads) * _outR, + _centerYIn = Math.sin(_centerRads) * _inR, + _centerYOut = Math.sin(_centerRads) * _outR, + _textX = Math.cos(_centerRads) * (_outR + 3), + _textY = Math.sin(_centerRads) * (_outR + 3), + _segments = []; + _repr.renderer.buttons_layer.activate(); + var _path = new paper.Path(); + _path.add([_startXIn, _startYIn]); + _path.arcTo([_centerXIn, _centerYIn], [_endXIn, _endYIn]); + _path.lineTo([_endXOut, _endYOut]); + _path.arcTo([_centerXOut, _centerYOut], [_startXOut, _startYOut]); + _path.fillColor = _options.buttons_background; + _path.opacity = .5; + _path.closed = true; + _path.__representation = _repr; + if (_textX >= -2 && _textX <= 2) { + if (_textY > 0) { + _textY += 6; + } + } + var _text = new paper.PointText(_textX,_textY); + _text.characterStyle = { + fontSize: _options.buttons_label_font_size, + fillColor: _options.buttons_label_color + }; + if (_textX > 2) { + _text.paragraphStyle.justification = 'left'; + } else if (_textX < -2) { + _text.paragraphStyle.justification = 'right'; + } else { + _text.paragraphStyle.justification = 'center'; + } + _text.visible = false; + var _visible = false, + _restPos = new paper.Point(-200, -200), + _grp = new paper.Group([_path, _text]), + _delta = _grp.position, + _imgdelta = new paper.Point([_centerX, _centerY]), + _currentPos = new paper.Point(0,0); + _text.content = _caption; + _grp.visible = false; + _grp.position = _restPos; + var _res = { + show: function() { + _visible = true; + _grp.position = _currentPos.add(_delta); + _grp.visible = true; + }, + moveTo: function(_point) { + _currentPos = _point; + if (_visible) { + _grp.position = _point.add(_delta); + } + }, + hide: function() { + _visible = false; + _grp.visible = false; + _grp.position = _restPos; + }, + select: function() { + _path.opacity = .8; + _text.visible = true; + }, + unselect: function() { + _path.opacity = .5; + _text.visible = false; + }, + destroy: function() { + _grp.remove(); + } + } + _img.onload = function() { + var _h = _img.height; + var _raster = new paper.Raster(_img); + _raster.position = _imgdelta.add(_grp.position).subtract(_delta); + _grp.addChild(_raster); + } + _img.src = _imgsrc; + return _res + } +} + +Rkns.Renderer._BaseRepresentation = function(_renderer, _model) { + if (typeof _renderer !== "undefined") { + this.renderer = _renderer; + this.renkan = _renderer.renkan; + this.project = _renderer.renkan.project; + this.options = _renderer.renkan.options; + this.model = _model; + if (this.model) { + var _this = this; + this._changeBinding = function() { + _this.redraw(); + } + this._removeBinding = function() { + _renderer.removeRepresentation(_this); + _(function() { + _renderer.redraw() + }).defer(); + } + this.model.on("change", this._changeBinding ); + this.model.on("remove", this._removeBinding ); + } + } +} + +Rkns.Renderer._BaseRepresentation.prototype.super = function(_func) { + Rkns.Renderer._BaseRepresentation.prototype[_func].apply(this, Array.prototype.slice.call(arguments, 1)); +} + +Rkns.Renderer._BaseRepresentation.prototype.redraw = function() {} + +Rkns.Renderer._BaseRepresentation.prototype.moveTo = function() {} + +Rkns.Renderer._BaseRepresentation.prototype.show = function() {} + +Rkns.Renderer._BaseRepresentation.prototype.hide = function() {} + +Rkns.Renderer._BaseRepresentation.prototype.select = function() {} + +Rkns.Renderer._BaseRepresentation.prototype.unselect = function() {} + +Rkns.Renderer._BaseRepresentation.prototype.highlight = function() {} + +Rkns.Renderer._BaseRepresentation.prototype.unhighlight = function() {} + +Rkns.Renderer._BaseRepresentation.prototype.mouseup = function() {} + +Rkns.Renderer._BaseRepresentation.prototype.destroy = function() { + if (this.model) { + this.model.off("change", this._changeBinding ); + this.model.off("remove", this._removeBinding ); + } +} + +Rkns.Renderer.Node = Rkns.Utils.inherit(Rkns.Renderer._BaseRepresentation); + +Rkns.Renderer.Node.prototype._init = function() { + this.renderer.node_layer.activate(); + this.type = "Node"; + this.circle = new paper.Path.Circle([0, 0], 1); + this.circle.__representation = this; + this.circle.fillColor = this.options.node_fill_color; + if (this.options.show_node_circles) { + this.circle.strokeWidth = this.options.node_stroke_width; + this.h_ratio = 1; + } else { + this.circle.opacity = .01; + this.h_ratio = 0; + } + this.title = new paper.PointText([0,0]); + this.title.characterStyle = { + font: this.options.node_label_font, + fontSize: this.options.node_label_font_size, + fillColor: this.options.node_label_color + }; + if (this.options.editor_mode) { + this.edit_button = new Rkns.Renderer.NodeEditButton(this.renderer, null); + this.edit_button.node_representation = this; + this.remove_button = new Rkns.Renderer.NodeRemoveButton(this.renderer, null); + this.remove_button.node_representation = this; + this.link_button = new Rkns.Renderer.NodeLinkButton(this.renderer, null); + this.link_button.node_representation = this; + } + this.last_circle_radius = 1; + this.title.paragraphStyle.justification = 'center'; + + if (this.renderer.minimap) { + this.renderer.minimap.node_layer.activate(); + this.minimap_circle = new paper.Path.Circle([0, 0], 1); + this.renderer.minimap.node_group.addChild(this.minimap_circle); + } +} + +Rkns.Renderer.Node.prototype.redraw = function(_dontRedrawEdges) { + var _model_coords = new paper.Point(this.model.get("position")), + _baseRadius = Rkns.Renderer._NODE_SIZE_BASE * Math.exp((this.model.get("size") || 0) * Rkns.Renderer._NODE_SIZE_STEP); + if (!this.is_dragging || !this.paper_coords) { + this.paper_coords = this.renderer.toPaperCoords(_model_coords); + } + this.circle_radius = _baseRadius * this.renderer.scale; + if (this.last_circle_radius !== this.circle_radius) { + if (this.options.editor_mode) { + this.edit_button.setSectorSize(); + this.remove_button.setSectorSize(); + this.link_button.setSectorSize(); + } + var square = new paper.Size(this.circle_radius, this.circle_radius), + topleft = this.paper_coords.subtract(square), + bounds = new paper.Rectangle(topleft, square.multiply(2)); + this.circle.fitBounds(bounds); + if (this.node_image) { + this.node_image.fitBounds(bounds); + } + } else { + this.circle.position = this.paper_coords; + if (this.node_image) { + this.node_image.position = this.paper_coords; + } + } + this.last_circle_radius = this.circle_radius; + + var _text = this.model.get("title") || this.renkan.translate("(untitled)"); + this.title.content = Rkns.Renderer.Utils.shortenText(_text, this.options.node_label_max_length); + + this.title.position = this.paper_coords.add([ + 0, + this.circle_radius * this.h_ratio + this.options.node_label_font_size + this.options.node_label_distance + ]); + var _color = this.model.get("color") || (this.model.get("created_by") || Rkns.Renderer._USER_PLACEHOLDER(this.renkan)).get("color"); + this.circle.strokeColor = _color; + if (this.options.editor_mode) { + this.edit_button.moveTo(this.paper_coords); + this.remove_button.moveTo(this.paper_coords); + this.link_button.moveTo(this.paper_coords); + } + var _img = this.model.get("image"); + if (_img && _img !== this.img) { + var _image = new Image(), + _this = this; + _image.onload = function() { + if (_this.node_image) { + _this.node_image.remove(); + } + _this.renderer.node_layer.activate(); + var _ratio = Math.min(2 / _image.width, 2 / _image.height ); + if (!_this.options.show_node_circles) { + _this.h_ratio = Math.min(1, _image.height / _image.width); + } + var _raster = new paper.Raster(_image); + if (_this.options.clip_node_images) { + var _clip = new paper.Path.Circle([0, 0], 1); + _raster.scale(_ratio); + _this.node_image = new paper.Group(_clip, _raster); + _this.node_image.opacity = .99; + /* This is a workaround to allow clipping at group level + * If opacity was set to 1, paper.js would merge all clipping groups in one (known bug). + */ + _this.node_image.clipped = true; + _clip.__representation = _this; + } else { + _this.node_image = _raster; + } + _this.node_image.__representation = _this; + var square = new paper.Size(_this.circle_radius, _this.circle_radius), + topleft = _this.paper_coords.subtract(square), + bounds = new paper.Rectangle(topleft, square.multiply(2)); + _this.node_image.fitBounds(bounds); + _this.redraw(); + } + _image.src = _img; + } + this.img = _img; + if (this.node_image && !this.img) { + this.node_image.remove(); + delete this.node_image; + } + + if (this.renderer.minimap) { + this.minimap_circle.fillColor = _color; + var minipos = this.renderer.toMinimapCoords(_model_coords), + miniradius = this.renderer.minimap.scale * _baseRadius, + minisize = new paper.Size([miniradius, miniradius]); + this.minimap_circle.fitBounds(minipos.subtract(minisize), minisize.multiply(2)); + } + + if (!_dontRedrawEdges) { + Rkns._.each(this.project.get("edges").filter(function (ed) { return ((ed.to === this.model) || (ed.from === this.model));}), function(edge, index, list){ + var repr = this.renderer.getRepresentationByModel(edge); + if(repr != null && typeof repr.from_representation.paper_coords !== "undefined" && typeof repr.to_representation.paper_coords !== "undefined") { + repr.redraw(); + } + }, this); + } + +} + +Rkns.Renderer.Node.prototype.paperShift = function(_delta) { + if (this.options.editor_mode) { + if (!this.renkan.read_only) { + this.is_dragging = true; + this.paper_coords = this.paper_coords.add(_delta); + this.redraw(); + } + } else { + this.renderer.paperShift(_delta); + } +} + +Rkns.Renderer.Node.prototype.openEditor = function() { + this.renderer.removeRepresentationsOfType("editor"); + var _editor = this.renderer.addRepresentation("NodeEditor",null); + _editor.node_representation = this; + _editor.draw(); +} + +Rkns.Renderer.Node.prototype.select = function() { + this.circle.strokeWidth = this.options.selected_node_stroke_width; + if (this.renderer.isEditable()) { + this.edit_button.show(); + this.remove_button.show(); + this.link_button.show(); + } + var _uri = this.model.get("uri"); + if (_uri) { + Rkns.$('.Rk-Bin-Item').each(function() { + var _el = Rkns.$(this); + if (_el.attr("data-uri") == _uri) { + _el.addClass("selected"); + } + }); + } + if (!this.options.editor_mode) { + this.openEditor(); + } + + if (this.renderer.minimap) { + this.minimap_circle.strokeWidth = this.options.minimap_highlight_weight; + this.minimap_circle.strokeColor = this.options.minimap_highlight_color; + } +} + +Rkns.Renderer.Node.prototype.unselect = function(_newTarget) { + if (!_newTarget || _newTarget.node_representation !== this) { + if (this.options.editor_mode) { + this.edit_button.hide(); + this.remove_button.hide(); + this.link_button.hide(); + } + this.circle.strokeWidth = this.options.node_stroke_width; + Rkns.$('.Rk-Bin-Item').removeClass("selected"); + if (this.renderer.minimap) { + this.minimap_circle.strokeColor = undefined; + } + } +} + +Rkns.Renderer.Node.prototype.highlight = function() { + this.circle.fillColor = this.options.highlighted_node_fill_color; + if (this.node_image) { + this.node_image.opacity = .5; + } +} + +Rkns.Renderer.Node.prototype.unhighlight = function(_newTarget) { + this.circle.fillColor = this.options.node_fill_color; + if (this.node_image) { + this.node_image.opacity = .99; + } +} + +Rkns.Renderer.Node.prototype.saveCoords = function() { + var _coords = this.renderer.toModelCoords(this.paper_coords), + _data = { + position: { + x: _coords.x, + y: _coords.y + } + }; + if (this.renderer.isEditable()) { + this.model.set(_data); + } +} + +Rkns.Renderer.Node.prototype.mouseup = function(_event) { + if (this.renderer.isEditable() && this.renderer.is_dragging) { + this.saveCoords(); + } + else { + this.openEditor(); + } + this.renderer.click_target = null; + this.renderer.is_dragging = false; + this.is_dragging = false; +} + +Rkns.Renderer.Node.prototype.destroy = function(_event) { + this.super("destroy"); + if (this.options.editor_mode) { + this.edit_button.destroy(); + this.remove_button.destroy(); + this.link_button.destroy(); + } + this.circle.remove(); + this.title.remove(); + if (this.renderer.minimap) { + this.minimap_circle.remove(); + } + if (this.node_image) { + this.node_image.remove(); + } +} + +/* */ + +Rkns.Renderer.Edge = Rkns.Utils.inherit(Rkns.Renderer._BaseRepresentation); + +Rkns.Renderer.Edge.prototype._init = function() { + this.renderer.edge_layer.activate(); + this.type = "Edge"; + this.from_representation = this.renderer.getRepresentationByModel(this.model.get("from")); + this.to_representation = this.renderer.getRepresentationByModel(this.model.get("to")); + this.bundle = this.renderer.addToBundles(this); + this.line = new paper.Path(); + this.line.add([0,0],[0,0],[0,0]); + this.line.__representation = this; + this.line.strokeWidth = this.options.edge_stroke_width; + this.arrow = new paper.Path(); + this.arrow.add( + [ 0, 0 ], + [ this.options.edge_arrow_length, this.options.edge_arrow_width / 2 ], + [ 0, this.options.edge_arrow_width ] + ); + this.arrow.__representation = this; + this.text = new paper.PointText(); + this.text.characterStyle = { + font: this.options.edge_label_font, + fontSize: this.options.edge_label_font_size, + fillColor: this.options.edge_label_color + }; + this.text.paragraphStyle.justification = 'center'; + this.text_angle = 0; + this.arrow_angle = 0; + if (this.options.editor_mode) { + this.edit_button = new Rkns.Renderer.EdgeEditButton(this.renderer, null); + this.edit_button.edge_representation = this; + this.remove_button = new Rkns.Renderer.EdgeRemoveButton(this.renderer, null); + this.remove_button.edge_representation = this; + } + + if (this.renderer.minimap) { + this.renderer.minimap.edge_layer.activate(); + this.minimap_line = new paper.Path(); + this.minimap_line.add([0,0],[0,0]); + this.minimap_line.strokeWidth = 1; + } +} + +Rkns.Renderer.Edge.prototype.redraw = function() { + this.from_representation = this.renderer.getRepresentationByModel(this.model.get("from")); + this.to_representation = this.renderer.getRepresentationByModel(this.model.get("to")); + if (!this.from_representation || !this.to_representation) { + return; + } + var _p0a = this.from_representation.paper_coords, + _p1a = this.to_representation.paper_coords, + _v = _p1a.subtract(_p0a), + _r = _v.length, + _u = _v.divide(_r), + _ortho = new paper.Point([- _u.y, _u.x]), + _group_pos = this.bundle.getPosition(this), + _delta = _ortho.multiply( this.options.edge_gap_in_bundles * _group_pos ), + _p0b = _p0a.add(_delta), /* Adding a 4 px difference */ + _p1b = _p1a.add(_delta), /* to differentiate bundled links */ + _a = _v.angle, + _textdelta = _ortho.multiply(this.options.edge_label_distance), + _handle = _v.divide(3), + _color = this.model.get("color") || this.model.get("color") || (this.model.get("created_by") || Rkns.Renderer._USER_PLACEHOLDER(this.renkan)).get("color"); + this.paper_coords = _p0b.add(_p1b).divide(2); + this.line.strokeColor = _color; + this.line.segments[0].point = _p0a; + this.line.segments[1].point = this.paper_coords; + this.line.segments[1].handleIn = _handle.multiply(-1); + this.line.segments[1].handleOut = _handle; + this.line.segments[2].point = _p1a; + this.arrow.rotate(_a - this.arrow_angle); + this.arrow.fillColor = _color; + this.arrow.position = this.paper_coords; + this.arrow_angle = _a; + if (_a > 90) { + _a -= 180; + _textdelta = _textdelta.multiply(-1); + } + if (_a < -90) { + _a += 180; + _textdelta = _textdelta.multiply(-1); + } + this.text.rotate(_a - this.text_angle); + var _text = this.model.get("title"); + this.text.content = Rkns.Renderer.Utils.shortenText(_text, this.options.edge_label_max_length); + this.text.position = this.paper_coords.add(_textdelta); + this.text_angle = _a; + if (this.options.editor_mode) { + this.edit_button.moveTo(this.paper_coords); + this.remove_button.moveTo(this.paper_coords); + } + + if (this.renderer.minimap) { + this.minimap_line.strokeColor = _color; + this.minimap_line.segments[0].point = this.renderer.toMinimapCoords(new paper.Point(this.from_representation.model.get("position"))); + this.minimap_line.segments[1].point = this.renderer.toMinimapCoords(new paper.Point(this.to_representation.model.get("position"))); + } +} + +Rkns.Renderer.Edge.prototype.openEditor = function() { + this.renderer.removeRepresentationsOfType("editor"); + var _editor = this.renderer.addRepresentation("EdgeEditor",null); + _editor.edge_representation = this; + _editor.draw(); +} + +Rkns.Renderer.Edge.prototype.select = function() { + this.line.strokeWidth = this.options.selected_edge_stroke_width; + if (this.renderer.isEditable()) { + this.edit_button.show(); + this.remove_button.show(); + } + if (!this.options.editor_mode) { + this.openEditor(); + } +} + +Rkns.Renderer.Edge.prototype.unselect = function(_newTarget) { + if (!_newTarget || _newTarget.edge_representation !== this) { + if (this.options.editor_mode) { + this.edit_button.hide(); + this.remove_button.hide(); + } + this.line.strokeWidth = this.options.edge_stroke_width; + } +} + +Rkns.Renderer.Edge.prototype.mouseup = function(_event) { + if (!this.renkan.read_only) { + if (this.renderer.is_dragging) { + this.from_representation.saveCoords(); + this.to_representation.saveCoords(); + } else { + this.openEditor(); + } + } + this.renderer.click_target = null; + this.renderer.is_dragging = false; +} + +Rkns.Renderer.Edge.prototype.paperShift = function(_delta) { + if (this.options.editor_mode) { + if (!this.options.read_only) { + this.from_representation.paperShift(_delta); + this.to_representation.paperShift(_delta); + } + } else { + this.renderer.paperShift(_delta); + } +} + +Rkns.Renderer.Edge.prototype.destroy = function() { + this.super("destroy"); + this.line.remove(); + this.arrow.remove(); + this.text.remove(); + if (this.renderer.minimap) { + this.minimap_line.remove(); + } + if (this.options.editor_mode) { + this.edit_button.destroy(); + this.remove_button.destroy(); + } + var _this = this; + this.bundle.edges = Rkns._(this.bundle.edges).reject(function(_edge) { + return _edge === _this; + }); +} + +/* */ + +Rkns.Renderer.TempEdge = Rkns.Utils.inherit(Rkns.Renderer._BaseRepresentation); + +Rkns.Renderer.TempEdge.prototype._init = function() { + this.renderer.edge_layer.activate(); + this.type = "temp-edge"; + + var _color = (this.project.get("users").get(this.renkan.current_user) || Rkns.Renderer._USER_PLACEHOLDER(this.renkan)).get("color"); + this.line = new paper.Path(); + this.line.strokeColor = _color; + this.line.add([0,0],[0,0]); + this.line.__representation = this; + this.arrow = new paper.Path(); + this.arrow.fillColor = _color; + this.arrow.add( + [ 0, 0 ], + [ this.options.edge_arrow_length, this.options.edge_arrow_width / 2 ], + [ 0, this.options.edge_arrow_width ] + ); + this.arrow.__representation = this; + this.arrow_angle = 0; +} + +Rkns.Renderer.TempEdge.prototype.redraw = function() { + var _p0 = this.from_representation.paper_coords, + _p1 = this.end_pos, + _a = _p1.subtract(_p0).angle, + _c = _p0.add(_p1).divide(2); + this.line.segments[0].point = _p0; + this.line.segments[1].point = _p1; + this.arrow.rotate(_a - this.arrow_angle); + this.arrow.position = _c; + this.arrow_angle = _a; +} + +Rkns.Renderer.TempEdge.prototype.paperShift = function(_delta) { + if (!this.renderer.isEditable()) { + this.renderer.removeRepresentation(_this); + paper.view.draw(); + return; + } + this.end_pos = this.end_pos.add(_delta); + var _hitResult = paper.project.hitTest(this.end_pos); + this.renderer.findTarget(_hitResult); + this.redraw(); +} + +Rkns.Renderer.TempEdge.prototype.mouseup = function(_event) { + var _hitResult = paper.project.hitTest(_event.point), + _model = this.from_representation.model, + _endDrag = true; + if (_hitResult && typeof _hitResult.item.__representation !== "undefined") { + var _target = _hitResult.item.__representation; + if (_target.type === "Node" && _model !== _target.model) { + var _data = { + id: Rkns.Utils.getUID('edge'), + created_by: this.renkan.current_user, + from: _model.get("_id"), + to: _target.model.get("_id") + }; + if (this.renderer.isEditable()) { + this.project.addEdge(_data); + } + } + if (_model === _target.model || (_target.node_representation && _target.node_representation.model === _model)) { + _endDrag = false; + this.renderer.is_dragging = true; + } + } + if (_endDrag) { + this.renderer.click_target = null; + this.renderer.is_dragging = false; + this.renderer.removeRepresentation(this); + paper.view.draw(); + } +} + +Rkns.Renderer.TempEdge.prototype.destroy = function() { + this.arrow.remove(); + this.line.remove(); +} + +/* */ + +Rkns.Renderer.NodeEditor = Rkns.Utils.inherit(Rkns.Renderer._BaseRepresentation); + +Rkns.Renderer.NodeEditor.prototype._init = function() { + this.renderer.buttons_layer.activate(); + this.type = "editor"; + this.editor_block = new paper.Path(); + var _pts = Rkns._(Rkns._.range(8)).map(function() {return [0,0]}); + this.editor_block.add.apply(this.editor_block, _pts); + this.editor_block.strokeWidth = this.options.tooltip_border_width; + this.editor_block.strokeColor = this.options.tooltip_border_color; + this.editor_block.opacity = .8; + this.editor_$ = Rkns.$('
        ') + .appendTo(this.renderer.editor_$) + .css({ + position: "absolute", + opacity: .8 + }) + .hide(); +} + +Rkns.Renderer.NodeEditor.prototype.template = Rkns._.template( + '

        ×<%-translate("Edit Node")%>

        ' + + '

        ' + + '

        ' + + '

        ' + + '

        <%-translate("Size:")%>-<%-node.size%>+

        ' + + '
        <%-translate("Node color:")%>
          ' + + '<% _(Rkns.pickerColors).each(function(c) { %>
        • <% }); %>
        <%- translate("Choose color") %>
        ' + + '' + + '

        ' + + '

        ' + + '<% if (node.has_creator) { %>

        <%-translate("Created by:")%> <%- Rkns.Renderer.Utils.shortenText(node.created_by_title, 25) %>

        <% } %>' +); + +Rkns.Renderer.NodeEditor.prototype.readOnlyTemplate = Rkns._.template( + '

        ×' + + '<% if (node.uri) { %><% } %><%-node.title%><% if (node.uri) { %><% } %>

        ' + + '<% if (node.uri) { %>

        <%-node.short_uri%>

        <% } %>' + + '

        <%-node.description%>

        ' + + '<% if (node.has_creator) { %>

        <%-translate("Created by:")%><%- Rkns.Renderer.Utils.shortenText(node.created_by_title, 25) %>

        <% } %>' +); + +Rkns.Renderer.NodeEditor.prototype.draw = function() { + var _model = this.node_representation.model, + _created_by = _model.get("created_by") || Rkns.Renderer._USER_PLACEHOLDER(this.renkan), + _template = (this.renderer.isEditable() ? this.template : this.readOnlyTemplate ), + _image_placeholder = this.options.static_url + "img/image-placeholder.png", + _size = (_model.get("size") || 0); + this.editor_$ + .html(_template({ + node: { + has_creator: !!_model.get("created_by"), + title: _model.get("title"), + uri: _model.get("uri"), + short_uri: Rkns.Renderer.Utils.shortenText((_model.get("uri") || "").replace(/^(https?:\/\/)?(www\.)?/,'').replace(/\/$/,''),40), + description: _model.get("description"), + image: _model.get("image") || "", + image_placeholder: _image_placeholder, + color: _model.get("color") || _created_by.get("color"), + created_by_color: _created_by.get("color"), + created_by_title: _created_by.get("title"), + size: (_size > 0 ? "+" : "") + _size + }, + translate: this.renkan.translate + })); + this.redraw(); + var _this = this, + closeEditor = function() { + _this.renderer.removeRepresentation(_this); + paper.view.draw(); + } + + this.editor_$.find(".Rk-CloseX").click(closeEditor); + + if (this.renderer.isEditable()) { + + var onFieldChange = Rkns._(function() { + Rkns._(function() { + if (_this.renderer.isEditable()) { + var _uri = _this.editor_$.find(".Rk-Edit-URI").val(), + _image = _this.editor_$.find(".Rk-Edit-Image").val(); + _this.editor_$.find(".Rk-Edit-ImgPreview").attr("src", _image || _image_placeholder); + _this.editor_$.find(".Rk-Edit-Goto").attr("href",_uri); + var _data = { + title: _this.editor_$.find(".Rk-Edit-Title").val(), + description: _this.editor_$.find(".Rk-Edit-Description").val(), + uri: _uri, + image: _image + } + _model.set(_data); + _this.redraw(); + } else { + closeEditor(); + } + + }).defer(); + }).throttle(500); + + this.editor_$.find("input, textarea").bind("change keyup paste", onFieldChange); + + this.editor_$.find(".Rk-Edit-Image-File").bind("change", function() { + if (this.files.length) { + var f = this.files[0], + fr = new FileReader(); + if (f.type.substr(0,5) !== "image") { + alert(_this.renkan.translate("This file is not an image")); + return; + } + if (f.size > (Rkns.Renderer._IMAGE_MAX_KB * 1024)) { + alert(_this.renkan.translate("Image size must be under ")+Rkns.Renderer._IMAGE_MAX_KB+_this.renkan.translate("KB")); + return; + } + fr.onload = function(e) { + _this.editor_$.find(".Rk-Edit-Image").val(e.target.result); + onFieldChange(); + } + fr.readAsDataURL(f); + } + }); + this.editor_$.find(".Rk-Edit-Title")[0].focus(); + this.editor_$.find(".Rk-Edit-ColorPicker-Wrapper").hover( + function() { _this.editor_$.find(".Rk-Edit-ColorPicker").show(); }, + function() { _this.editor_$.find(".Rk-Edit-ColorPicker").hide(); } + ); + this.editor_$.find(".Rk-Edit-ColorPicker li").hover( + function() { _this.editor_$.find(".Rk-Edit-Color").css("background", $(this).attr("data-color")); }, + function() { _this.editor_$.find(".Rk-Edit-Color").css("background", _model.get("color") || (_model.get("created_by") || Rkns.Renderer._USER_PLACEHOLDER(this.renkan)).get("color")) } + ).click(function() { + if (_this.renderer.isEditable()) { + _model.set("color", $(this).attr("data-color")); + paper.view.draw(); + } else { + closeEditor(); + } + }); + + function shiftSize(n) { + if (_this.renderer.isEditable()) { + var _newsize = n+(_model.get("size") || 0); + _this.editor_$.find(".Rk-Edit-Size-Value").text((_newsize > 0 ? "+" : "") + _newsize); + _model.set("size", _newsize); + paper.view.draw(); + } else { + closeEditor(); + } + } + + this.editor_$.find(".Rk-Edit-Size-Down").click(function() { + shiftSize(-1); + return false; + }); + this.editor_$.find(".Rk-Edit-Size-Up").click(function() { + shiftSize(1); + return false; + }); + } + this.editor_$.find("img").load(function() { + _this.redraw(); + }); +} + +Rkns.Renderer.NodeEditor.prototype.redraw = function() { + var _coords = this.node_representation.paper_coords; + Rkns.Renderer.Utils.drawEditBox(this.options, _coords, this.editor_block, this.node_representation.circle_radius * .75, this.editor_$); + this.editor_$.show(); + paper.view.draw(); +} + +Rkns.Renderer.NodeEditor.prototype.destroy = function() { + this.editor_block.remove(); + this.editor_$.detach(); +} + +/* */ + +Rkns.Renderer.EdgeEditor = Rkns.Utils.inherit(Rkns.Renderer._BaseRepresentation); + +Rkns.Renderer.EdgeEditor.prototype._init = function() { + this.renderer.buttons_layer.activate(); + this.type = "editor"; + this.editor_block = new paper.Path(); + var _pts = Rkns._(Rkns._.range(8)).map(function() {return [0,0]}); + this.editor_block.add.apply(this.editor_block, _pts); + this.editor_block.strokeWidth = this.options.tooltip_border_width; + this.editor_block.strokeColor = this.options.tooltip_border_color; + this.editor_block.opacity = .8; + this.editor_$ = Rkns.$('
        ') + .appendTo(this.renderer.editor_$) + .css({ + position: "absolute", + opacity: .8 + }) + .hide(); +} + +Rkns.Renderer.EdgeEditor.prototype.template = Rkns._.template( + '

        ×<%-translate("Edit Edge")%>

        ' + + '

        ' + + '

        ' + + '<% if (properties.length) { %>

        <% } %>' + + '
        <%-translate("Edge color:")%>
          ' + + '<% _(Rkns.pickerColors).each(function(c) { %>
        • <% }); %>
        <%- translate("Choose color") %>
        ' + + '

        <%- translate("Change edge direction") %>

        ' + + '

        <%-translate("From:")%><%- Rkns.Renderer.Utils.shortenText(edge.from_title, 25) %>

        ' + + '

        <%-translate("To:")%><%- Rkns.Renderer.Utils.shortenText(edge.to_title, 25) %>

        ' + + '<% if (edge.has_creator) { %>

        <%-translate("Created by:")%><%- Rkns.Renderer.Utils.shortenText(edge.created_by_title, 25) %>

        <% } %>' +); + +Rkns.Renderer.EdgeEditor.prototype.readOnlyTemplate = Rkns._.template( + '

        ×' + + '<% if (edge.uri) { %><% } %><%-edge.title%><% if (edge.uri) { %><% } %>

        ' + + '<% if (edge.uri) { %>

        <%-edge.short_uri%>

        <% } %>' + + '

        <%-edge.description%>

        ' + + '

        <%-translate("From:")%><%- Rkns.Renderer.Utils.shortenText(edge.from_title, 25) %>

        ' + + '

        <%-translate("To:")%><%- Rkns.Renderer.Utils.shortenText(edge.to_title, 25) %>

        ' + + '<% if (edge.has_creator) { %>

        <%-translate("Created by:")%><%- Rkns.Renderer.Utils.shortenText(edge.created_by_title, 25) %>

        <% } %>' +); + +Rkns.Renderer.EdgeEditor.prototype.draw = function() { + var _model = this.edge_representation.model, + _from_model = _model.get("from"), + _to_model = _model.get("to"), + _created_by = _model.get("created_by") || Rkns.Renderer._USER_PLACEHOLDER(this.renkan), + _template = (this.renderer.isEditable() ? this.template : this.readOnlyTemplate); + this.editor_$ + .html(_template({ + edge: { + has_creator: !!_model.get("created_by"), + title: _model.get("title"), + uri: _model.get("uri"), + short_uri: Rkns.Renderer.Utils.shortenText((_model.get("uri") || "").replace(/^(https?:\/\/)?(www\.)?/,'').replace(/\/$/,''),40), + description: _model.get("description"), + color: _model.get("color") || _created_by.get("color"), + from_title: _from_model.get("title"), + to_title: _to_model.get("title"), + from_color: _from_model.get("color") || (_from_model.get("created_by") || Rkns.Renderer._USER_PLACEHOLDER(this.renkan)).get("color"), + to_color: _to_model.get("color") || (_to_model.get("created_by") || Rkns.Renderer._USER_PLACEHOLDER(this.renkan)).get("color"), + created_by_color: _created_by.get("color"), + created_by_title: _created_by.get("title") + }, + translate: this.renkan.translate, + properties: this.options.properties + })); + this.redraw(); + var _this = this, + closeEditor = function() { + _this.renderer.removeRepresentation(_this); + paper.view.draw(); + } + this.editor_$.find(".Rk-CloseX").click(closeEditor); + + if (this.renderer.isEditable()) { + + var onFieldChange = Rkns._(function() { + Rkns._(function() { + if (_this.renderer.isEditable()) { + _this.editor_$.find(".Rk-Edit-Goto").attr("href",_this.editor_$.find(".Rk-Edit-URI").val()); + var _data = { + title: _this.editor_$.find(".Rk-Edit-Title").val(), + uri: _this.editor_$.find(".Rk-Edit-URI").val() + } + _model.set(_data); + paper.view.draw(); + } else { + closeEditor(); + } + }).defer(); + }).throttle(500); + + this.editor_$.find("input").bind("keyup change paste", onFieldChange); + this.editor_$.find(".Rk-Edit-Vocabulary").change(function() { + var e = $(this), + v = e.val(); + if (v) { + _this.editor_$.find(".Rk-Edit-Title").val(e.find(":selected").text()); + _this.editor_$.find(".Rk-Edit-URI").val(v); + onFieldChange(); + } + }); + this.editor_$.find(".Rk-Edit-Direction").click(function() { + if (_this.renderer.isEditable()) { + _model.set({ + from: _model.get("to"), + to: _model.get("from") + }); + _this.draw(); + } else { + closeEditor(); + } + }); + this.editor_$.find(".Rk-Edit-ColorPicker-Wrapper").hover( + function() { _this.editor_$.find(".Rk-Edit-ColorPicker").show(); }, + function() { _this.editor_$.find(".Rk-Edit-ColorPicker").hide(); } + ); + this.editor_$.find(".Rk-Edit-ColorPicker li").hover( + function() { _this.editor_$.find(".Rk-Edit-Color").css("background", $(this).attr("data-color")); }, + function() { _this.editor_$.find(".Rk-Edit-Color").css("background", _model.get("color") || (_model.get("created_by") || Rkns.Renderer._USER_PLACEHOLDER(this.renkan)).get("color")); } + ).click(function() { + if (_this.renderer.isEditable()) { + _model.set("color", $(this).attr("data-color")); + paper.view.draw(); + } else { + closeEditor(); + } + }); + } +} + +Rkns.Renderer.EdgeEditor.prototype.redraw = function() { + var _coords = this.edge_representation.paper_coords; + Rkns.Renderer.Utils.drawEditBox(this.options, _coords, this.editor_block, 5, this.editor_$); + this.editor_$.show(); + paper.view.draw(); +} + +Rkns.Renderer.EdgeEditor.prototype.destroy = function() { + this.editor_block.remove(); + this.editor_$.detach(); +} + +/* */ + +Rkns.Renderer.NodeEditButton = Rkns.Utils.inherit(Rkns.Renderer._BaseRepresentation); + +Rkns.Renderer.NodeEditButton.prototype._init = function() { + this.type = "Node-edit-button"; + this.lastSectorInner = 0; +} + +Rkns.Renderer.NodeEditButton.prototype.setSectorSize = function() { + var sectorInner = this.node_representation.circle_radius; + if (sectorInner !== this.lastSectorInner) { + if (this.sector) { + this.sector.destroy(); + } + this.sector = Rkns.Renderer.Utils.sector(this, 1 + sectorInner, Rkns.Renderer._NODE_BUTTON_WIDTH + sectorInner, - 90, 30, 1, this.options.static_url+'img/edit.png', this.renkan.translate("Edit")); + this.lastSectorInner = sectorInner; + } +} + +Rkns.Renderer.NodeEditButton.prototype.moveTo = function(_pos) { + this.sector.moveTo(_pos); +} + +Rkns.Renderer.NodeEditButton.prototype.show = function() { + this.sector.show(); +} + +Rkns.Renderer.NodeEditButton.prototype.hide = function() { + this.sector.hide(); +} + +Rkns.Renderer.NodeEditButton.prototype.select = function() { + this.sector.select(); +} + +Rkns.Renderer.NodeEditButton.prototype.unselect = function(_newTarget) { + this.sector.unselect(); + if (!_newTarget || (_newTarget !== this.node_representation && _newTarget.node_representation !== this.node_representation)) { + this.node_representation.unselect(); + } +} + +Rkns.Renderer.NodeEditButton.prototype.mouseup = function() { + if (!this.renderer.is_dragging) { + this.node_representation.openEditor(); + } +} + +Rkns.Renderer.NodeEditButton.prototype.destroy = function() { + this.sector.destroy(); +} + +/* */ + +Rkns.Renderer.NodeRemoveButton = Rkns.Utils.inherit(Rkns.Renderer._BaseRepresentation); + +Rkns.Renderer.NodeRemoveButton.prototype._init = function() { + this.type = "Node-remove-button"; + this.lastSectorInner = 0; +} + +Rkns.Renderer.NodeRemoveButton.prototype.setSectorSize = function() { + var sectorInner = this.node_representation.circle_radius; + if (sectorInner !== this.lastSectorInner) { + if (this.sector) { + this.sector.destroy(); + } + this.sector = Rkns.Renderer.Utils.sector(this, 1 + sectorInner, Rkns.Renderer._NODE_BUTTON_WIDTH + sectorInner, - 210, - 90, 1, this.options.static_url+'img/remove.png', this.renkan.translate("Remove")); + this.lastSectorInner = sectorInner; + } +} + +Rkns.Renderer.NodeRemoveButton.prototype.moveTo = function(_pos) { + this.sector.moveTo(_pos); +} + +Rkns.Renderer.NodeRemoveButton.prototype.show = function() { + this.sector.show(); +} + +Rkns.Renderer.NodeRemoveButton.prototype.hide = function() { + this.sector.hide(); +} + +Rkns.Renderer.NodeRemoveButton.prototype.select = function() { + this.sector.select(); +} + +Rkns.Renderer.NodeRemoveButton.prototype.unselect = function(_newTarget) { + this.sector.unselect(); + if (!_newTarget || (_newTarget !== this.node_representation && _newTarget.node_representation !== this.node_representation)) { + this.node_representation.unselect(); + } +} + +Rkns.Renderer.NodeRemoveButton.prototype.mouseup = function() { + this.renderer.removeRepresentationsOfType("editor"); + if (this.renderer.isEditable() && confirm(this.renkan.translate('Do you really wish to remove node ') + '"' + this.node_representation.model.get("title") + '"?')) { + this.project.removeNode(this.node_representation.model); + } +} + +Rkns.Renderer.NodeRemoveButton.prototype.destroy = function() { + this.sector.destroy(); +} + +/* */ + +Rkns.Renderer.NodeLinkButton = Rkns.Utils.inherit(Rkns.Renderer._BaseRepresentation); + +Rkns.Renderer.NodeLinkButton.prototype._init = function() { + this.type = "Node-link-button"; + this.lastSectorInner = 0; +} + +Rkns.Renderer.NodeLinkButton.prototype.setSectorSize = function() { + var sectorInner = this.node_representation.circle_radius; + if (sectorInner !== this.lastSectorInner) { + if (this.sector) { + this.sector.destroy(); + } + this.sector = Rkns.Renderer.Utils.sector(this, 1 + sectorInner, Rkns.Renderer._NODE_BUTTON_WIDTH + sectorInner, 30, 150, 1, this.options.static_url+'img/link.png', this.renkan.translate("Link to another node")); + this.lastSectorInner = sectorInner; + } +} + +Rkns.Renderer.NodeLinkButton.prototype.moveTo = function(_pos) { + this.sector.moveTo(_pos); +} + +Rkns.Renderer.NodeLinkButton.prototype.show = function() { + this.sector.show(); +} + +Rkns.Renderer.NodeLinkButton.prototype.hide = function() { + this.sector.hide(); +} + +Rkns.Renderer.NodeLinkButton.prototype.select = function() { + this.sector.select(); +} + +Rkns.Renderer.NodeLinkButton.prototype.unselect = function(_newTarget) { + this.sector.unselect(); + if (!_newTarget || (_newTarget !== this.node_representation && _newTarget.node_representation !== this.node_representation)) { + this.node_representation.unselect(); + } +} + +Rkns.Renderer.NodeLinkButton.prototype.destroy = function() { + this.sector.destroy(); +} + +/* */ + +Rkns.Renderer.EdgeEditButton = Rkns.Utils.inherit(Rkns.Renderer._BaseRepresentation); + +Rkns.Renderer.EdgeEditButton.prototype._init = function() { + this.type = "Edge-edit-button"; + this.sector = Rkns.Renderer.Utils.sector(this, Rkns.Renderer._EDGE_BUTTON_INNER, Rkns.Renderer._EDGE_BUTTON_OUTER, - 90, 90, 1, this.options.static_url+'img/edit.png', this.renkan.translate("Edit")); +} + +Rkns.Renderer.EdgeEditButton.prototype.moveTo = function(_pos) { + this.sector.moveTo(_pos); +} + +Rkns.Renderer.EdgeEditButton.prototype.show = function() { + this.sector.show(); +} + +Rkns.Renderer.EdgeEditButton.prototype.hide = function() { + this.sector.hide(); +} + +Rkns.Renderer.EdgeEditButton.prototype.select = function() { + this.sector.select(); +} + +Rkns.Renderer.EdgeEditButton.prototype.unselect = function(_newTarget) { + this.sector.unselect(); + if (!_newTarget || (_newTarget !== this.edge_representation && _newTarget.edge_representation !== this.edge_representation)) { + this.edge_representation.unselect(); + } +} + +Rkns.Renderer.EdgeEditButton.prototype.mouseup = function() { + if (!this.renderer.is_dragging) { + this.edge_representation.openEditor(); + } +} + +Rkns.Renderer.EdgeEditButton.prototype.destroy = function() { + this.sector.destroy(); +} + +/* */ + +Rkns.Renderer.EdgeRemoveButton = Rkns.Utils.inherit(Rkns.Renderer._BaseRepresentation); + +Rkns.Renderer.EdgeRemoveButton.prototype._init = function() { + this.type = "Edge-remove-button"; + this.sector = Rkns.Renderer.Utils.sector(this, Rkns.Renderer._EDGE_BUTTON_INNER, Rkns.Renderer._EDGE_BUTTON_OUTER, - 270, -90, 1, this.options.static_url+'img/remove.png', this.renkan.translate("Remove")); +} +Rkns.Renderer.EdgeRemoveButton.prototype.moveTo = function(_pos) { + this.sector.moveTo(_pos); +} + +Rkns.Renderer.EdgeRemoveButton.prototype.show = function() { + this.sector.show(); +} + +Rkns.Renderer.EdgeRemoveButton.prototype.hide = function() { + this.sector.hide(); +} + +Rkns.Renderer.EdgeRemoveButton.prototype.select = function() { + this.sector.select(); +} + +Rkns.Renderer.EdgeRemoveButton.prototype.unselect = function(_newTarget) { + this.sector.unselect(); + if (!_newTarget || (_newTarget !== this.edge_representation && _newTarget.edge_representation !== this.edge_representation)) { + this.edge_representation.unselect(); + } +} + +Rkns.Renderer.EdgeRemoveButton.prototype.mouseup = function() { + this.renderer.removeRepresentationsOfType("editor"); + if (this.renderer.isEditable() && confirm(this.renkan.translate('Do you really wish to remove edge ') + '"' + this.edge_representation.model.get("title") + '"?')) { + this.project.removeEdge(this.edge_representation.model); + } +} + +Rkns.Renderer.EdgeRemoveButton.prototype.destroy = function() { + this.sector.destroy(); +} + +/* */ + +Rkns.Renderer.MiniFrame = Rkns.Utils.inherit(Rkns.Renderer._BaseRepresentation); + +Rkns.Renderer.MiniFrame.prototype.paperShift = function(_delta) { + this.renderer.offset = this.renderer.offset.subtract(_delta.divide(this.renderer.minimap.scale).multiply(this.renderer.scale)); + this.renderer.redraw(); +} + +Rkns.Renderer.MiniFrame.prototype.mouseup = function(_delta) { + this.renderer.click_target = null; + this.renderer.is_dragging = false; +} + +/* */ + +Rkns.Renderer.Scene = function(_renkan) { + this.renkan = _renkan; + this.$ = Rkns.$(".Rk-Render"); + this.representations = []; + this.$.html(this.template(_renkan)); + this.onStatusChange(); + this.canvas_$ = this.$.find(".Rk-Canvas"); + this.editor_$ = this.$.find(".Rk-Editor"); + this.notif_$ = this.$.find(".Rk-Notifications"); + paper.setup(this.canvas_$[0]); + this.scale = 1; + this.offset = paper.view.center; + this.totalScroll = 0; + this.click_target = null; + this.selected_target = null; + this.edge_layer = new paper.Layer(); + this.node_layer = new paper.Layer(); + this.buttons_layer = new paper.Layer(); + + if (_renkan.options.show_minimap) { + this.minimap = { + background_layer: new paper.Layer(), + edge_layer: new paper.Layer(), + node_layer: new paper.Layer(), + node_group: new paper.Group(), + size: new paper.Size( _renkan.options.minimap_width, _renkan.options.minimap_height ) + } + + this.minimap.background_layer.activate(); + this.minimap.topleft = paper.view.bounds.bottomRight.subtract(this.minimap.size); + this.minimap.rectangle = new paper.Path.Rectangle(this.minimap.topleft.subtract([2,2]), this.minimap.size.add([4,4])); + this.minimap.rectangle.fillColor = _renkan.options.minimap_background_color; + this.minimap.rectangle.strokeColor = _renkan.options.minimap_border_color; + this.minimap.rectangle.strokeWidth = 4; + this.minimap.offset = new paper.Point(this.minimap.size.divide(2)); + this.minimap.scale = .1; + + this.minimap.node_layer.activate(); + this.minimap.cliprectangle = new paper.Path.Rectangle(this.minimap.topleft, this.minimap.size); + this.minimap.node_group.addChild(this.minimap.cliprectangle); + this.minimap.node_group.clipped = true; + this.minimap.miniframe = new paper.Path.Rectangle(this.minimap.topleft, this.minimap.size); + this.minimap.node_group.addChild(this.minimap.miniframe); + this.minimap.miniframe.fillColor = '#c0c0ff'; + this.minimap.miniframe.opacity = .3; + this.minimap.miniframe.strokeColor = '#000080'; + this.minimap.miniframe.strokeWidth = 3; + this.minimap.miniframe.__representation = new Rkns.Renderer.MiniFrame(this, null); + } + + this.bundles = []; + this.click_mode = false; + var _tool = new paper.Tool(), + _this = this, + _allowScroll = true; + + _tool.minDistance = Rkns.Renderer._MIN_DRAG_DISTANCE; + _tool.onMouseMove = function(_event) { + _this.onMouseMove(_event); + } + _tool.onMouseDown = function(_event) { + _this.onMouseDown(_event); + } + _tool.onMouseDrag = function(_event) { + _this.onMouseDrag(_event); + } + this.canvas_$.mouseup(function(_event) { + _this.onMouseUp(_event); + }); + this.canvas_$.mousewheel(function(_event, _delta) { + if (_allowScroll) { + _this.onScroll(_event, _delta); + } + }); + this.canvas_$.dblclick(function(_event) { + _this.onDoubleClick(_event); + }); + this.canvas_$.on("dragover", function(_event) { + _event.stopPropagation(); + _event.preventDefault(); + }); + this.canvas_$.on("dragenter", function(_event) { + _allowScroll = false; + _event.stopPropagation(); + _event.preventDefault(); + }); + this.canvas_$.on("dragleave", function(_event) { + _allowScroll = true; + _event.stopPropagation(); + _event.preventDefault(); + }); + this.canvas_$.on("drop", function(_event) { + _event.stopPropagation(); + _event.preventDefault(); + _allowScroll = true; + if (!_this.isEditable()) { + return; + } + var res = {}; + Rkns._(_event.originalEvent.dataTransfer.types).each(function(t) { + try { + res[t] = _event.originalEvent.dataTransfer.getData(t); + } catch(e) {} + }); + var text = _event.originalEvent.dataTransfer.getData("Text"); + if (typeof text === "string") { + switch(text[0]) { + case "{": + case "[": + try { + var data = JSON.parse(text); + _(res).extend(data); + } + catch(e) { + if (!res["text/plain"]) { + res["text/plain"] = text; + } + } + break; + case "<": + if (!res["text/html"]) { + res["text/html"] = text; + } + break; + default: + if (!res["text/plain"]) { + res["text/plain"] = text; + } + } + } + var url = _event.originalEvent.dataTransfer.getData("URL"); + if (url && !res["text/uri-list"]) { + res["text/uri-list"] = url; + } + if (res["text/json"] || res["application/json"]) { + try { + var data = JSON.parse(res["text/json"] || res["application/json"]); + _(res).extend(data); + } + catch(e) {} + } + var newNode = {}; + switch(res["text/x-iri-specific-site"]) { + case "twitter": + var snippet = Rkns.$('
        ').html(res["text/x-iri-selected-html"]), + tweetdiv = snippet.find(".tweet") + newNode.title = _renkan.translate("Tweet by ") + tweetdiv.attr("data-name"); + newNode.uri = "http://twitter.com/" + tweetdiv.attr("data-screen-name") + "/status/" + tweetdiv.attr("data-tweet-id"); + newNode.image = tweetdiv.find(".avatar").attr("src"); + newNode.description = tweetdiv.find(".js-tweet-text:first").text(); + break; + case "google": + var snippet = Rkns.$('
        ').html(res["text/x-iri-selected-html"]); + newNode.title = snippet.find("h3:first").text().trim(); + newNode.uri = snippet.find("h3 a").attr("href"); + newNode.description = snippet.find(".st:first").text().trim(); + break; + case undefined: + default: + if (res["text/x-iri-source-uri"]) { + newNode.uri = res["text/x-iri-source-uri"]; + } + if (res["text/plain"] || res["text/x-iri-selected-text"]) { + newNode.description = (res["text/plain"] || res["text/x-iri-selected-text"]).replace(/[\s\n]+/gm,' ').trim(); + } + if (res["text/html"] || res["text/x-iri-selected-html"]) { + var snippet = Rkns.$('
        ').html(res["text/html"] || res["text/x-iri-selected-html"]); + newNode.image = snippet.find("img").attr("src") || ''; + newNode.uri = snippet.find("a").attr("href") || newNode.uri; + newNode.title = snippet.find("[title]").attr("title"); + newNode.description = snippet.text().replace(/[\s\n]+/gm,' ').trim(); + } + if (res["text/uri-list"]) { + newNode.uri = res["text/uri-list"]; + } + if (res["text/x-moz-url"] && !newNode.title) { + newNode.title = (res["text/x-moz-url"].split("\n")[1] || "").trim(); + if (newNode.title === newNode.uri) { + newNode.title = false; + } + } + if (res["text/x-iri-source-title"] && !newNode.title) { + newNode.title = res["text/x-iri-source-title"]; + } + if (res["text/html"] || res["text/x-iri-selected-html"]) { + newNode.image = snippet.find("[data-image]").attr("data-image") || newNode.image; + newNode.uri = snippet.find("[data-uri]").attr("data-uri") || newNode.uri; + newNode.title = snippet.find("[data-title]").attr("data-title") || newNode.title; + newNode.description = snippet.find("[data-description]").attr("data-description") || newNode.description; + } + } + var fields = ["title", "description", "uri", "image"]; + for (var i = 0; i < fields.length; i++) { + var f = fields[i]; + if (res["text/x-iri-" + f] || res[f]) { + newNode[f] = res["text/x-iri-" + f] || res[f]; + } + } + if (newNode.title || newNode.description || newNode.uri) { + var _off = _this.canvas_$.offset(), + _point = new paper.Point([ + _event.originalEvent.pageX - _off.left, + _event.originalEvent.pageY - _off.top + ]), + _coords = _this.toModelCoords(_point), + _data = { + id: Rkns.Utils.getUID('node'), + created_by: _this.renkan.current_user, + uri: newNode.uri || "", + title: newNode.title || _this.renkan.translate("Dragged resource"), + description: newNode.description || "", + image: newNode.image || "", + color: newNode.color || undefined, + position: { + x: _coords.x, + y: _coords.y + } + }; + var _node = _this.renkan.project.addNode(_data); + _this.getRepresentationByModel(_node).openEditor(); + } + }) + this.editor_$.find(".Rk-ZoomOut").click(function() { + var _newScale = _this.scale * Math.SQRT1_2, + _offset = new paper.Point([ + _this.canvas_$.width(), + _this.canvas_$.height() + ]).multiply( .5 * ( 1 - Math.SQRT1_2 ) ).add(_this.offset.multiply( Math.SQRT1_2 )); + _this.setScale( _newScale, _offset ); + }); + this.editor_$.find(".Rk-ZoomIn").click(function() { + var _newScale = _this.scale * Math.SQRT2, + _offset = new paper.Point([ + _this.canvas_$.width(), + _this.canvas_$.height() + ]).multiply( .5 * ( 1 - Math.SQRT2 ) ).add(_this.offset.multiply( Math.SQRT2 )); + _this.setScale( _newScale, _offset ); + }); + this.$.find(".Rk-CurrentUser").mouseenter( + function() { _this.$.find(".Rk-UserList").slideDown() } + ); + this.$.find(".Rk-Users").mouseleave( + function() { _this.$.find(".Rk-UserList").slideUp(); } + ); + this.$.find(".Rk-FullScreen-Button").click(function() { + var _isFull = document.fullScreen || document.mozFullScreen || document.webkitIsFullScreen, + _el = _this.renkan.$[0], + _requestMethods = ["requestFullScreen","mozRequestFullScreen","webkitRequestFullScreen"], + _cancelMethods = ["cancelFullScreen","mozCancelFullScreen","webkitCancelFullScreen"]; + if (_isFull) { + for (var i = 0; i < _cancelMethods.length; i++) { + if (typeof document[_cancelMethods[i]] === "function") { + document[_cancelMethods[i]](); + break; + } + } + } else { + for (var i = 0; i < _requestMethods.length; i++) { + if (typeof _el[_requestMethods[i]] === "function") { + _el[_requestMethods[i]](); + break; + } + } + } + }); + this.$.find(".Rk-AddNode-Button").click(function() { + if (_this.click_mode === Rkns.Renderer._CLICKMODE_ADDNODE) { + _this.click_mode = false; + _this.notif_$.hide(); + } else { + _this.click_mode = Rkns.Renderer._CLICKMODE_ADDNODE; + _this.notif_$.text(_renkan.translate("Click on the background canvas to add a node")).fadeIn(); + } + }); + this.$.find(".Rk-AddEdge-Button").click(function() { + if (_this.click_mode === Rkns.Renderer._CLICKMODE_STARTEDGE || _this.click_mode === Rkns.Renderer._CLICKMODE_ENDEDGE) { + _this.click_mode = false; + _this.notif_$.hide(); + } else { + _this.click_mode = Rkns.Renderer._CLICKMODE_STARTEDGE; + _this.notif_$.text(_renkan.translate("Click on a first node to start the edge")).fadeIn(); + } + }); + this.$.find(".Rk-Bookmarklet-Button") + .attr("href","javascript:" + Rkns.Renderer._BOOKMARKLET_CODE(_renkan)) + .click(function(){ + _this.notif_$ + .text(_renkan.translate("Drag this button to your bookmark bar. When on a third-party website, click it to enable drag-and-drop from the website to Renkan.")) + .fadeIn() + .delay(5000) + .fadeOut(); + return false; + }); + this.$.find(".Rk-TopBar-Button").mouseover(function() { + Rkns.$(this).find(".Rk-TopBar-Tooltip").show(); + }).mouseout(function() { + Rkns.$(this).find(".Rk-TopBar-Tooltip").hide(); + }); + this.$.find(".Rk-Fold-Bins").click(function() { + var bins = _renkan.$.find(".Rk-Bins"); + if (bins.offset().left < 0) { + bins.animate({left: 0},250); + _this.$.animate({left: 300},250,function() { + var w = _this.$.width(); + paper.view.viewSize = new paper.Size([w, _this.canvas_$.height()]); + }); + $(this).html("«"); + } else { + bins.animate({left: -300},250); + _this.$.animate({left: 0},250,function() { + var w = _this.$.width(); + paper.view.viewSize = new paper.Size([w, _this.canvas_$.height()]); + }); + $(this).html("»"); + } + }); + + paper.view.onResize = function(_event) { + _this.offset = _this.offset.add(_event.delta.divide(2)); + if (_this.minimap) { + _this.minimap.topleft = paper.view.bounds.bottomRight.subtract(_this.minimap.size) + _this.minimap.rectangle.fitBounds(_this.minimap.topleft.subtract([2,2]), _this.minimap.size.add([4,4])); + _this.minimap.cliprectangle.fitBounds(_this.minimap.topleft, _this.minimap.size); + } + _this.redraw(); + } + + var _thRedraw = Rkns._.throttle(function() { + _this.redraw(); + },50); + + this.addRepresentations("Node", this.renkan.project.get("nodes")); + this.addRepresentations("Edge", this.renkan.project.get("edges")); + this.renkan.project.on("change:title", function() { + _this.$.find(".Rk-PadTitle").val(_renkan.project.get("title")); + }); + + this.$.find(".Rk-PadTitle").on("keyup input paste", function() { + _renkan.project.set({"title": $(this).val()}); + }) + + this.renkan.project.get("users").each(function(_user) { + _this.addUser(_user); + }); + + this.renkan.project.on("add:users", function(_user) { + _this.addUser(_user); + }); + this.renkan.project.on("add:nodes", function(_node) { + _this.addRepresentation("Node", _node); + _thRedraw(); + }); + this.renkan.project.on("add:edges", function(_edge) { + _this.addRepresentation("Edge", _edge); + _thRedraw(); + }); + this.renkan.project.on("change:title", function(_model, _title) { + var el = $(".Rk-PadTitle"); + if (el.is("input")) { + if (el.val() !== _title) { + el.val(_title); + } + } else { + el.text(_title); + } + }); + + this.redraw(); + + if (this.minimap) { + window.setInterval(function() { + _this.rescaleMinimap() + }, 2000); + } +} + +Rkns.Renderer.Scene.prototype.template = Rkns._.template( + '<% if (options.show_top_bar) { %>
        <% if (!options.editor_mode) { %>

        <%- project.get("title") || translate("Untitled project")%>

        ' + + '<% } else { %>" placeholder="<%-translate("Untitled project")%>" /><% } %>' + + '
        <unknown user>
          ' + + '
          <%-translate("Full Screen")%>
          ' + + '<% if (options.editor_mode) { %>' + + '
          <%-translate("Add Node")%>
          ' + + '
          <%-translate("Add Edge")%>
          ' + + '
          ' + + '
          ' + + '<%-translate("Renkan \'Drag-to-Add\' bookmarklet")%>
          ' + + '
          ' + + '<% } } %>' + + '
          ' + + '<% if (options.show_bins) { %>
          «
          <% } %>' + + '
          ">
          ">
          ' + + '
          ' +); + +Rkns.Renderer.Scene.prototype.addToBundles = function(_edgeRepr) { + var _bundle = Rkns._(this.bundles).find(function(_bundle) { + return ( + ( _bundle.from === _edgeRepr.from_representation && _bundle.to === _edgeRepr.to_representation ) + || ( _bundle.from === _edgeRepr.to_representation && _bundle.to === _edgeRepr.from_representation ) + ); + }); + if (typeof _bundle !== "undefined") { + _bundle.edges.push(_edgeRepr) + } else { + _bundle = { + from: _edgeRepr.from_representation, + to: _edgeRepr.to_representation, + edges: [ _edgeRepr ], + getPosition: function(_er) { + var _dir = (_er.from_representation === this.from) ? 1 : -1; + return _dir * ( Rkns._(this.edges).indexOf(_er) - (this.edges.length - 1) / 2 ); + } + } + this.bundles.push(_bundle); + } + return _bundle; +} + +Rkns.Renderer.Scene.prototype.isEditable = function() { + return (this.renkan.options.editor_mode && !this.renkan.read_only) +} + +Rkns.Renderer.Scene.prototype.onStatusChange = function() { + var savebtn = this.$.find(".Rk-Save-Button"), + tip = savebtn.find(".Rk-TopBar-Tooltip-Contents"); + if (this.renkan.read_only) { + savebtn.removeClass("disabled Rk-Save-Online").addClass("Rk-Save-ReadOnly"); + tip.text(this.renkan.translate("Connection lost")); + } else { + if (this.renkan.options.snapshot_mode) { + savebtn.removeClass("Rk-Save-ReadOnly Rk-Save-Online"); + tip.text(this.renkan.translate("Archive Project")); + } else { + savebtn.removeClass("disabled Rk-Save-ReadOnly").addClass("Rk-Save-Online"); + tip.text(this.renkan.translate("Auto-save enabled")); + } + } +} + +Rkns.Renderer.Scene.prototype.setScale = function(_newScale, _offset) { + if (_newScale > Rkns.Renderer._MIN_SCALE && _newScale < Rkns.Renderer._MAX_SCALE) { + this.scale = _newScale; + if (_offset) { + this.offset = _offset + } + this.redraw(); + } +} + +Rkns.Renderer.Scene.prototype.autoScale = function() { + var nodes = this.renkan.project.get("nodes") + if (nodes.length > 1) { + var _xx = nodes.map(function(_node) { return _node.get("position").x }), + _yy = nodes.map(function(_node) { return _node.get("position").y }), + _minx = Math.min.apply(Math, _xx), + _miny = Math.min.apply(Math, _yy), + _maxx = Math.max.apply(Math, _xx), + _maxy = Math.max.apply(Math, _yy); + var _scale = Math.max(Rkns.Renderer._MIN_SCALE, Math.min(Rkns.Renderer._MAX_SCALE, (paper.view.size.width - 2 * Rkns.Renderer._AUTOSCALE_MARGIN) / (_maxx - _minx), (paper.view.size.height - 2 * Rkns.Renderer._AUTOSCALE_MARGIN) / (_maxy - _miny))); + this.setScale(_scale, paper.view.center.subtract(new paper.Point([(_maxx + _minx) / 2, (_maxy + _miny) / 2]).multiply(_scale))); + } + if (nodes.length === 1) { + this.setScale(1, paper.view.center.subtract(new paper.Point([nodes.at(0).get("position").x, nodes.at(0).get("position").y]))); + } +} + +Rkns.Renderer.Scene.prototype.redrawMiniframe = function() { + var topleft = this.toMinimapCoords(this.toModelCoords(new paper.Point([0,0]))), + bottomright = this.toMinimapCoords(this.toModelCoords(paper.view.bounds.bottomRight)); + this.minimap.miniframe.fitBounds(topleft, bottomright); +} + +Rkns.Renderer.Scene.prototype.rescaleMinimap = function() { + var nodes = this.renkan.project.get("nodes") + if (nodes.length > 1) { + var _xx = nodes.map(function(_node) { return _node.get("position").x }), + _yy = nodes.map(function(_node) { return _node.get("position").y }), + _minx = Math.min.apply(Math, _xx), + _miny = Math.min.apply(Math, _yy), + _maxx = Math.max.apply(Math, _xx), + _maxy = Math.max.apply(Math, _yy); + var _scale = Math.min( + this.scale * .8 * this.renkan.options.minimap_width / paper.view.bounds.width, + this.scale * .8 * this.renkan.options.minimap_height / paper.view.bounds.height, + ( this.renkan.options.minimap_width - 2 * Rkns.Renderer._MINIMAP_MARGIN ) / (_maxx - _minx), + ( this.renkan.options.minimap_height - 2 * Rkns.Renderer._MINIMAP_MARGIN ) / (_maxy - _miny) + ); + this.minimap.offset = this.minimap.size.divide(2).subtract(new paper.Point([(_maxx + _minx) / 2, (_maxy + _miny) / 2]).multiply(_scale)); + this.minimap.scale = _scale; + } + if (nodes.length === 1) { + this.minimap.scale = .1; + this.minimap.offset = this.minimap.size.divide(2).subtract(new paper.Point([nodes.at(0).get("position").x, nodes.at(0).get("position").y]).multiply(this.minimap.scale)); + } + this.redraw(); +} + +Rkns.Renderer.Scene.prototype.toPaperCoords = function(_point) { + return _point.multiply(this.scale).add(this.offset); +} + +Rkns.Renderer.Scene.prototype.toMinimapCoords = function(_point) { + return _point.multiply(this.minimap.scale).add(this.minimap.offset).add(this.minimap.topleft); +} + +Rkns.Renderer.Scene.prototype.toModelCoords = function(_point) { + return _point.subtract(this.offset).divide(this.scale); +} + +Rkns.Renderer.Scene.prototype.addRepresentation = function(_type, _model) { + var _repr = new Rkns.Renderer[_type](this, _model); + this.representations.push(_repr); + return _repr; +} + +Rkns.Renderer.Scene.prototype.addRepresentations = function(_type, _collection) { + var _this = this; + _collection.forEach(function(_model) { + _this.addRepresentation(_type, _model); + }); +} + +Rkns.Renderer.Scene.prototype.userTemplate = Rkns._.template( + '
        • <%=name%>
        • ' +); + +Rkns.Renderer.Scene.prototype.addUser = function(_user) { + if (_user.get("_id") === this.renkan.current_user) { + this.$.find(".Rk-CurrentUser-Name").text(_user.get("title")); + this.$.find(".Rk-CurrentUser-Color").css("background", _user.get("color")); + } else { + this.$.find(".Rk-UserList").append( + Rkns.$( + this.userTemplate({ + name: _user.get("title"), + background: _user.get("color") + }) + ) + ); + } +} + +Rkns.Renderer.Scene.prototype.removeRepresentation = function(_representation) { + _representation.destroy(); + this.representations = Rkns._(this.representations).reject( + function(_repr) { + return _repr == _representation + } + ); +} + +Rkns.Renderer.Scene.prototype.getRepresentationByModel = function(_model) { + return Rkns._(this.representations).find(function(_repr) { + return _repr.model === _model; + }); +} + +Rkns.Renderer.Scene.prototype.removeRepresentationsOfType = function(_type) { + var _representations = Rkns._(this.representations).filter(function(_repr) { + return _repr.type == _type; + }), + _this = this; + Rkns._(_representations).each(function(_repr) { + _this.removeRepresentation(_repr); + }); +} + +Rkns.Renderer.Scene.prototype.highlightModel = function(_model) { + var _repr = this.getRepresentationByModel(_model); + if (_repr) { + _repr.highlight(); + } +} + +Rkns.Renderer.Scene.prototype.unhighlightAll = function(_model) { + Rkns._(this.representations).each(function(_repr) { + _repr.unhighlight(); + }); +} + +Rkns.Renderer.Scene.prototype.redraw = function() { + Rkns._(this.representations).each(function(_representation) { + _representation.redraw(true); + }); + if (this.minimap) { + this.redrawMiniframe(); + } + paper.view.draw(); +} + +Rkns.Renderer.Scene.prototype.addTempEdge = function(_from, _point) { + var _tmpEdge = this.addRepresentation("TempEdge",null); + _tmpEdge.end_pos = _point; + _tmpEdge.from_representation = _from; + _tmpEdge.redraw(); + this.click_target = _tmpEdge; +} + +Rkns.Renderer.Scene.prototype.findTarget = function(_hitResult) { + if (_hitResult && typeof _hitResult.item.__representation !== "undefined") { + var _newTarget = _hitResult.item.__representation; + if (this.selected_target !== _hitResult.item.__representation) { + if (this.selected_target) { + this.selected_target.unselect(_newTarget); + } + _newTarget.select(this.selected_target); + this.selected_target = _newTarget; + } + } else { + if (this.selected_target) { + this.selected_target.unselect(null); + } + this.selected_target = null; + } +} + +Rkns.Renderer.Scene.prototype.paperShift = function(_delta) { + this.offset = this.offset.add(_delta); + this.redraw(); +} + +Rkns.Renderer.Scene.prototype.onMouseMove = function(_event) { + var _hitResult = paper.project.hitTest(_event.point); + if (this.is_dragging) { + if (this.click_target && typeof this.click_target.paperShift === "function") { + this.click_target.paperShift(_event.delta); + } else { + this.paperShift(_event.delta); + } + } else { + this.findTarget(_hitResult); + } +} + +Rkns.Renderer.Scene.prototype.onMouseDown = function(_event) { + if (!this.click_target || this.click_target.type !== "temp-edge") { + this.removeRepresentationsOfType("editor"); + this.is_dragging = false; + var _hitResult = paper.project.hitTest(_event.point); + if (this.isEditable() && _hitResult && typeof _hitResult.item.__representation !== "undefined") { + this.click_target = _hitResult.item.__representation; + if (this.click_target.type === "Node-link-button") { + this.removeRepresentationsOfType("editor"); + this.addTempEdge(this.click_target.node_representation, _event.point); + } + } else { + this.click_target = null; + if (this.isEditable() && this.click_mode === Rkns.Renderer._CLICKMODE_ADDNODE) { + var _coords = this.toModelCoords(_event.point), + _data = { + id: Rkns.Utils.getUID('node'), + created_by: this.renkan.current_user, + position: { + x: _coords.x, + y: _coords.y + } + }; + _node = this.renkan.project.addNode(_data); + this.getRepresentationByModel(_node).openEditor(); + } + } + } + if (this.click_mode) { + if (this.isEditable() && this.click_mode === Rkns.Renderer._CLICKMODE_STARTEDGE && this.click_target && this.click_target.type === "Node") { + this.removeRepresentationsOfType("editor"); + this.addTempEdge(this.click_target, _event.point); + this.click_mode = Rkns.Renderer._CLICKMODE_ENDEDGE; + this.notif_$.fadeOut(function() { + Rkns.$(this).html(_renkan.translate("Click on a second node to complete the edge")).fadeIn(); + }); + } else { + this.notif_$.hide(); + this.click_mode = false; + } + } +} + +Rkns.Renderer.Scene.prototype.onMouseDrag = function(_event) { + this.is_dragging = true; + this.onMouseMove(_event); +} + +Rkns.Renderer.Scene.prototype.onMouseUp = function(_event) { + if (this.click_target) { + var _off = this.canvas_$.offset(); + this.click_target.mouseup( + { + point: new paper.Point([ + _event.pageX - _off.left, + _event.pageY - _off.top + ]) + } + ); + } else { + this.click_target = null; + this.is_dragging = false; + } +} + +Rkns.Renderer.Scene.prototype.onScroll = function(_event, _scrolldelta) { + this.totalScroll += _scrolldelta; + if (Math.abs(this.totalScroll) >= 1) { + var _off = this.canvas_$.offset(), + _delta = new paper.Point([ + _event.pageX - _off.left, + _event.pageY - _off.top + ]).subtract(this.offset).multiply( Math.SQRT2 - 1 ); + if (this.totalScroll > 0) { + this.setScale( this.scale * Math.SQRT2, this.offset.subtract(_delta) ); + } else { + this.setScale( this.scale * Math.SQRT1_2, this.offset.add(_delta.divide(Math.SQRT2))); + } + this.totalScroll = 0; + } +} + +Rkns.Renderer.Scene.prototype.onDoubleClick = function(_event) { + if (!this.isEditable()) { + return; + } + var _off = this.canvas_$.offset(), + _point = new paper.Point([ + _event.pageX - _off.left, + _event.pageY - _off.top + ]); + var _hitResult = paper.project.hitTest(_point); + if (this.isEditable() && (!_hitResult || typeof _hitResult.item.__representation === "undefined")) { + var _coords = this.toModelCoords(_point), + _data = { + id: Rkns.Utils.getUID('node'), + created_by: this.renkan.current_user, + position: { + x: _coords.x, + y: _coords.y + } + }; + _node = this.renkan.project.addNode(_data); + this.getRepresentationByModel(_node).openEditor(); + } + paper.view.draw(); +} diff -r 4aec3f00ea87 -r 1fa074d64662 integ/renkan/lib/backbone-relational.js --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/integ/renkan/lib/backbone-relational.js Wed Apr 03 18:56:34 2013 +0200 @@ -0,0 +1,1687 @@ +/** + * Backbone-relational.js 0.6.0 + * (c) 2011 Paul Uithol + * + * Backbone-relational may be freely distributed under the MIT license; see the accompanying LICENSE.txt. + * For details and documentation: https://github.com/PaulUithol/Backbone-relational. + * Depends on Backbone (and thus on Underscore as well): https://github.com/documentcloud/backbone. + */ +( function( undefined ) { + "use strict"; + + /** + * CommonJS shim + **/ + var _, Backbone, exports; + if ( typeof window === 'undefined' ) { + _ = require( 'underscore' ); + Backbone = require( 'backbone' ); + exports = module.exports = Backbone; + } + else { + _ = window._; + Backbone = window.Backbone; + exports = window; + } + + Backbone.Relational = { + showWarnings: true + }; + + /** + * Semaphore mixin; can be used as both binary and counting. + **/ + Backbone.Semaphore = { + _permitsAvailable: null, + _permitsUsed: 0, + + acquire: function() { + if ( this._permitsAvailable && this._permitsUsed >= this._permitsAvailable ) { + throw new Error( 'Max permits acquired' ); + } + else { + this._permitsUsed++; + } + }, + + release: function() { + if ( this._permitsUsed === 0 ) { + throw new Error( 'All permits released' ); + } + else { + this._permitsUsed--; + } + }, + + isLocked: function() { + return this._permitsUsed > 0; + }, + + setAvailablePermits: function( amount ) { + if ( this._permitsUsed > amount ) { + throw new Error( 'Available permits cannot be less than used permits' ); + } + this._permitsAvailable = amount; + } + }; + + /** + * A BlockingQueue that accumulates items while blocked (via 'block'), + * and processes them when unblocked (via 'unblock'). + * Process can also be called manually (via 'process'). + */ + Backbone.BlockingQueue = function() { + this._queue = []; + }; + _.extend( Backbone.BlockingQueue.prototype, Backbone.Semaphore, { + _queue: null, + + add: function( func ) { + if ( this.isBlocked() ) { + this._queue.push( func ); + } + else { + func(); + } + }, + + process: function() { + while ( this._queue && this._queue.length ) { + this._queue.shift()(); + } + }, + + block: function() { + this.acquire(); + }, + + unblock: function() { + this.release(); + if ( !this.isBlocked() ) { + this.process(); + } + }, + + isBlocked: function() { + return this.isLocked(); + } + }); + /** + * Global event queue. Accumulates external events ('add:', 'remove:' and 'update:') + * until the top-level object is fully initialized (see 'Backbone.RelationalModel'). + */ + Backbone.Relational.eventQueue = new Backbone.BlockingQueue(); + + /** + * Backbone.Store keeps track of all created (and destruction of) Backbone.RelationalModel. + * Handles lookup for relations. + */ + Backbone.Store = function() { + this._collections = []; + this._reverseRelations = []; + this._subModels = []; + this._modelScopes = [ exports ]; + }; + _.extend( Backbone.Store.prototype, Backbone.Events, { + addModelScope: function( scope ) { + this._modelScopes.push( scope ); + }, + + /** + * Add a set of subModelTypes to the store, that can be used to resolve the '_superModel' + * for a model later in 'setupSuperModel'. + * + * @param {Backbone.RelationalModel} subModelTypes + * @param {Backbone.RelationalModel} superModelType + */ + addSubModels: function( subModelTypes, superModelType ) { + this._subModels.push({ + 'superModelType': superModelType, + 'subModels': subModelTypes + }); + }, + + /** + * Check if the given modelType is registered as another model's subModel. If so, add it to the super model's + * '_subModels', and set the modelType's '_superModel', '_subModelTypeName', and '_subModelTypeAttribute'. + * + * @param {Backbone.RelationalModel} modelType + */ + setupSuperModel: function( modelType ) { + _.find( this._subModels, function( subModelDef ) { + return _.find( subModelDef.subModels, function( subModelTypeName, typeValue ) { + var subModelType = this.getObjectByName( subModelTypeName ); + + if ( modelType === subModelType ) { + // Set 'modelType' as a child of the found superModel + subModelDef.superModelType._subModels[ typeValue ] = modelType; + + // Set '_superModel', '_subModelTypeValue', and '_subModelTypeAttribute' on 'modelType'. + modelType._superModel = subModelDef.superModelType; + modelType._subModelTypeValue = typeValue; + modelType._subModelTypeAttribute = subModelDef.superModelType.prototype.subModelTypeAttribute; + return true; + } + }, this ); + }, this ); + }, + + /** + * Add a reverse relation. Is added to the 'relations' property on model's prototype, and to + * existing instances of 'model' in the store as well. + * @param {Object} relation + * @param {Backbone.RelationalModel} relation.model + * @param {String} relation.type + * @param {String} relation.key + * @param {String|Object} relation.relatedModel + */ + addReverseRelation: function( relation ) { + var exists = _.any( this._reverseRelations, function( rel ) { + return _.all( relation, function( val, key ) { + return val === rel[ key ]; + }); + }); + + if ( !exists && relation.model && relation.type ) { + this._reverseRelations.push( relation ); + + var addRelation = function( model, relation ) { + if ( !model.prototype.relations ) { + model.prototype.relations = []; + } + model.prototype.relations.push( relation ); + + _.each( model._subModels, function( subModel ) { + addRelation( subModel, relation ); + }, this ); + }; + + addRelation( relation.model, relation ); + + this.retroFitRelation( relation ); + } + }, + + /** + * Add a 'relation' to all existing instances of 'relation.model' in the store + * @param {Object} relation + */ + retroFitRelation: function( relation ) { + var coll = this.getCollection( relation.model ); + coll.each( function( model ) { + if ( !( model instanceof relation.model ) ) { + return; + } + + new relation.type( model, relation ); + }, this); + }, + + /** + * Find the Store's collection for a certain type of model. + * @param {Backbone.RelationalModel} model + * @return {Backbone.Collection} A collection if found (or applicable for 'model'), or null + */ + getCollection: function( model ) { + if ( model instanceof Backbone.RelationalModel ) { + model = model.constructor; + } + + var rootModel = model; + while ( rootModel._superModel ) { + rootModel = rootModel._superModel; + } + + var coll = _.detect( this._collections, function( c ) { + return c.model === rootModel; + }); + + if ( !coll ) { + coll = this._createCollection( rootModel ); + } + + return coll; + }, + + /** + * Find a type on the global object by name. Splits name on dots. + * @param {String} name + * @return {Object} + */ + getObjectByName: function( name ) { + var parts = name.split( '.' ), + type = null; + + _.find( this._modelScopes, function( scope ) { + type = _.reduce( parts, function( memo, val ) { + return memo[ val ]; + }, scope ); + + if ( type && type !== scope ) { + return true; + } + }, this ); + + return type; + }, + + _createCollection: function( type ) { + var coll; + + // If 'type' is an instance, take its constructor + if ( type instanceof Backbone.RelationalModel ) { + type = type.constructor; + } + + // Type should inherit from Backbone.RelationalModel. + if ( type.prototype instanceof Backbone.RelationalModel ) { + coll = new Backbone.Collection(); + coll.model = type; + + this._collections.push( coll ); + } + + return coll; + }, + + /** + * Find the attribute that is to be used as the `id` on a given object + * @param type + * @param {String|Number|Object|Backbone.RelationalModel} item + * @return {String|Number} + */ + resolveIdForItem: function( type, item ) { + var id = _.isString( item ) || _.isNumber( item ) ? item : null; + + if ( id === null ) { + if ( item instanceof Backbone.RelationalModel ) { + id = item.id; + } + else if ( _.isObject( item ) ) { + id = item[ type.prototype.idAttribute ]; + } + } + + // Make all falsy values `null` (except for 0, which could be an id.. see '/issues/179') + if ( !id && id !== 0 ) { + id = null; + } + + return id; + }, + + /** + * + * @param type + * @param {String|Number|Object|Backbone.RelationalModel} item + */ + find: function( type, item ) { + var id = this.resolveIdForItem( type, item ); + var coll = this.getCollection( type ); + + // Because the found object could be of any of the type's superModel + // types, only return it if it's actually of the type asked for. + if ( coll ) { + var obj = coll.get( id ); + + if ( obj instanceof type ) { + return obj; + } + } + + return null; + }, + + /** + * Add a 'model' to it's appropriate collection. Retain the original contents of 'model.collection'. + * @param {Backbone.RelationalModel} model + */ + register: function( model ) { + var coll = this.getCollection( model ); + + if ( coll ) { + if ( coll.get( model ) ) { + throw new Error( "Cannot instantiate more than one Backbone.RelationalModel with the same id per type!" ); + } + + var modelColl = model.collection; + coll.add( model ); + model.bind( 'destroy', this.unregister, this ); + model.collection = modelColl; + } + }, + + /** + * Explicitly update a model's id in it's store collection + * @param {Backbone.RelationalModel} model + */ + update: function( model ) { + var coll = this.getCollection( model ); + coll._onModelEvent( 'change:' + model.idAttribute, model, coll ); + }, + + /** + * Remove a 'model' from the store. + * @param {Backbone.RelationalModel} model + */ + unregister: function( model ) { + model.unbind( 'destroy', this.unregister ); + var coll = this.getCollection( model ); + coll && coll.remove( model ); + } + }); + Backbone.Relational.store = new Backbone.Store(); + + /** + * The main Relation class, from which 'HasOne' and 'HasMany' inherit. Internally, 'relational:' events + * are used to regulate addition and removal of models from relations. + * + * @param {Backbone.RelationalModel} instance + * @param {Object} options + * @param {string} options.key + * @param {Backbone.RelationalModel.constructor} options.relatedModel + * @param {Boolean|String} [options.includeInJSON=true] Serialize the given attribute for related model(s)' in toJSON, or just their ids. + * @param {Boolean} [options.createModels=true] Create objects from the contents of keys if the object is not found in Backbone.store. + * @param {Object} [options.reverseRelation] Specify a bi-directional relation. If provided, Relation will reciprocate + * the relation to the 'relatedModel'. Required and optional properties match 'options', except that it also needs + * {Backbone.Relation|String} type ('HasOne' or 'HasMany'). + */ + Backbone.Relation = function( instance, options ) { + this.instance = instance; + // Make sure 'options' is sane, and fill with defaults from subclasses and this object's prototype + options = _.isObject( options ) ? options : {}; + this.reverseRelation = _.defaults( options.reverseRelation || {}, this.options.reverseRelation ); + this.reverseRelation.type = !_.isString( this.reverseRelation.type ) ? this.reverseRelation.type : + Backbone[ this.reverseRelation.type ] || Backbone.Relational.store.getObjectByName( this.reverseRelation.type ); + this.model = options.model || this.instance.constructor; + this.options = _.defaults( options, this.options, Backbone.Relation.prototype.options ); + + this.key = this.options.key; + this.keySource = this.options.keySource || this.key; + this.keyDestination = this.options.keyDestination || this.keySource || this.key; + + // 'exports' should be the global object where 'relatedModel' can be found on if given as a string. + this.relatedModel = this.options.relatedModel; + if ( _.isString( this.relatedModel ) ) { + this.relatedModel = Backbone.Relational.store.getObjectByName( this.relatedModel ); + } + + if ( !this.checkPreconditions() ) { + return false; + } + + if ( instance ) { + this.keyContents = this.instance.get( this.keySource ); + + // Explicitly clear 'keySource', to prevent a leaky abstraction if 'keySource' differs from 'key'. + if ( this.key !== this.keySource ) { + this.instance.unset( this.keySource, { silent: true } ); + } + + // Add this Relation to instance._relations + this.instance._relations.push( this ); + } + + // Add the reverse relation on 'relatedModel' to the store's reverseRelations + if ( !this.options.isAutoRelation && this.reverseRelation.type && this.reverseRelation.key ) { + Backbone.Relational.store.addReverseRelation( _.defaults( { + isAutoRelation: true, + model: this.relatedModel, + relatedModel: this.model, + reverseRelation: this.options // current relation is the 'reverseRelation' for it's own reverseRelation + }, + this.reverseRelation // Take further properties from this.reverseRelation (type, key, etc.) + ) ); + } + + _.bindAll( this, '_modelRemovedFromCollection', '_relatedModelAdded', '_relatedModelRemoved' ); + + if ( instance ) { + this.initialize(); + + // When a model in the store is destroyed, check if it is 'this.instance'. + Backbone.Relational.store.getCollection( this.instance ) + .bind( 'relational:remove', this._modelRemovedFromCollection ); + + // When 'relatedModel' are created or destroyed, check if it affects this relation. + Backbone.Relational.store.getCollection( this.relatedModel ) + .bind( 'relational:add', this._relatedModelAdded ) + .bind( 'relational:remove', this._relatedModelRemoved ); + } + }; + // Fix inheritance :\ + Backbone.Relation.extend = Backbone.Model.extend; + // Set up all inheritable **Backbone.Relation** properties and methods. + _.extend( Backbone.Relation.prototype, Backbone.Events, Backbone.Semaphore, { + options: { + createModels: true, + includeInJSON: true, + isAutoRelation: false + }, + + instance: null, + key: null, + keyContents: null, + relatedModel: null, + reverseRelation: null, + related: null, + + _relatedModelAdded: function( model, coll, options ) { + // Allow 'model' to set up it's relations, before calling 'tryAddRelated' + // (which can result in a call to 'addRelated' on a relation of 'model') + var dit = this; + model.queue( function() { + dit.tryAddRelated( model, options ); + }); + }, + + _relatedModelRemoved: function( model, coll, options ) { + this.removeRelated( model, options ); + }, + + _modelRemovedFromCollection: function( model ) { + if ( model === this.instance ) { + this.destroy(); + } + }, + + /** + * Check several pre-conditions. + * @return {Boolean} True if pre-conditions are satisfied, false if they're not. + */ + checkPreconditions: function() { + var i = this.instance, + k = this.key, + m = this.model, + rm = this.relatedModel, + warn = Backbone.Relational.showWarnings && typeof console !== 'undefined'; + + if ( !m || !k || !rm ) { + warn && console.warn( 'Relation=%o; no model, key or relatedModel (%o, %o, %o)', this, m, k, rm ); + return false; + } + // Check if the type in 'model' inherits from Backbone.RelationalModel + if ( !( m.prototype instanceof Backbone.RelationalModel ) ) { + warn && console.warn( 'Relation=%o; model does not inherit from Backbone.RelationalModel (%o)', this, i ); + return false; + } + // Check if the type in 'relatedModel' inherits from Backbone.RelationalModel + if ( !( rm.prototype instanceof Backbone.RelationalModel ) ) { + warn && console.warn( 'Relation=%o; relatedModel does not inherit from Backbone.RelationalModel (%o)', this, rm ); + return false; + } + // Check if this is not a HasMany, and the reverse relation is HasMany as well + if ( this instanceof Backbone.HasMany && this.reverseRelation.type === Backbone.HasMany ) { + warn && console.warn( 'Relation=%o; relation is a HasMany, and the reverseRelation is HasMany as well.', this ); + return false; + } + + // Check if we're not attempting to create a duplicate relationship + if ( i && i._relations.length ) { + var exists = _.any( i._relations, function( rel ) { + var hasReverseRelation = this.reverseRelation.key && rel.reverseRelation.key; + return rel.relatedModel === rm && rel.key === k && + ( !hasReverseRelation || this.reverseRelation.key === rel.reverseRelation.key ); + }, this ); + + if ( exists ) { + warn && console.warn( 'Relation=%o between instance=%o.%s and relatedModel=%o.%s already exists', + this, i, k, rm, this.reverseRelation.key ); + return false; + } + } + + return true; + }, + + /** + * Set the related model(s) for this relation + * @param {Backbone.Mode|Backbone.Collection} related + * @param {Object} [options] + */ + setRelated: function( related, options ) { + this.related = related; + + this.instance.acquire(); + this.instance.set( this.key, related, _.defaults( options || {}, { silent: true } ) ); + this.instance.release(); + }, + + /** + * Determine if a relation (on a different RelationalModel) is the reverse + * relation of the current one. + * @param {Backbone.Relation} relation + * @return {Boolean} + */ + _isReverseRelation: function( relation ) { + if ( relation.instance instanceof this.relatedModel && this.reverseRelation.key === relation.key && + this.key === relation.reverseRelation.key ) { + return true; + } + return false; + }, + + /** + * Get the reverse relations (pointing back to 'this.key' on 'this.instance') for the currently related model(s). + * @param {Backbone.RelationalModel} [model] Get the reverse relations for a specific model. + * If not specified, 'this.related' is used. + * @return {Backbone.Relation[]} + */ + getReverseRelations: function( model ) { + var reverseRelations = []; + // Iterate over 'model', 'this.related.models' (if this.related is a Backbone.Collection), or wrap 'this.related' in an array. + var models = !_.isUndefined( model ) ? [ model ] : this.related && ( this.related.models || [ this.related ] ); + _.each( models , function( related ) { + _.each( related.getRelations(), function( relation ) { + if ( this._isReverseRelation( relation ) ) { + reverseRelations.push( relation ); + } + }, this ); + }, this ); + + return reverseRelations; + }, + + /** + * Rename options.silent to options.silentChange, so events propagate properly. + * (for example in HasMany, from 'addRelated'->'handleAddition') + * @param {Object} [options] + * @return {Object} + */ + sanitizeOptions: function( options ) { + options = options ? _.clone( options ) : {}; + if ( options.silent ) { + options.silentChange = true; + delete options.silent; + } + return options; + }, + + /** + * Rename options.silentChange to options.silent, so events are silenced as intended in Backbone's + * original functions. + * @param {Object} [options] + * @return {Object} + */ + unsanitizeOptions: function( options ) { + options = options ? _.clone( options ) : {}; + if ( options.silentChange ) { + options.silent = true; + delete options.silentChange; + } + return options; + }, + + // Cleanup. Get reverse relation, call removeRelated on each. + destroy: function() { + Backbone.Relational.store.getCollection( this.instance ) + .unbind( 'relational:remove', this._modelRemovedFromCollection ); + + Backbone.Relational.store.getCollection( this.relatedModel ) + .unbind( 'relational:add', this._relatedModelAdded ) + .unbind( 'relational:remove', this._relatedModelRemoved ); + + _.each( this.getReverseRelations(), function( relation ) { + relation.removeRelated( this.instance ); + }, this ); + } + }); + + Backbone.HasOne = Backbone.Relation.extend({ + options: { + reverseRelation: { type: 'HasMany' } + }, + + initialize: function() { + _.bindAll( this, 'onChange' ); + + this.instance.bind( 'relational:change:' + this.key, this.onChange ); + + var model = this.findRelated( { silent: true } ); + this.setRelated( model ); + + // Notify new 'related' object of the new relation. + _.each( this.getReverseRelations(), function( relation ) { + relation.addRelated( this.instance ); + }, this ); + }, + + findRelated: function( options ) { + var item = this.keyContents; + var model = null; + + if ( item instanceof this.relatedModel ) { + model = item; + } + else if ( item || item === 0 ) { // since 0 can be a valid `id` as well + model = this.relatedModel.findOrCreate( item, { create: this.options.createModels } ); + } + + return model; + }, + + /** + * If the key is changed, notify old & new reverse relations and initialize the new relation + */ + onChange: function( model, attr, options ) { + // Don't accept recursive calls to onChange (like onChange->findRelated->findOrCreate->initializeRelations->addRelated->onChange) + if ( this.isLocked() ) { + return; + } + this.acquire(); + options = this.sanitizeOptions( options ); + + // 'options._related' is set by 'addRelated'/'removeRelated'. If it is set, the change + // is the result of a call from a relation. If it's not, the change is the result of + // a 'set' call on this.instance. + var changed = _.isUndefined( options._related ); + var oldRelated = changed ? this.related : options._related; + + if ( changed ) { + this.keyContents = attr; + + // Set new 'related' + if ( attr instanceof this.relatedModel ) { + this.related = attr; + } + else if ( attr ) { + var related = this.findRelated( options ); + this.setRelated( related ); + } + else { + this.setRelated( null ); + } + } + + // Notify old 'related' object of the terminated relation + if ( oldRelated && this.related !== oldRelated ) { + _.each( this.getReverseRelations( oldRelated ), function( relation ) { + relation.removeRelated( this.instance, options ); + }, this ); + } + + // Notify new 'related' object of the new relation. Note we do re-apply even if this.related is oldRelated; + // that can be necessary for bi-directional relations if 'this.instance' was created after 'this.related'. + // In that case, 'this.instance' will already know 'this.related', but the reverse might not exist yet. + _.each( this.getReverseRelations(), function( relation ) { + relation.addRelated( this.instance, options ); + }, this); + + // Fire the 'update:' event if 'related' was updated + if ( !options.silentChange && this.related !== oldRelated ) { + var dit = this; + Backbone.Relational.eventQueue.add( function() { + dit.instance.trigger( 'update:' + dit.key, dit.instance, dit.related, options ); + }); + } + this.release(); + }, + + /** + * If a new 'this.relatedModel' appears in the 'store', try to match it to the last set 'keyContents' + */ + tryAddRelated: function( model, options ) { + if ( this.related ) { + return; + } + options = this.sanitizeOptions( options ); + + var item = this.keyContents; + if ( item || item === 0 ) { // since 0 can be a valid `id` as well + var id = Backbone.Relational.store.resolveIdForItem( this.relatedModel, item ); + if ( !_.isNull( id ) && model.id === id ) { + this.addRelated( model, options ); + } + } + }, + + addRelated: function( model, options ) { + if ( model !== this.related ) { + var oldRelated = this.related || null; + this.setRelated( model ); + this.onChange( this.instance, model, { _related: oldRelated } ); + } + }, + + removeRelated: function( model, options ) { + if ( !this.related ) { + return; + } + + if ( model === this.related ) { + var oldRelated = this.related || null; + this.setRelated( null ); + this.onChange( this.instance, model, { _related: oldRelated } ); + } + } + }); + + Backbone.HasMany = Backbone.Relation.extend({ + collectionType: null, + + options: { + reverseRelation: { type: 'HasOne' }, + collectionType: Backbone.Collection, + collectionKey: true, + collectionOptions: {} + }, + + initialize: function() { + _.bindAll( this, 'onChange', 'handleAddition', 'handleRemoval', 'handleReset' ); + this.instance.bind( 'relational:change:' + this.key, this.onChange ); + + // Handle a custom 'collectionType' + this.collectionType = this.options.collectionType; + if ( _.isString( this.collectionType ) ) { + this.collectionType = Backbone.Relational.store.getObjectByName( this.collectionType ); + } + if ( !this.collectionType.prototype instanceof Backbone.Collection ){ + throw new Error( 'collectionType must inherit from Backbone.Collection' ); + } + + // Handle cases where a model/relation is created with a collection passed straight into 'attributes' + if ( this.keyContents instanceof Backbone.Collection ) { + this.setRelated( this._prepareCollection( this.keyContents ) ); + } + else { + this.setRelated( this._prepareCollection() ); + } + + this.findRelated( { silent: true } ); + }, + + _getCollectionOptions: function() { + return _.isFunction( this.options.collectionOptions ) ? + this.options.collectionOptions( this.instance ) : + this.options.collectionOptions; + }, + + /** + * Bind events and setup collectionKeys for a collection that is to be used as the backing store for a HasMany. + * If no 'collection' is supplied, a new collection will be created of the specified 'collectionType' option. + * @param {Backbone.Collection} [collection] + */ + _prepareCollection: function( collection ) { + if ( this.related ) { + this.related + .unbind( 'relational:add', this.handleAddition ) + .unbind( 'relational:remove', this.handleRemoval ) + .unbind( 'relational:reset', this.handleReset ) + } + + if ( !collection || !( collection instanceof Backbone.Collection ) ) { + collection = new this.collectionType( [], this._getCollectionOptions() ); + } + + collection.model = this.relatedModel; + + if ( this.options.collectionKey ) { + var key = this.options.collectionKey === true ? this.options.reverseRelation.key : this.options.collectionKey; + + if ( collection[ key ] && collection[ key ] !== this.instance ) { + if ( Backbone.Relational.showWarnings && typeof console !== 'undefined' ) { + console.warn( 'Relation=%o; collectionKey=%s already exists on collection=%o', this, key, this.options.collectionKey ); + } + } + else if ( key ) { + collection[ key ] = this.instance; + } + } + + collection + .bind( 'relational:add', this.handleAddition ) + .bind( 'relational:remove', this.handleRemoval ) + .bind( 'relational:reset', this.handleReset ); + + return collection; + }, + + findRelated: function( options ) { + if ( this.keyContents ) { + var models = []; + + if ( this.keyContents instanceof Backbone.Collection ) { + models = this.keyContents.models; + } + else { + // Handle cases the an API/user supplies just an Object/id instead of an Array + this.keyContents = _.isArray( this.keyContents ) ? this.keyContents : [ this.keyContents ]; + + // Try to find instances of the appropriate 'relatedModel' in the store + _.each( this.keyContents, function( item ) { + var model = null; + if ( item instanceof this.relatedModel ) { + model = item; + } + else if ( item || item === 0 ) { // since 0 can be a valid `id` as well + model = this.relatedModel.findOrCreate( item, { create: this.options.createModels } ); + } + + if ( model && !this.related.getByCid( model ) && !this.related.get( model ) ) { + models.push( model ); + } + }, this ); + } + + // Add all found 'models' in on go, so 'add' will only be called once (and thus 'sort', etc.) + if ( models.length ) { + options = this.unsanitizeOptions( options ); + this.related.add( models, options ); + } + } + }, + + /** + * If the key is changed, notify old & new reverse relations and initialize the new relation + */ + onChange: function( model, attr, options ) { + options = this.sanitizeOptions( options ); + this.keyContents = attr; + + // Notify old 'related' object of the terminated relation + _.each( this.getReverseRelations(), function( relation ) { + relation.removeRelated( this.instance, options ); + }, this ); + + // Replace 'this.related' by 'attr' if it is a Backbone.Collection + if ( attr instanceof Backbone.Collection ) { + this._prepareCollection( attr ); + this.related = attr; + } + // Otherwise, 'attr' should be an array of related object ids. + // Re-use the current 'this.related' if it is a Backbone.Collection, and remove any current entries. + // Otherwise, create a new collection. + else { + var coll; + + if ( this.related instanceof Backbone.Collection ) { + coll = this.related; + coll.remove( coll.models ); + } + else { + coll = this._prepareCollection(); + } + + this.setRelated( coll ); + this.findRelated( options ); + } + + // Notify new 'related' object of the new relation + _.each( this.getReverseRelations(), function( relation ) { + relation.addRelated( this.instance, options ); + }, this ); + + var dit = this; + Backbone.Relational.eventQueue.add( function() { + !options.silentChange && dit.instance.trigger( 'update:' + dit.key, dit.instance, dit.related, options ); + }); + }, + + tryAddRelated: function( model, options ) { + options = this.sanitizeOptions( options ); + if ( !this.related.getByCid( model ) && !this.related.get( model ) ) { + // Check if this new model was specified in 'this.keyContents' + var item = _.any( this.keyContents, function( item ) { + var id = Backbone.Relational.store.resolveIdForItem( this.relatedModel, item ); + return !_.isNull( id ) && id === model.id; + }, this ); + + if ( item ) { + this.related.add( model, options ); + } + } + }, + + /** + * When a model is added to a 'HasMany', trigger 'add' on 'this.instance' and notify reverse relations. + * (should be 'HasOne', must set 'this.instance' as their related). + */ + handleAddition: function( model, coll, options ) { + //console.debug('handleAddition called; args=%o', arguments); + // Make sure the model is in fact a valid model before continuing. + // (it can be invalid as a result of failing validation in Backbone.Collection._prepareModel) + if ( !( model instanceof Backbone.Model ) ) { + return; + } + + options = this.sanitizeOptions( options ); + + _.each( this.getReverseRelations( model ), function( relation ) { + relation.addRelated( this.instance, options ); + }, this ); + + // Only trigger 'add' once the newly added model is initialized (so, has it's relations set up) + var dit = this; + Backbone.Relational.eventQueue.add( function() { + !options.silentChange && dit.instance.trigger( 'add:' + dit.key, model, dit.related, options ); + }); + }, + + /** + * When a model is removed from a 'HasMany', trigger 'remove' on 'this.instance' and notify reverse relations. + * (should be 'HasOne', which should be nullified) + */ + handleRemoval: function( model, coll, options ) { + //console.debug('handleRemoval called; args=%o', arguments); + if ( !( model instanceof Backbone.Model ) ) { + return; + } + + options = this.sanitizeOptions( options ); + + _.each( this.getReverseRelations( model ), function( relation ) { + relation.removeRelated( this.instance, options ); + }, this ); + + var dit = this; + Backbone.Relational.eventQueue.add( function() { + !options.silentChange && dit.instance.trigger( 'remove:' + dit.key, model, dit.related, options ); + }); + }, + + handleReset: function( coll, options ) { + options = this.sanitizeOptions( options ); + + var dit = this; + Backbone.Relational.eventQueue.add( function() { + !options.silentChange && dit.instance.trigger( 'reset:' + dit.key, dit.related, options ); + }); + }, + + addRelated: function( model, options ) { + var dit = this; + options = this.unsanitizeOptions( options ); + model.queue( function() { // Queued to avoid errors for adding 'model' to the 'this.related' set twice + if ( dit.related && !dit.related.getByCid( model ) && !dit.related.get( model ) ) { + dit.related.add( model, options ); + } + }); + }, + + removeRelated: function( model, options ) { + options = this.unsanitizeOptions( options ); + if ( this.related.getByCid( model ) || this.related.get( model ) ) { + this.related.remove( model, options ); + } + } + }); + + /** + * A type of Backbone.Model that also maintains relations to other models and collections. + * New events when compared to the original: + * - 'add:' (model, related collection, options) + * - 'remove:' (model, related collection, options) + * - 'update:' (model, related model or collection, options) + */ + Backbone.RelationalModel = Backbone.Model.extend({ + relations: null, // Relation descriptions on the prototype + _relations: null, // Relation instances + _isInitialized: false, + _deferProcessing: false, + _queue: null, + + subModelTypeAttribute: 'type', + subModelTypes: null, + + constructor: function( attributes, options ) { + // Nasty hack, for cases like 'model.get( ).add( item )'. + // Defer 'processQueue', so that when 'Relation.createModels' is used we: + // a) Survive 'Backbone.Collection.add'; this takes care we won't error on "can't add model to a set twice" + // (by creating a model from properties, having the model add itself to the collection via one of + // it's relations, then trying to add it to the collection). + // b) Trigger 'HasMany' collection events only after the model is really fully set up. + // Example that triggers both a and b: "p.get('jobs').add( { company: c, person: p } )". + var dit = this; + if ( options && options.collection ) { + this._deferProcessing = true; + + var processQueue = function( model ) { + if ( model === dit ) { + dit._deferProcessing = false; + dit.processQueue(); + options.collection.unbind( 'relational:add', processQueue ); + } + }; + options.collection.bind( 'relational:add', processQueue ); + + // So we do process the queue eventually, regardless of whether this model really gets added to 'options.collection'. + _.defer( function() { + processQueue( dit ); + }); + } + + this._queue = new Backbone.BlockingQueue(); + this._queue.block(); + Backbone.Relational.eventQueue.block(); + + Backbone.Model.apply( this, arguments ); + + // Try to run the global queue holding external events + Backbone.Relational.eventQueue.unblock(); + }, + + /** + * Override 'trigger' to queue 'change' and 'change:*' events + */ + trigger: function( eventName ) { + if ( eventName.length > 5 && 'change' === eventName.substr( 0, 6 ) ) { + var dit = this, args = arguments; + Backbone.Relational.eventQueue.add( function() { + Backbone.Model.prototype.trigger.apply( dit, args ); + }); + } + else { + Backbone.Model.prototype.trigger.apply( this, arguments ); + } + + return this; + }, + + /** + * Initialize Relations present in this.relations; determine the type (HasOne/HasMany), then creates a new instance. + * Invoked in the first call so 'set' (which is made from the Backbone.Model constructor). + */ + initializeRelations: function() { + this.acquire(); // Setting up relations often also involve calls to 'set', and we only want to enter this function once + this._relations = []; + + _.each( this.relations, function( rel ) { + var type = !_.isString( rel.type ) ? rel.type : Backbone[ rel.type ] || Backbone.Relational.store.getObjectByName( rel.type ); + if ( type && type.prototype instanceof Backbone.Relation ) { + new type( this, rel ); // Also pushes the new Relation into _relations + } + else { + Backbone.Relational.showWarnings && typeof console !== 'undefined' && console.warn( 'Relation=%o; missing or invalid type!', rel ); + } + }, this ); + + this._isInitialized = true; + this.release(); + this.processQueue(); + }, + + /** + * When new values are set, notify this model's relations (also if options.silent is set). + * (Relation.setRelated locks this model before calling 'set' on it to prevent loops) + */ + updateRelations: function( options ) { + if ( this._isInitialized && !this.isLocked() ) { + _.each( this._relations, function( rel ) { + // Update from data in `rel.keySource` if set, or `rel.key` otherwise + var val = this.attributes[ rel.keySource ] || this.attributes[ rel.key ]; + if ( rel.related !== val ) { + this.trigger( 'relational:change:' + rel.key, this, val, options || {} ); + } + }, this ); + } + }, + + /** + * Either add to the queue (if we're not initialized yet), or execute right away. + */ + queue: function( func ) { + this._queue.add( func ); + }, + + /** + * Process _queue + */ + processQueue: function() { + if ( this._isInitialized && !this._deferProcessing && this._queue.isBlocked() ) { + this._queue.unblock(); + } + }, + + /** + * Get a specific relation. + * @param key {string} The relation key to look for. + * @return {Backbone.Relation} An instance of 'Backbone.Relation', if a relation was found for 'key', or null. + */ + getRelation: function( key ) { + return _.detect( this._relations, function( rel ) { + if ( rel.key === key ) { + return true; + } + }, this ); + }, + + /** + * Get all of the created relations. + * @return {Backbone.Relation[]} + */ + getRelations: function() { + return this._relations; + }, + + /** + * Retrieve related objects. + * @param key {string} The relation key to fetch models for. + * @param [options] {Object} Options for 'Backbone.Model.fetch' and 'Backbone.sync'. + * @param [update=false] {boolean} Whether to force a fetch from the server (updating existing models). + * @return {jQuery.when[]} An array of request objects + */ + fetchRelated: function( key, options, update ) { + options || ( options = {} ); + var setUrl, + requests = [], + rel = this.getRelation( key ), + keyContents = rel && rel.keyContents, + toFetch = keyContents && _.select( _.isArray( keyContents ) ? keyContents : [ keyContents ], function( item ) { + var id = Backbone.Relational.store.resolveIdForItem( rel.relatedModel, item ); + return !_.isNull( id ) && ( update || !Backbone.Relational.store.find( rel.relatedModel, id ) ); + }, this ); + + if ( toFetch && toFetch.length ) { + // Create a model for each entry in 'keyContents' that is to be fetched + var models = _.map( toFetch, function( item ) { + var model; + + if ( _.isObject( item ) ) { + model = rel.relatedModel.build( item ); + } + else { + var attrs = {}; + attrs[ rel.relatedModel.prototype.idAttribute ] = item; + model = rel.relatedModel.build( attrs ); + } + + return model; + }, this ); + + // Try if the 'collection' can provide a url to fetch a set of models in one request. + if ( rel.related instanceof Backbone.Collection && _.isFunction( rel.related.url ) ) { + setUrl = rel.related.url( models ); + } + + // An assumption is that when 'Backbone.Collection.url' is a function, it can handle building of set urls. + // To make sure it can, test if the url we got by supplying a list of models to fetch is different from + // the one supplied for the default fetch action (without args to 'url'). + if ( setUrl && setUrl !== rel.related.url() ) { + var opts = _.defaults( + { + error: function() { + var args = arguments; + _.each( models, function( model ) { + model.trigger( 'destroy', model, model.collection, options ); + options.error && options.error.apply( model, args ); + }); + }, + url: setUrl + }, + options, + { add: true } + ); + + requests = [ rel.related.fetch( opts ) ]; + } + else { + requests = _.map( models, function( model ) { + var opts = _.defaults( + { + error: function() { + model.trigger( 'destroy', model, model.collection, options ); + options.error && options.error.apply( model, arguments ); + } + }, + options + ); + return model.fetch( opts ); + }, this ); + } + } + + return requests; + }, + + set: function( key, value, options ) { + Backbone.Relational.eventQueue.block(); + + // Duplicate backbone's behavior to allow separate key/value parameters, instead of a single 'attributes' object + var attributes; + if ( _.isObject( key ) || key == null ) { + attributes = key; + options = value; + } + else { + attributes = {}; + attributes[ key ] = value; + } + + var result = Backbone.Model.prototype.set.apply( this, arguments ); + + // Ideal place to set up relations :) + if ( !this._isInitialized && !this.isLocked() ) { + this.constructor.initializeModelHierarchy(); + + Backbone.Relational.store.register( this ); + + this.initializeRelations(); + } + // Update the 'idAttribute' in Backbone.store if; we don't want it to miss an 'id' update due to {silent:true} + else if ( attributes && this.idAttribute in attributes ) { + Backbone.Relational.store.update( this ); + } + + if ( attributes ) { + this.updateRelations( options ); + } + + // Try to run the global queue holding external events + Backbone.Relational.eventQueue.unblock(); + + return result; + }, + + unset: function( attribute, options ) { + Backbone.Relational.eventQueue.block(); + + var result = Backbone.Model.prototype.unset.apply( this, arguments ); + this.updateRelations( options ); + + // Try to run the global queue holding external events + Backbone.Relational.eventQueue.unblock(); + + return result; + }, + + clear: function( options ) { + Backbone.Relational.eventQueue.block(); + + var result = Backbone.Model.prototype.clear.apply( this, arguments ); + this.updateRelations( options ); + + // Try to run the global queue holding external events + Backbone.Relational.eventQueue.unblock(); + + return result; + }, + + /** + * Override 'change', so the change will only execute after 'set' has finised (relations are updated), + * and 'previousAttributes' will be available when the event is fired. + */ + change: function( options ) { + var dit = this, args = arguments; + Backbone.Relational.eventQueue.add( function() { + Backbone.Model.prototype.change.apply( dit, args ); + }); + }, + + clone: function() { + var attributes = _.clone( this.attributes ); + if ( !_.isUndefined( attributes[ this.idAttribute ] ) ) { + attributes[ this.idAttribute ] = null; + } + + _.each( this.getRelations(), function( rel ) { + delete attributes[ rel.key ]; + }); + + return new this.constructor( attributes ); + }, + + /** + * Convert relations to JSON, omits them when required + */ + toJSON: function() { + // If this Model has already been fully serialized in this branch once, return to avoid loops + if ( this.isLocked() ) { + return this.id; + } + + this.acquire(); + var json = Backbone.Model.prototype.toJSON.call( this ); + + if ( this.constructor._superModel && !( this.constructor._subModelTypeAttribute in json ) ) { + json[ this.constructor._subModelTypeAttribute ] = this.constructor._subModelTypeValue; + } + + _.each( this._relations, function( rel ) { + var value = json[ rel.key ]; + + if ( rel.options.includeInJSON === true) { + if ( value && _.isFunction( value.toJSON ) ) { + json[ rel.keyDestination ] = value.toJSON(); + } + else { + json[ rel.keyDestination ] = null; + } + } + else if ( _.isString( rel.options.includeInJSON ) ) { + if ( value instanceof Backbone.Collection ) { + json[ rel.keyDestination ] = value.pluck( rel.options.includeInJSON ); + } + else if ( value instanceof Backbone.Model ) { + json[ rel.keyDestination ] = value.get( rel.options.includeInJSON ); + } + else { + json[ rel.keyDestination ] = null; + } + } + else if ( _.isArray( rel.options.includeInJSON ) ) { + if ( value instanceof Backbone.Collection ) { + var valueSub = []; + value.each( function( model ) { + var curJson = {}; + _.each( rel.options.includeInJSON, function( key ) { + curJson[ key ] = model.get( key ); + }); + valueSub.push( curJson ); + }); + json[ rel.keyDestination ] = valueSub; + } + else if ( value instanceof Backbone.Model ) { + var valueSub = {}; + _.each( rel.options.includeInJSON, function( key ) { + valueSub[ key ] = value.get( key ); + }); + json[ rel.keyDestination ] = valueSub; + } + else { + json[ rel.keyDestination ] = null; + } + } + else { + delete json[ rel.key ]; + } + + if ( rel.keyDestination !== rel.key ) { + delete json[ rel.key ]; + } + }); + + this.release(); + return json; + } + }, + { + setup: function( superModel ) { + // We don't want to share a relations array with a parent, as this will cause problems with + // reverse relations. + this.prototype.relations = ( this.prototype.relations || [] ).slice( 0 ); + + this._subModels = {}; + this._superModel = null; + + // If this model has 'subModelTypes' itself, remember them in the store + if ( this.prototype.hasOwnProperty( 'subModelTypes' ) ) { + Backbone.Relational.store.addSubModels( this.prototype.subModelTypes, this ); + } + // The 'subModelTypes' property should not be inherited, so reset it. + else { + this.prototype.subModelTypes = null; + } + + // Initialize all reverseRelations that belong to this new model. + _.each( this.prototype.relations, function( rel ) { + if ( !rel.model ) { + rel.model = this; + } + + if ( rel.reverseRelation && rel.model === this ) { + var preInitialize = true; + if ( _.isString( rel.relatedModel ) ) { + /** + * The related model might not be defined for two reasons + * 1. it never gets defined, e.g. a typo + * 2. it is related to itself + * In neither of these cases do we need to pre-initialize reverse relations. + */ + var relatedModel = Backbone.Relational.store.getObjectByName( rel.relatedModel ); + preInitialize = relatedModel && ( relatedModel.prototype instanceof Backbone.RelationalModel ); + } + + var type = !_.isString( rel.type ) ? rel.type : Backbone[ rel.type ] || Backbone.Relational.store.getObjectByName( rel.type ); + if ( preInitialize && type && type.prototype instanceof Backbone.Relation ) { + new type( null, rel ); + } + } + }, this ); + + return this; + }, + + /** + * Create a 'Backbone.Model' instance based on 'attributes'. + * @param {Object} attributes + * @param {Object} [options] + * @return {Backbone.Model} + */ + build: function( attributes, options ) { + var model = this; + + // 'build' is a possible entrypoint; it's possible no model hierarchy has been determined yet. + this.initializeModelHierarchy(); + + // Determine what type of (sub)model should be built if applicable. + // Lookup the proper subModelType in 'this._subModels'. + if ( this._subModels && this.prototype.subModelTypeAttribute in attributes ) { + var subModelTypeAttribute = attributes[ this.prototype.subModelTypeAttribute ]; + var subModelType = this._subModels[ subModelTypeAttribute ]; + if ( subModelType ) { + model = subModelType; + } + } + + return new model( attributes, options ); + }, + + initializeModelHierarchy: function() { + // If we're here for the first time, try to determine if this modelType has a 'superModel'. + if ( _.isUndefined( this._superModel ) || _.isNull( this._superModel ) ) { + Backbone.Relational.store.setupSuperModel( this ); + + // If a superModel has been found, copy relations from the _superModel if they haven't been + // inherited automatically (due to a redefinition of 'relations'). + // Otherwise, make sure we don't get here again for this type by making '_superModel' false so we fail + // the isUndefined/isNull check next time. + if ( this._superModel ) { + // + if ( this._superModel.prototype.relations ) { + var supermodelRelationsExist = _.any( this.prototype.relations, function( rel ) { + return rel.model && rel.model !== this; + }, this ); + + if ( !supermodelRelationsExist ) { + this.prototype.relations = this._superModel.prototype.relations.concat( this.prototype.relations ); + } + } + } + else { + this._superModel = false; + } + } + + // If we came here through 'build' for a model that has 'subModelTypes', and not all of them have been resolved yet, try to resolve each. + if ( this.prototype.subModelTypes && _.keys( this.prototype.subModelTypes ).length !== _.keys( this._subModels ).length ) { + _.each( this.prototype.subModelTypes, function( subModelTypeName ) { + var subModelType = Backbone.Relational.store.getObjectByName( subModelTypeName ); + subModelType && subModelType.initializeModelHierarchy(); + }); + } + }, + + /** + * Find an instance of `this` type in 'Backbone.Relational.store'. + * - If `attributes` is a string or a number, `findOrCreate` will just query the `store` and return a model if found. + * - If `attributes` is an object, the model will be updated with `attributes` if found. + * Otherwise, a new model is created with `attributes` (unless `options.create` is explicitly set to `false`). + * @param {Object|String|Number} attributes Either a model's id, or the attributes used to create or update a model. + * @param {Object} [options] + * @param {Boolean} [options.create=true] + * @return {Backbone.RelationalModel} + */ + findOrCreate: function( attributes, options ) { + // Try to find an instance of 'this' model type in the store + var model = Backbone.Relational.store.find( this, attributes ); + + // If we found an instance, update it with the data in 'item'; if not, create an instance + // (unless 'options.create' is false). + if ( _.isObject( attributes ) ) { + if ( model ) { + model.set( model.parse ? model.parse( attributes ) : attributes, options ); + } + else if ( !options || ( options && options.create !== false ) ) { + model = this.build( attributes, options ); + } + } + + return model; + } + }); + _.extend( Backbone.RelationalModel.prototype, Backbone.Semaphore ); + + /** + * Override Backbone.Collection._prepareModel, so objects will be built using the correct type + * if the collection.model has subModels. + */ + Backbone.Collection.prototype.__prepareModel = Backbone.Collection.prototype._prepareModel; + Backbone.Collection.prototype._prepareModel = function ( model, options ) { + options || (options = {}); + if ( !( model instanceof Backbone.Model ) ) { + var attrs = model; + options.collection = this; + + if ( typeof this.model.findOrCreate !== 'undefined' ) { + model = this.model.findOrCreate( attrs, options ); + } + else { + model = new this.model( attrs, options ); + } + + if ( !model._validate( model.attributes, options ) ) { + model = false; + } + } + else if ( !model.collection ) { + model.collection = this; + } + + return model; + } + + /** + * Override Backbone.Collection.add, so objects fetched from the server multiple times will + * update the existing Model. Also, trigger 'relational:add'. + */ + var add = Backbone.Collection.prototype.__add = Backbone.Collection.prototype.add; + Backbone.Collection.prototype.add = function( models, options ) { + options || (options = {}); + if ( !_.isArray( models ) ) { + models = [ models ]; + } + + var modelsToAdd = []; + + //console.debug( 'calling add on coll=%o; model=%o, options=%o', this, models, options ); + _.each( models, function( model ) { + if ( !( model instanceof Backbone.Model ) ) { + // `_prepareModel` attempts to find `model` in Backbone.store through `findOrCreate`, + // and sets the new properties on it if is found. Otherwise, a new model is instantiated. + model = Backbone.Collection.prototype._prepareModel.call( this, model, options ); + } + + if ( model instanceof Backbone.Model && !this.get( model ) && !this.getByCid( model ) ) { + modelsToAdd.push( model ); + } + }, this ); + + + // Add 'models' in a single batch, so the original add will only be called once (and thus 'sort', etc). + if ( modelsToAdd.length ) { + add.call( this, modelsToAdd, options ); + + _.each( modelsToAdd, function( model ) { + this.trigger( 'relational:add', model, this, options ); + }, this ); + } + + return this; + }; + + /** + * Override 'Backbone.Collection.remove' to trigger 'relational:remove'. + */ + var remove = Backbone.Collection.prototype.__remove = Backbone.Collection.prototype.remove; + Backbone.Collection.prototype.remove = function( models, options ) { + options || (options = {}); + if ( !_.isArray( models ) ) { + models = [ models ]; + } + else { + models = models.slice( 0 ); + } + + //console.debug('calling remove on coll=%o; models=%o, options=%o', this, models, options ); + _.each( models, function( model ) { + model = this.getByCid( model ) || this.get( model ); + + if ( model instanceof Backbone.Model ) { + remove.call( this, model, options ); + this.trigger('relational:remove', model, this, options); + } + }, this ); + + return this; + }; + + /** + * Override 'Backbone.Collection.reset' to trigger 'relational:reset'. + */ + var reset = Backbone.Collection.prototype.__reset = Backbone.Collection.prototype.reset; + Backbone.Collection.prototype.reset = function( models, options ) { + reset.call( this, models, options ); + this.trigger( 'relational:reset', this, options ); + + return this; + }; + + /** + * Override 'Backbone.Collection.sort' to trigger 'relational:reset'. + */ + var sort = Backbone.Collection.prototype.__sort = Backbone.Collection.prototype.sort; + Backbone.Collection.prototype.sort = function( options ) { + sort.call( this, options ); + this.trigger( 'relational:reset', this, options ); + + return this; + }; + + /** + * Override 'Backbone.Collection.trigger' so 'add', 'remove' and 'reset' events are queued until relations + * are ready. + */ + var trigger = Backbone.Collection.prototype.__trigger = Backbone.Collection.prototype.trigger; + Backbone.Collection.prototype.trigger = function( eventName ) { + if ( eventName === 'add' || eventName === 'remove' || eventName === 'reset' ) { + var dit = this, args = arguments; + + if (eventName === 'add') { + args = _.toArray(args); + // the fourth argument in case of a regular add is the option object. + // we need to clone it, as it could be modified while we wait on the eventQueue to be unblocked + if (_.isObject(args[3])) { + args[3] = _.clone(args[3]); + } + } + + Backbone.Relational.eventQueue.add( function() { + trigger.apply( dit, args ); + }); + } + else { + trigger.apply( this, arguments ); + } + + return this; + }; + + // Override .extend() to automatically call .setup() + Backbone.RelationalModel.extend = function( protoProps, classProps ) { + var child = Backbone.Model.extend.apply( this, arguments ); + + child.setup( this ); + + return child; + }; +})(); diff -r 4aec3f00ea87 -r 1fa074d64662 integ/renkan/lib/backbone.js --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/integ/renkan/lib/backbone.js Wed Apr 03 18:56:34 2013 +0200 @@ -0,0 +1,1431 @@ +// Backbone.js 0.9.2 + +// (c) 2010-2012 Jeremy Ashkenas, DocumentCloud Inc. +// Backbone may be freely distributed under the MIT license. +// For all details and documentation: +// http://backbonejs.org + +(function(){ + + // Initial Setup + // ------------- + + // Save a reference to the global object (`window` in the browser, `global` + // on the server). + var root = this; + + // Save the previous value of the `Backbone` variable, so that it can be + // restored later on, if `noConflict` is used. + var previousBackbone = root.Backbone; + + // Create a local reference to slice/splice. + var slice = Array.prototype.slice; + var splice = Array.prototype.splice; + + // The top-level namespace. All public Backbone classes and modules will + // be attached to this. Exported for both CommonJS and the browser. + var Backbone; + if (typeof exports !== 'undefined') { + Backbone = exports; + } else { + Backbone = root.Backbone = {}; + } + + // Current version of the library. Keep in sync with `package.json`. + Backbone.VERSION = '0.9.2'; + + // Require Underscore, if we're on the server, and it's not already present. + var _ = root._; + if (!_ && (typeof require !== 'undefined')) _ = require('underscore'); + + // For Backbone's purposes, jQuery, Zepto, or Ender owns the `$` variable. + var $ = root.jQuery || root.Zepto || root.ender; + + // Set the JavaScript library that will be used for DOM manipulation and + // Ajax calls (a.k.a. the `$` variable). By default Backbone will use: jQuery, + // Zepto, or Ender; but the `setDomLibrary()` method lets you inject an + // alternate JavaScript library (or a mock library for testing your views + // outside of a browser). + Backbone.setDomLibrary = function(lib) { + $ = lib; + }; + + // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable + // to its previous owner. Returns a reference to this Backbone object. + Backbone.noConflict = function() { + root.Backbone = previousBackbone; + return this; + }; + + // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option + // will fake `"PUT"` and `"DELETE"` requests via the `_method` parameter and + // set a `X-Http-Method-Override` header. + Backbone.emulateHTTP = false; + + // Turn on `emulateJSON` to support legacy servers that can't deal with direct + // `application/json` requests ... will encode the body as + // `application/x-www-form-urlencoded` instead and will send the model in a + // form param named `model`. + Backbone.emulateJSON = false; + + // Backbone.Events + // ----------------- + + // Regular expression used to split event strings + var eventSplitter = /\s+/; + + // A module that can be mixed in to *any object* in order to provide it with + // custom events. You may bind with `on` or remove with `off` callback functions + // to an event; trigger`-ing an event fires all callbacks in succession. + // + // var object = {}; + // _.extend(object, Backbone.Events); + // object.on('expand', function(){ alert('expanded'); }); + // object.trigger('expand'); + // + var Events = Backbone.Events = { + + // Bind one or more space separated events, `events`, to a `callback` + // function. Passing `"all"` will bind the callback to all events fired. + on: function(events, callback, context) { + + var calls, event, node, tail, list; + if (!callback) return this; + events = events.split(eventSplitter); + calls = this._callbacks || (this._callbacks = {}); + + // Create an immutable callback list, allowing traversal during + // modification. The tail is an empty object that will always be used + // as the next node. + while (event = events.shift()) { + list = calls[event]; + node = list ? list.tail : {}; + node.next = tail = {}; + node.context = context; + node.callback = callback; + calls[event] = {tail: tail, next: list ? list.next : node}; + } + + return this; + }, + + // Remove one or many callbacks. If `context` is null, removes all callbacks + // with that function. If `callback` is null, removes all callbacks for the + // event. If `events` is null, removes all bound callbacks for all events. + off: function(events, callback, context) { + var event, calls, node, tail, cb, ctx; + + // No events, or removing *all* events. + if (!(calls = this._callbacks)) return; + if (!(events || callback || context)) { + delete this._callbacks; + return this; + } + + // Loop through the listed events and contexts, splicing them out of the + // linked list of callbacks if appropriate. + events = events ? events.split(eventSplitter) : _.keys(calls); + while (event = events.shift()) { + node = calls[event]; + delete calls[event]; + if (!node || !(callback || context)) continue; + // Create a new list, omitting the indicated callbacks. + tail = node.tail; + while ((node = node.next) !== tail) { + cb = node.callback; + ctx = node.context; + if ((callback && cb !== callback) || (context && ctx !== context)) { + this.on(event, cb, ctx); + } + } + } + + return this; + }, + + // Trigger one or many events, firing all bound callbacks. Callbacks are + // passed the same arguments as `trigger` is, apart from the event name + // (unless you're listening on `"all"`, which will cause your callback to + // receive the true name of the event as the first argument). + trigger: function(events) { + var event, node, calls, tail, args, all, rest; + if (!(calls = this._callbacks)) return this; + all = calls.all; + events = events.split(eventSplitter); + rest = slice.call(arguments, 1); + + // For each event, walk through the linked list of callbacks twice, + // first to trigger the event, then to trigger any `"all"` callbacks. + while (event = events.shift()) { + if (node = calls[event]) { + tail = node.tail; + while ((node = node.next) !== tail) { + node.callback.apply(node.context || this, rest); + } + } + if (node = all) { + tail = node.tail; + args = [event].concat(rest); + while ((node = node.next) !== tail) { + node.callback.apply(node.context || this, args); + } + } + } + + return this; + } + + }; + + // Aliases for backwards compatibility. + Events.bind = Events.on; + Events.unbind = Events.off; + + // Backbone.Model + // -------------- + + // Create a new model, with defined attributes. A client id (`cid`) + // is automatically generated and assigned for you. + var Model = Backbone.Model = function(attributes, options) { + var defaults; + attributes || (attributes = {}); + if (options && options.parse) attributes = this.parse(attributes); + if (defaults = getValue(this, 'defaults')) { + attributes = _.extend({}, defaults, attributes); + } + if (options && options.collection) this.collection = options.collection; + this.attributes = {}; + this._escapedAttributes = {}; + this.cid = _.uniqueId('c'); + this.changed = {}; + this._silent = {}; + this._pending = {}; + this.set(attributes, {silent: true}); + // Reset change tracking. + this.changed = {}; + this._silent = {}; + this._pending = {}; + this._previousAttributes = _.clone(this.attributes); + this.initialize.apply(this, arguments); + }; + + // Attach all inheritable methods to the Model prototype. + _.extend(Model.prototype, Events, { + + // A hash of attributes whose current and previous value differ. + changed: null, + + // A hash of attributes that have silently changed since the last time + // `change` was called. Will become pending attributes on the next call. + _silent: null, + + // A hash of attributes that have changed since the last `'change'` event + // began. + _pending: null, + + // The default name for the JSON `id` attribute is `"id"`. MongoDB and + // CouchDB users may want to set this to `"_id"`. + idAttribute: 'id', + + // Initialize is an empty function by default. Override it with your own + // initialization logic. + initialize: function(){}, + + // Return a copy of the model's `attributes` object. + toJSON: function(options) { + return _.clone(this.attributes); + }, + + // Get the value of an attribute. + get: function(attr) { + return this.attributes[attr]; + }, + + // Get the HTML-escaped value of an attribute. + escape: function(attr) { + var html; + if (html = this._escapedAttributes[attr]) return html; + var val = this.get(attr); + return this._escapedAttributes[attr] = _.escape(val == null ? '' : '' + val); + }, + + // Returns `true` if the attribute contains a value that is not null + // or undefined. + has: function(attr) { + return this.get(attr) != null; + }, + + // Set a hash of model attributes on the object, firing `"change"` unless + // you choose to silence it. + set: function(key, value, options) { + var attrs, attr, val; + + // Handle both `"key", value` and `{key: value}` -style arguments. + if (_.isObject(key) || key == null) { + attrs = key; + options = value; + } else { + attrs = {}; + attrs[key] = value; + } + + // Extract attributes and options. + options || (options = {}); + if (!attrs) return this; + if (attrs instanceof Model) attrs = attrs.attributes; + if (options.unset) for (attr in attrs) attrs[attr] = void 0; + + // Run validation. + if (!this._validate(attrs, options)) return false; + + // Check for changes of `id`. + if (this.idAttribute in attrs) this.id = attrs[this.idAttribute]; + + var changes = options.changes = {}; + var now = this.attributes; + var escaped = this._escapedAttributes; + var prev = this._previousAttributes || {}; + + // For each `set` attribute... + for (attr in attrs) { + val = attrs[attr]; + + // If the new and current value differ, record the change. + if (!_.isEqual(now[attr], val) || (options.unset && _.has(now, attr))) { + delete escaped[attr]; + (options.silent ? this._silent : changes)[attr] = true; + } + + // Update or delete the current value. + options.unset ? delete now[attr] : now[attr] = val; + + // If the new and previous value differ, record the change. If not, + // then remove changes for this attribute. + if (!_.isEqual(prev[attr], val) || (_.has(now, attr) != _.has(prev, attr))) { + this.changed[attr] = val; + if (!options.silent) this._pending[attr] = true; + } else { + delete this.changed[attr]; + delete this._pending[attr]; + } + } + + // Fire the `"change"` events. + if (!options.silent) this.change(options); + return this; + }, + + // Remove an attribute from the model, firing `"change"` unless you choose + // to silence it. `unset` is a noop if the attribute doesn't exist. + unset: function(attr, options) { + (options || (options = {})).unset = true; + return this.set(attr, null, options); + }, + + // Clear all attributes on the model, firing `"change"` unless you choose + // to silence it. + clear: function(options) { + (options || (options = {})).unset = true; + return this.set(_.clone(this.attributes), options); + }, + + // Fetch the model from the server. If the server's representation of the + // model differs from its current attributes, they will be overriden, + // triggering a `"change"` event. + fetch: function(options) { + options = options ? _.clone(options) : {}; + var model = this; + var success = options.success; + options.success = function(resp, status, xhr) { + if (!model.set(model.parse(resp, xhr), options)) return false; + if (success) success(model, resp); + }; + options.error = Backbone.wrapError(options.error, model, options); + return (this.sync || Backbone.sync).call(this, 'read', this, options); + }, + + // Set a hash of model attributes, and sync the model to the server. + // If the server returns an attributes hash that differs, the model's + // state will be `set` again. + save: function(key, value, options) { + var attrs, current; + + // Handle both `("key", value)` and `({key: value})` -style calls. + if (_.isObject(key) || key == null) { + attrs = key; + options = value; + } else { + attrs = {}; + attrs[key] = value; + } + options = options ? _.clone(options) : {}; + + // If we're "wait"-ing to set changed attributes, validate early. + if (options.wait) { + if (!this._validate(attrs, options)) return false; + current = _.clone(this.attributes); + } + + // Regular saves `set` attributes before persisting to the server. + var silentOptions = _.extend({}, options, {silent: true}); + if (attrs && !this.set(attrs, options.wait ? silentOptions : options)) { + return false; + } + + // After a successful server-side save, the client is (optionally) + // updated with the server-side state. + var model = this; + var success = options.success; + options.success = function(resp, status, xhr) { + var serverAttrs = model.parse(resp, xhr); + if (options.wait) { + delete options.wait; + serverAttrs = _.extend(attrs || {}, serverAttrs); + } + if (!model.set(serverAttrs, options)) return false; + if (success) { + success(model, resp); + } else { + model.trigger('sync', model, resp, options); + } + }; + + // Finish configuring and sending the Ajax request. + options.error = Backbone.wrapError(options.error, model, options); + var method = this.isNew() ? 'create' : 'update'; + var xhr = (this.sync || Backbone.sync).call(this, method, this, options); + if (options.wait) this.set(current, silentOptions); + return xhr; + }, + + // Destroy this model on the server if it was already persisted. + // Optimistically removes the model from its collection, if it has one. + // If `wait: true` is passed, waits for the server to respond before removal. + destroy: function(options) { + options = options ? _.clone(options) : {}; + var model = this; + var success = options.success; + + var triggerDestroy = function() { + model.trigger('destroy', model, model.collection, options); + }; + + if (this.isNew()) { + triggerDestroy(); + return false; + } + + options.success = function(resp) { + if (options.wait) triggerDestroy(); + if (success) { + success(model, resp); + } else { + model.trigger('sync', model, resp, options); + } + }; + + options.error = Backbone.wrapError(options.error, model, options); + var xhr = (this.sync || Backbone.sync).call(this, 'delete', this, options); + if (!options.wait) triggerDestroy(); + return xhr; + }, + + // Default URL for the model's representation on the server -- if you're + // using Backbone's restful methods, override this to change the endpoint + // that will be called. + url: function() { + var base = getValue(this, 'urlRoot') || getValue(this.collection, 'url') || urlError(); + if (this.isNew()) return base; + return base + (base.charAt(base.length - 1) == '/' ? '' : '/') + encodeURIComponent(this.id); + }, + + // **parse** converts a response into the hash of attributes to be `set` on + // the model. The default implementation is just to pass the response along. + parse: function(resp, xhr) { + return resp; + }, + + // Create a new model with identical attributes to this one. + clone: function() { + return new this.constructor(this.attributes); + }, + + // A model is new if it has never been saved to the server, and lacks an id. + isNew: function() { + return this.id == null; + }, + + // Call this method to manually fire a `"change"` event for this model and + // a `"change:attribute"` event for each changed attribute. + // Calling this will cause all objects observing the model to update. + change: function(options) { + options || (options = {}); + var changing = this._changing; + this._changing = true; + + // Silent changes become pending changes. + for (var attr in this._silent) this._pending[attr] = true; + + // Silent changes are triggered. + var changes = _.extend({}, options.changes, this._silent); + this._silent = {}; + for (var attr in changes) { + this.trigger('change:' + attr, this, this.get(attr), options); + } + if (changing) return this; + + // Continue firing `"change"` events while there are pending changes. + while (!_.isEmpty(this._pending)) { + this._pending = {}; + this.trigger('change', this, options); + // Pending and silent changes still remain. + for (var attr in this.changed) { + if (this._pending[attr] || this._silent[attr]) continue; + delete this.changed[attr]; + } + this._previousAttributes = _.clone(this.attributes); + } + + this._changing = false; + return this; + }, + + // Determine if the model has changed since the last `"change"` event. + // If you specify an attribute name, determine if that attribute has changed. + hasChanged: function(attr) { + if (!arguments.length) return !_.isEmpty(this.changed); + return _.has(this.changed, attr); + }, + + // Return an object containing all the attributes that have changed, or + // false if there are no changed attributes. Useful for determining what + // parts of a view need to be updated and/or what attributes need to be + // persisted to the server. Unset attributes will be set to undefined. + // You can also pass an attributes object to diff against the model, + // determining if there *would be* a change. + changedAttributes: function(diff) { + if (!diff) return this.hasChanged() ? _.clone(this.changed) : false; + var val, changed = false, old = this._previousAttributes; + for (var attr in diff) { + if (_.isEqual(old[attr], (val = diff[attr]))) continue; + (changed || (changed = {}))[attr] = val; + } + return changed; + }, + + // Get the previous value of an attribute, recorded at the time the last + // `"change"` event was fired. + previous: function(attr) { + if (!arguments.length || !this._previousAttributes) return null; + return this._previousAttributes[attr]; + }, + + // Get all of the attributes of the model at the time of the previous + // `"change"` event. + previousAttributes: function() { + return _.clone(this._previousAttributes); + }, + + // Check if the model is currently in a valid state. It's only possible to + // get into an *invalid* state if you're using silent changes. + isValid: function() { + return !this.validate(this.attributes); + }, + + // Run validation against the next complete set of model attributes, + // returning `true` if all is well. If a specific `error` callback has + // been passed, call that instead of firing the general `"error"` event. + _validate: function(attrs, options) { + if (options.silent || !this.validate) return true; + attrs = _.extend({}, this.attributes, attrs); + var error = this.validate(attrs, options); + if (!error) return true; + if (options && options.error) { + options.error(this, error, options); + } else { + this.trigger('error', this, error, options); + } + return false; + } + + }); + + // Backbone.Collection + // ------------------- + + // Provides a standard collection class for our sets of models, ordered + // or unordered. If a `comparator` is specified, the Collection will maintain + // its models in sort order, as they're added and removed. + var Collection = Backbone.Collection = function(models, options) { + options || (options = {}); + if (options.model) this.model = options.model; + if (options.comparator) this.comparator = options.comparator; + this._reset(); + this.initialize.apply(this, arguments); + if (models) this.reset(models, {silent: true, parse: options.parse}); + }; + + // Define the Collection's inheritable methods. + _.extend(Collection.prototype, Events, { + + // The default model for a collection is just a **Backbone.Model**. + // This should be overridden in most cases. + model: Model, + + // Initialize is an empty function by default. Override it with your own + // initialization logic. + initialize: function(){}, + + // The JSON representation of a Collection is an array of the + // models' attributes. + toJSON: function(options) { + return this.map(function(model){ return model.toJSON(options); }); + }, + + // Add a model, or list of models to the set. Pass **silent** to avoid + // firing the `add` event for every new model. + add: function(models, options) { + var i, index, length, model, cid, id, cids = {}, ids = {}, dups = []; + options || (options = {}); + models = _.isArray(models) ? models.slice() : [models]; + + // Begin by turning bare objects into model references, and preventing + // invalid models or duplicate models from being added. + for (i = 0, length = models.length; i < length; i++) { + if (!(model = models[i] = this._prepareModel(models[i], options))) { + throw new Error("Can't add an invalid model to a collection"); + } + cid = model.cid; + id = model.id; + if (cids[cid] || this._byCid[cid] || ((id != null) && (ids[id] || this._byId[id]))) { + dups.push(i); + continue; + } + cids[cid] = ids[id] = model; + } + + // Remove duplicates. + i = dups.length; + while (i--) { + models.splice(dups[i], 1); + } + + // Listen to added models' events, and index models for lookup by + // `id` and by `cid`. + for (i = 0, length = models.length; i < length; i++) { + (model = models[i]).on('all', this._onModelEvent, this); + this._byCid[model.cid] = model; + if (model.id != null) this._byId[model.id] = model; + } + + // Insert models into the collection, re-sorting if needed, and triggering + // `add` events unless silenced. + this.length += length; + index = options.at != null ? options.at : this.models.length; + splice.apply(this.models, [index, 0].concat(models)); + if (this.comparator) this.sort({silent: true}); + if (options.silent) return this; + for (i = 0, length = this.models.length; i < length; i++) { + if (!cids[(model = this.models[i]).cid]) continue; + options.index = i; + model.trigger('add', model, this, options); + } + return this; + }, + + // Remove a model, or a list of models from the set. Pass silent to avoid + // firing the `remove` event for every model removed. + remove: function(models, options) { + var i, l, index, model; + options || (options = {}); + models = _.isArray(models) ? models.slice() : [models]; + for (i = 0, l = models.length; i < l; i++) { + model = this.getByCid(models[i]) || this.get(models[i]); + if (!model) continue; + delete this._byId[model.id]; + delete this._byCid[model.cid]; + index = this.indexOf(model); + this.models.splice(index, 1); + this.length--; + if (!options.silent) { + options.index = index; + model.trigger('remove', model, this, options); + } + this._removeReference(model); + } + return this; + }, + + // Add a model to the end of the collection. + push: function(model, options) { + model = this._prepareModel(model, options); + this.add(model, options); + return model; + }, + + // Remove a model from the end of the collection. + pop: function(options) { + var model = this.at(this.length - 1); + this.remove(model, options); + return model; + }, + + // Add a model to the beginning of the collection. + unshift: function(model, options) { + model = this._prepareModel(model, options); + this.add(model, _.extend({at: 0}, options)); + return model; + }, + + // Remove a model from the beginning of the collection. + shift: function(options) { + var model = this.at(0); + this.remove(model, options); + return model; + }, + + // Get a model from the set by id. + get: function(id) { + if (id == null) return void 0; + return this._byId[id.id != null ? id.id : id]; + }, + + // Get a model from the set by client id. + getByCid: function(cid) { + return cid && this._byCid[cid.cid || cid]; + }, + + // Get the model at the given index. + at: function(index) { + return this.models[index]; + }, + + // Return models with matching attributes. Useful for simple cases of `filter`. + where: function(attrs) { + if (_.isEmpty(attrs)) return []; + return this.filter(function(model) { + for (var key in attrs) { + if (attrs[key] !== model.get(key)) return false; + } + return true; + }); + }, + + // Force the collection to re-sort itself. You don't need to call this under + // normal circumstances, as the set will maintain sort order as each item + // is added. + sort: function(options) { + options || (options = {}); + if (!this.comparator) throw new Error('Cannot sort a set without a comparator'); + var boundComparator = _.bind(this.comparator, this); + if (this.comparator.length == 1) { + this.models = this.sortBy(boundComparator); + } else { + this.models.sort(boundComparator); + } + if (!options.silent) this.trigger('reset', this, options); + return this; + }, + + // Pluck an attribute from each model in the collection. + pluck: function(attr) { + return _.map(this.models, function(model){ return model.get(attr); }); + }, + + // When you have more items than you want to add or remove individually, + // you can reset the entire set with a new list of models, without firing + // any `add` or `remove` events. Fires `reset` when finished. + reset: function(models, options) { + models || (models = []); + options || (options = {}); + for (var i = 0, l = this.models.length; i < l; i++) { + this._removeReference(this.models[i]); + } + this._reset(); + this.add(models, _.extend({silent: true}, options)); + if (!options.silent) this.trigger('reset', this, options); + return this; + }, + + // Fetch the default set of models for this collection, resetting the + // collection when they arrive. If `add: true` is passed, appends the + // models to the collection instead of resetting. + fetch: function(options) { + options = options ? _.clone(options) : {}; + if (options.parse === undefined) options.parse = true; + var collection = this; + var success = options.success; + options.success = function(resp, status, xhr) { + collection[options.add ? 'add' : 'reset'](collection.parse(resp, xhr), options); + if (success) success(collection, resp); + }; + options.error = Backbone.wrapError(options.error, collection, options); + return (this.sync || Backbone.sync).call(this, 'read', this, options); + }, + + // Create a new instance of a model in this collection. Add the model to the + // collection immediately, unless `wait: true` is passed, in which case we + // wait for the server to agree. + create: function(model, options) { + var coll = this; + options = options ? _.clone(options) : {}; + model = this._prepareModel(model, options); + if (!model) return false; + if (!options.wait) coll.add(model, options); + var success = options.success; + options.success = function(nextModel, resp, xhr) { + if (options.wait) coll.add(nextModel, options); + if (success) { + success(nextModel, resp); + } else { + nextModel.trigger('sync', model, resp, options); + } + }; + model.save(null, options); + return model; + }, + + // **parse** converts a response into a list of models to be added to the + // collection. The default implementation is just to pass it through. + parse: function(resp, xhr) { + return resp; + }, + + // Proxy to _'s chain. Can't be proxied the same way the rest of the + // underscore methods are proxied because it relies on the underscore + // constructor. + chain: function () { + return _(this.models).chain(); + }, + + // Reset all internal state. Called when the collection is reset. + _reset: function(options) { + this.length = 0; + this.models = []; + this._byId = {}; + this._byCid = {}; + }, + + // Prepare a model or hash of attributes to be added to this collection. + _prepareModel: function(model, options) { + options || (options = {}); + if (!(model instanceof Model)) { + var attrs = model; + options.collection = this; + model = new this.model(attrs, options); + if (!model._validate(model.attributes, options)) model = false; + } else if (!model.collection) { + model.collection = this; + } + return model; + }, + + // Internal method to remove a model's ties to a collection. + _removeReference: function(model) { + if (this == model.collection) { + delete model.collection; + } + model.off('all', this._onModelEvent, this); + }, + + // Internal method called every time a model in the set fires an event. + // Sets need to update their indexes when models change ids. All other + // events simply proxy through. "add" and "remove" events that originate + // in other collections are ignored. + _onModelEvent: function(event, model, collection, options) { + if ((event == 'add' || event == 'remove') && collection != this) return; + if (event == 'destroy') { + this.remove(model, options); + } + if (model && event === 'change:' + model.idAttribute) { + delete this._byId[model.previous(model.idAttribute)]; + this._byId[model.id] = model; + } + this.trigger.apply(this, arguments); + } + + }); + + // Underscore methods that we want to implement on the Collection. + var methods = ['forEach', 'each', 'map', 'reduce', 'reduceRight', 'find', + 'detect', 'filter', 'select', 'reject', 'every', 'all', 'some', 'any', + 'include', 'contains', 'invoke', 'max', 'min', 'sortBy', 'sortedIndex', + 'toArray', 'size', 'first', 'initial', 'rest', 'last', 'without', 'indexOf', + 'shuffle', 'lastIndexOf', 'isEmpty', 'groupBy']; + + // Mix in each Underscore method as a proxy to `Collection#models`. + _.each(methods, function(method) { + Collection.prototype[method] = function() { + return _[method].apply(_, [this.models].concat(_.toArray(arguments))); + }; + }); + + // Backbone.Router + // ------------------- + + // Routers map faux-URLs to actions, and fire events when routes are + // matched. Creating a new one sets its `routes` hash, if not set statically. + var Router = Backbone.Router = function(options) { + options || (options = {}); + if (options.routes) this.routes = options.routes; + this._bindRoutes(); + this.initialize.apply(this, arguments); + }; + + // Cached regular expressions for matching named param parts and splatted + // parts of route strings. + var namedParam = /:\w+/g; + var splatParam = /\*\w+/g; + var escapeRegExp = /[-[\]{}()+?.,\\^$|#\s]/g; + + // Set up all inheritable **Backbone.Router** properties and methods. + _.extend(Router.prototype, Events, { + + // Initialize is an empty function by default. Override it with your own + // initialization logic. + initialize: function(){}, + + // Manually bind a single named route to a callback. For example: + // + // this.route('search/:query/p:num', 'search', function(query, num) { + // ... + // }); + // + route: function(route, name, callback) { + Backbone.history || (Backbone.history = new History); + if (!_.isRegExp(route)) route = this._routeToRegExp(route); + if (!callback) callback = this[name]; + Backbone.history.route(route, _.bind(function(fragment) { + var args = this._extractParameters(route, fragment); + callback && callback.apply(this, args); + this.trigger.apply(this, ['route:' + name].concat(args)); + Backbone.history.trigger('route', this, name, args); + }, this)); + return this; + }, + + // Simple proxy to `Backbone.history` to save a fragment into the history. + navigate: function(fragment, options) { + Backbone.history.navigate(fragment, options); + }, + + // Bind all defined routes to `Backbone.history`. We have to reverse the + // order of the routes here to support behavior where the most general + // routes can be defined at the bottom of the route map. + _bindRoutes: function() { + if (!this.routes) return; + var routes = []; + for (var route in this.routes) { + routes.unshift([route, this.routes[route]]); + } + for (var i = 0, l = routes.length; i < l; i++) { + this.route(routes[i][0], routes[i][1], this[routes[i][1]]); + } + }, + + // Convert a route string into a regular expression, suitable for matching + // against the current location hash. + _routeToRegExp: function(route) { + route = route.replace(escapeRegExp, '\\$&') + .replace(namedParam, '([^\/]+)') + .replace(splatParam, '(.*?)'); + return new RegExp('^' + route + '$'); + }, + + // Given a route, and a URL fragment that it matches, return the array of + // extracted parameters. + _extractParameters: function(route, fragment) { + return route.exec(fragment).slice(1); + } + + }); + + // Backbone.History + // ---------------- + + // Handles cross-browser history management, based on URL fragments. If the + // browser does not support `onhashchange`, falls back to polling. + var History = Backbone.History = function() { + this.handlers = []; + _.bindAll(this, 'checkUrl'); + }; + + // Cached regex for cleaning leading hashes and slashes . + var routeStripper = /^[#\/]/; + + // Cached regex for detecting MSIE. + var isExplorer = /msie [\w.]+/; + + // Has the history handling already been started? + History.started = false; + + // Set up all inheritable **Backbone.History** properties and methods. + _.extend(History.prototype, Events, { + + // The default interval to poll for hash changes, if necessary, is + // twenty times a second. + interval: 50, + + // Gets the true hash value. Cannot use location.hash directly due to bug + // in Firefox where location.hash will always be decoded. + getHash: function(windowOverride) { + var loc = windowOverride ? windowOverride.location : window.location; + var match = loc.href.match(/#(.*)$/); + return match ? match[1] : ''; + }, + + // Get the cross-browser normalized URL fragment, either from the URL, + // the hash, or the override. + getFragment: function(fragment, forcePushState) { + if (fragment == null) { + if (this._hasPushState || forcePushState) { + fragment = window.location.pathname; + var search = window.location.search; + if (search) fragment += search; + } else { + fragment = this.getHash(); + } + } + if (!fragment.indexOf(this.options.root)) fragment = fragment.substr(this.options.root.length); + return fragment.replace(routeStripper, ''); + }, + + // Start the hash change handling, returning `true` if the current URL matches + // an existing route, and `false` otherwise. + start: function(options) { + if (History.started) throw new Error("Backbone.history has already been started"); + History.started = true; + + // Figure out the initial configuration. Do we need an iframe? + // Is pushState desired ... is it available? + this.options = _.extend({}, {root: '/'}, this.options, options); + this._wantsHashChange = this.options.hashChange !== false; + this._wantsPushState = !!this.options.pushState; + this._hasPushState = !!(this.options.pushState && window.history && window.history.pushState); + var fragment = this.getFragment(); + var docMode = document.documentMode; + var oldIE = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7)); + + if (oldIE) { + this.iframe = $('