-
Mapping Version History
+ {% if mapping.owner_type == 'Organization' %}
+ {% url 'mapping-diff-version' org=mapping.owner source=mapping.source mapping=mapping.id as mapping_version_diff_url %}
+ {% else %}
+ {% url 'mapping-diff-version' user=mapping.owner source=mapping.source mapping=mapping.id as mapping_version_diff_url %}
+ {% endif %}
+
+ {{ mapping_version_diff_url }}
+
{% for mapping_version in mapping_versions %}
@@ -46,10 +54,71 @@
None
Mapping Version History .
+
+
+
{% endblock tab-content %}
diff --git a/ocl_web/templates/mappings/mappings_diff.html b/ocl_web/templates/mappings/mappings_diff.html
new file mode 100644
index 00000000..10ac9e70
--- /dev/null
+++ b/ocl_web/templates/mappings/mappings_diff.html
@@ -0,0 +1,88 @@
+{% extends "mappings/mapping_base.html" %}
+{% load i18n %}
+{% load ocl_tags %}
+{% load bootstrap3 %}
+
+{% block resource-tabs %}
+{% endblock resource-tabs %}
+
+{% block tab-content %}
+
+
+
+
+
+
+{% endblock tab-content %}
+
+
+{% block extrajavascript %}
+
+
+{% endblock %}
+
+
+{% block resource-debug %}
+
URL kwargs {{ kwargs|pprint }}
+
URL Parameters {{ url_params|pprint }}
+
Mapping {{ mapping|pprint }}
+{% endblock resource-debug %}
+
From 84ecba68cf1e62609e0a29f2635e78a6ed028e3a Mon Sep 17 00:00:00 2001
From: hao555sky <836095186@qq.com>
Date: Fri, 18 Aug 2017 21:55:56 +0800
Subject: [PATCH 3/4] implement the function that get all mappings with any
source
---
ocl_web/apps/concepts/views.py | 89 +-
ocl_web/apps/sources/views.py | 14 -
ocl_web/config/users_urls.py | 6 +-
ocl_web/static/css/bootstrap-multiselect.css | 1 +
ocl_web/static/js/bootstrap-multiselect.js | 1716 +++++++++++++++++
ocl_web/static/js/project.js | 7 +
ocl_web/static/js/springy.js | 731 +++++++
ocl_web/static/js/springyui.js | 394 ++++
ocl_web/templates/base.html | 4 +
ocl_web/templates/concepts/concept_base.html | 4 +
.../concepts/concept_relationship.html | 186 ++
11 files changed, 3134 insertions(+), 18 deletions(-)
create mode 100644 ocl_web/static/css/bootstrap-multiselect.css
create mode 100644 ocl_web/static/js/bootstrap-multiselect.js
create mode 100644 ocl_web/static/js/springy.js
create mode 100755 ocl_web/static/js/springyui.js
create mode 100644 ocl_web/templates/concepts/concept_relationship.html
diff --git a/ocl_web/apps/concepts/views.py b/ocl_web/apps/concepts/views.py
index fc9f8f4d..4a16917f 100644
--- a/ocl_web/apps/concepts/views.py
+++ b/ocl_web/apps/concepts/views.py
@@ -39,6 +39,9 @@ def get_concept_details(self, owner_type, owner_id, source_id, concept_id,
""" Get the concept details. """
# TODO(paynejd@gmail.com): Validate input parameters
+ print('source_version_id: \n', source_version_id)
+ print('concept_version_id: \n', concept_version_id)
+
# Setup request parameters
params = {}
if include_mappings:
@@ -54,18 +57,21 @@ def get_concept_details(self, owner_type, owner_id, source_id, concept_id,
raise ValueError(
'Must specify only a source version or a concept version. Both were specified.')
elif source_version_id:
+ print('11111')
search_response = api.get(
owner_type, owner_id,
'sources', source_id, source_version_id,
'concepts', concept_id,
params=params)
elif concept_version_id:
+ print('22222')
search_response = api.get(
owner_type, owner_id,
'sources', source_id,
'concepts', concept_id, concept_version_id,
params=params)
else:
+ print('33333')
search_response = api.get(
owner_type, owner_id,
'sources', source_id,
@@ -76,8 +82,8 @@ def get_concept_details(self, owner_type, owner_id, source_id, concept_id,
elif search_response.status_code != 200:
search_response.raise_for_status()
- # print('search_response: ', search_response.json())
- # print('search_response type: ', type(search_response))
+ # print('search_response:\n ', search_response.json())
+ # print('search_response type: ', type(search_response))
# print('search_response json type: ', type(search_response.json()))
return search_response.json()
@@ -133,7 +139,9 @@ def get_context_data(self, *args, **kwargs):
source_version_id=self.source_version_id, concept_version_id=self.concept_version_id,
include_mappings=True, include_inverse_mappings=True)
- print('concept type: ', type(concept));
+ print('concept type: ', type(concept))
+ print('source_version_id: \n', self.source_version_id)
+ print('concept_version_id: \n', self.concept_version_id)
concept['has_direct_mappings'] = False
concept['has_inverse_mappings'] = False
@@ -386,6 +394,81 @@ def form_valid(self, form, *args, **kwargs):
return super(ConceptMappingsView, self).form_invalid(form)
+class ConceptRelationshipView(UserOrOrgMixin, ConceptReadBaseView):
+ template_name = "concepts/concept_relationship.html"
+
+ def get_context_data(self, *args, **kwargs):
+ """
+ Loads the concept details.
+ """
+ # Setup the context and args
+ context = super(ConceptRelationshipView, self).get_context_data(*args, **kwargs)
+ self.get_args()
+
+ api = OclApi(self.request, debug=True, facets=True)
+
+ selected_sources = self.request.GET.getlist('selected_source')
+ print('selected_sources: ', selected_sources)
+
+ print(len(selected_sources))
+
+ mappings = []
+
+ # Load the concept details
+ concept = self.get_concept_details(
+ self.owner_type, self.owner_id, self.source_id, self.concept_id,
+ source_version_id=self.source_version_id, concept_version_id=self.concept_version_id,
+ include_mappings=True, include_inverse_mappings=True)
+
+ mappings.extend(concept['mappings'])
+
+ if len(selected_sources) != 0:
+ for source_id in selected_sources:
+ search_response = api.get(self.owner_type, self.owner_id, 'sources', source_id, 'mappings')
+ for mapping in search_response.json()['results']:
+ if (self.proper_owner_type == mapping['to_source_owner_type'] and
+ self.owner_id == mapping['to_source_owner'] and
+ self.source_id == mapping['to_source_name'] and
+ self.concept_id == mapping['to_concept_code']):
+ mapping['is_inverse_mapping'] = True
+ concept['has_inverse_mappings'] = True
+ mapping['is_direct_mapping'] = False
+ else:
+ mapping['is_direct_mapping'] = True
+ mapping['is_inverse_mapping'] = False
+ concept['has_direct_mappings'] = True
+ if mapping['to_concept_url']:
+ mapping['is_internal_mapping'] = True
+ mapping['is_external_mapping'] = False
+ else:
+ mapping['is_internal_mapping'] = False
+ mapping['is_external_mapping'] = True
+
+ print('search_response : ', mapping)
+ mappings.extend(search_response.json()['results'])
+ print('\n\n')
+
+ if self.request.user.is_authenticated():
+ context['all_collections'] = api.get_all_collections_for_user(self.request.user.username)
+
+ all_sources = _get_org_or_user_sources_list2(self.request, str(self.request.user))
+
+ print('mappings: ', mappings)
+ print('\n\n')
+
+ # Set the context
+ context['kwargs'] = self.kwargs
+ context['url_params'] = self.request.GET
+ context['selected_tab'] = 'Relationship'
+ context['concept'] = concept
+ context['mappings'] = json.dumps(mappings)
+ context['all_sources'] = all_sources
+
+ print('\n ConceptRelationshipView concept: ', concept)
+
+ return context
+
+
# CLEAN
class ConceptHistoryView(UserOrOrgMixin, ConceptReadBaseView):
"""
diff --git a/ocl_web/apps/sources/views.py b/ocl_web/apps/sources/views.py
index 9ea68b98..5e8c4ee8 100644
--- a/ocl_web/apps/sources/views.py
+++ b/ocl_web/apps/sources/views.py
@@ -27,7 +27,6 @@
logger = logging.getLogger('oclweb')
-
class SourceReadBaseView(TemplateView):
""" Base class for Source Read views. """
@@ -181,7 +180,6 @@ def get_source_extrefs(self, owner_type, owner_id, source_id,
return searcher
-
class SourceDetailsView(UserOrOrgMixin, SourceReadBaseView):
""" Source Details view. """
template_name = "sources/source_details.html"
@@ -205,7 +203,6 @@ def get_context_data(self, *args, **kwargs):
return context
-
class SourceAboutView(UserOrOrgMixin, SourceReadBaseView):
""" Source About view. """
template_name = "sources/source_about.html"
@@ -238,7 +235,6 @@ def get_context_data(self, *args, **kwargs):
return context
-
class SourceConceptsView(UserOrOrgMixin, SourceReadBaseView):
""" Source Concepts view. """
template_name = "sources/source_concepts.html"
@@ -338,7 +334,6 @@ def get(self, request, *args, **kwargs):
return super(SourceConceptsView, self).get(self, *args, **kwargs)
-
class SourceMappingsView(UserOrOrgMixin, SourceReadBaseView):
""" Source Mappings view. """
template_name = "sources/source_mappings.html"
@@ -434,7 +429,6 @@ def get(self, request, *args, **kwargs):
return super(SourceMappingsView, self).get(self, *args, **kwargs)
-
class SourceExternalReferencesView(UserOrOrgMixin, SourceReadBaseView):
""" Source External References view. """
template_name = "sources/source_extrefs.html"
@@ -497,7 +491,6 @@ def get_context_data(self, *args, **kwargs):
return context
-
class SourceVersionsView(UserOrOrgMixin, SourceReadBaseView):
""" Source Versions view. """
template_name = "sources/source_versions.html"
@@ -552,7 +545,6 @@ def get(self, request, *args, **kwargs):
return super(SourceVersionsView, self).get(self, *args, **kwargs)
-
class SourceVersionsNewView(LoginRequiredMixin, UserOrOrgMixin, FormView):
""" View to Create new source version """
form_class = SourceVersionsNewForm
@@ -638,7 +630,6 @@ def form_valid(self, form):
return HttpResponseRedirect(self.request.path)
-
class SourceVersionsEditView(LoginRequiredMixin, UserOrOrgMixin, FormView):
""" View to edit source version """
form_class = SourceVersionsEditForm
@@ -702,7 +693,6 @@ def form_valid(self, form):
return HttpResponseRedirect(self.request.path)
-
class SourceVersionsRetireView(LoginRequiredMixin, UserOrOrgMixin, FormView):
""" View to retire source version """
form_class = SourceVersionsRetireForm
@@ -713,7 +703,6 @@ def get_initial(self):
pass
-
class SourceNewView(LoginRequiredMixin, UserOrOrgMixin, FormView):
""" View to create new source """
form_class = SourceNewForm
@@ -797,7 +786,6 @@ def form_valid(self, form):
return HttpResponseRedirect(self.request.path)
-
class SourceEditView(UserOrOrgMixin, FormView):
""" Edit source, either for an org or a user. """
template_name = "sources/source_edit.html"
@@ -937,7 +925,6 @@ def form_valid(self, form, *args, **kwargs):
return HttpResponseRedirect(self.get_success_url())
-
class SourceVersionEditJsonView(UserOrOrgMixin, TemplateView):
def put(self, request, *args, **kwargs):
api = OclApi(self.request, debug=True)
@@ -959,7 +946,6 @@ def put(self, request, *args, **kwargs):
return HttpResponse(res.content, status=res.status_code)
-
class SourceVersionDeleteView(UserOrOrgMixin, TemplateView):
""" source version delete view"""
diff --git a/ocl_web/config/users_urls.py b/ocl_web/config/users_urls.py
index 83dab14b..80f8bec3 100644
--- a/ocl_web/config/users_urls.py
+++ b/ocl_web/config/users_urls.py
@@ -21,7 +21,7 @@
SourceNewView, SourceEditView, SourceVersionsView, SourceExternalReferencesView,
SourceVersionsNewView, SourceVersionsEditView, SourceVersionsRetireView, SourceDeleteView, SourceVersionDeleteView, SourceVersionEditJsonView)
from apps.concepts.views import (
- ConceptDetailsView, ConceptMappingsView, ConceptHistoryView, ConceptEditView, ConceptDiffView,
+ ConceptDetailsView, ConceptMappingsView, ConceptHistoryView, ConceptRelationshipView, ConceptEditView, ConceptDiffView,
ConceptRetireView, ConceptNewView, ConceptForkView, ConceptDescView, ConceptNameView)
from apps.mappings.views import (
MappingDetailsView, MappingNewView, MappingForkView, MappingEditView, MappingRetireView, MappingVersionsView,
@@ -166,6 +166,10 @@
url(r'^(?P
[a-zA-Z0-9\-\.]+)/sources/(?P[a-zA-Z0-9\-\.]+)/concepts/(?P[a-zA-Z0-9\-\.]+)/history/$', # pylint: disable=C0301
ConceptHistoryView.as_view(), name='concept-history'),
+ # /users/:user/sources/:source/concepts/:concept/relationship/
+ url(r'^(?P[a-zA-Z0-9\-\.]+)/sources/(?P[a-zA-Z0-9\-\.]+)/concepts/(?P[a-zA-Z0-9\-\.]+)/relationship/$', # pylint: disable=C0301
+ ConceptRelationshipView.as_view(), name='concept-relationship'),
+
# /users/:user/sources/:source/concepts/:concept/diff/
url(r'^(?P[a-zA-Z0-9\-\.]+)/sources/(?P[a-zA-Z0-9\-\.]+)/concepts/(?P[a-zA-Z0-9\-\.]+)/diff/$', # pylint: disable=C0301
ConceptDiffView.as_view(), name='concept-version-diff'),
diff --git a/ocl_web/static/css/bootstrap-multiselect.css b/ocl_web/static/css/bootstrap-multiselect.css
new file mode 100644
index 00000000..5acaf9f7
--- /dev/null
+++ b/ocl_web/static/css/bootstrap-multiselect.css
@@ -0,0 +1 @@
+span.multiselect-native-select{position:relative}span.multiselect-native-select select{border:0!important;clip:rect(0 0 0 0)!important;height:1px!important;margin:-1px -1px -1px -3px!important;overflow:hidden!important;padding:0!important;position:absolute!important;width:1px!important;left:50%;top:30px}.multiselect-container{position:absolute;list-style-type:none;margin:0;padding:0}.multiselect-container .input-group{margin:5px}.multiselect-container>li{padding:0}.multiselect-container>li>a.multiselect-all label{font-weight:700}.multiselect-container>li.multiselect-group label{margin:0;padding:3px 20px 3px 20px;height:100%;font-weight:700}.multiselect-container>li.multiselect-group-clickable label{cursor:pointer}.multiselect-container>li>a{padding:0}.multiselect-container>li>a>label{margin:0;height:100%;cursor:pointer;font-weight:400;padding:3px 20px 3px 40px}.multiselect-container>li>a>label.radio,.multiselect-container>li>a>label.checkbox{margin:0}.multiselect-container>li>a>label>input[type=checkbox]{margin-bottom:5px}.btn-group>.btn-group:nth-child(2)>.multiselect.btn{border-top-left-radius:4px;border-bottom-left-radius:4px}.form-inline .multiselect-container label.checkbox,.form-inline .multiselect-container label.radio{padding:3px 20px 3px 40px}.form-inline .multiselect-container li a label.checkbox input[type=checkbox],.form-inline .multiselect-container li a label.radio input[type=radio]{margin-left:-20px;margin-right:0}
diff --git a/ocl_web/static/js/bootstrap-multiselect.js b/ocl_web/static/js/bootstrap-multiselect.js
new file mode 100644
index 00000000..9a50a18a
--- /dev/null
+++ b/ocl_web/static/js/bootstrap-multiselect.js
@@ -0,0 +1,1716 @@
+/**
+ * Bootstrap Multiselect (https://github.com/davidstutz/bootstrap-multiselect)
+ *
+ * Apache License, Version 2.0:
+ * Copyright (c) 2012 - 2015 David Stutz
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a
+ * copy of the License at http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ *
+ * BSD 3-Clause License:
+ * Copyright (c) 2012 - 2015 David Stutz
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ * - Neither the name of David Stutz nor the names of its contributors may be
+ * used to endorse or promote products derived from this software without
+ * specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+ * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+!function ($) {
+ "use strict";// jshint ;_;
+
+ if (typeof ko !== 'undefined' && ko.bindingHandlers && !ko.bindingHandlers.multiselect) {
+ ko.bindingHandlers.multiselect = {
+ after: ['options', 'value', 'selectedOptions', 'enable', 'disable'],
+
+ init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
+ var $element = $(element);
+ var config = ko.toJS(valueAccessor());
+
+ $element.multiselect(config);
+
+ if (allBindings.has('options')) {
+ var options = allBindings.get('options');
+ if (ko.isObservable(options)) {
+ ko.computed({
+ read: function() {
+ options();
+ setTimeout(function() {
+ var ms = $element.data('multiselect');
+ if (ms)
+ ms.updateOriginalOptions();//Not sure how beneficial this is.
+ $element.multiselect('rebuild');
+ }, 1);
+ },
+ disposeWhenNodeIsRemoved: element
+ });
+ }
+ }
+
+ //value and selectedOptions are two-way, so these will be triggered even by our own actions.
+ //It needs some way to tell if they are triggered because of us or because of outside change.
+ //It doesn't loop but it's a waste of processing.
+ if (allBindings.has('value')) {
+ var value = allBindings.get('value');
+ if (ko.isObservable(value)) {
+ ko.computed({
+ read: function() {
+ value();
+ setTimeout(function() {
+ $element.multiselect('refresh');
+ }, 1);
+ },
+ disposeWhenNodeIsRemoved: element
+ }).extend({ rateLimit: 100, notifyWhenChangesStop: true });
+ }
+ }
+
+ //Switched from arrayChange subscription to general subscription using 'refresh'.
+ //Not sure performance is any better using 'select' and 'deselect'.
+ if (allBindings.has('selectedOptions')) {
+ var selectedOptions = allBindings.get('selectedOptions');
+ if (ko.isObservable(selectedOptions)) {
+ ko.computed({
+ read: function() {
+ selectedOptions();
+ setTimeout(function() {
+ $element.multiselect('refresh');
+ }, 1);
+ },
+ disposeWhenNodeIsRemoved: element
+ }).extend({ rateLimit: 100, notifyWhenChangesStop: true });
+ }
+ }
+
+ var setEnabled = function (enable) {
+ setTimeout(function () {
+ if (enable)
+ $element.multiselect('enable');
+ else
+ $element.multiselect('disable');
+ });
+ };
+
+ if (allBindings.has('enable')) {
+ var enable = allBindings.get('enable');
+ if (ko.isObservable(enable)) {
+ ko.computed({
+ read: function () {
+ setEnabled(enable());
+ },
+ disposeWhenNodeIsRemoved: element
+ }).extend({ rateLimit: 100, notifyWhenChangesStop: true });
+ } else {
+ setEnabled(enable);
+ }
+ }
+
+ if (allBindings.has('disable')) {
+ var disable = allBindings.get('disable');
+ if (ko.isObservable(disable)) {
+ ko.computed({
+ read: function () {
+ setEnabled(!disable());
+ },
+ disposeWhenNodeIsRemoved: element
+ }).extend({ rateLimit: 100, notifyWhenChangesStop: true });
+ } else {
+ setEnabled(!disable);
+ }
+ }
+
+ ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
+ $element.multiselect('destroy');
+ });
+ },
+
+ update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
+ var $element = $(element);
+ var config = ko.toJS(valueAccessor());
+
+ $element.multiselect('setOptions', config);
+ $element.multiselect('rebuild');
+ }
+ };
+ }
+
+ function forEach(array, callback) {
+ for (var index = 0; index < array.length; ++index) {
+ callback(array[index], index);
+ }
+ }
+
+ /**
+ * Constructor to create a new multiselect using the given select.
+ *
+ * @param {jQuery} select
+ * @param {Object} options
+ * @returns {Multiselect}
+ */
+ function Multiselect(select, options) {
+
+ this.$select = $(select);
+ this.options = this.mergeOptions($.extend({}, options, this.$select.data()));
+
+ // Placeholder via data attributes
+ if (this.$select.attr("data-placeholder")) {
+ this.options.nonSelectedText = this.$select.data("placeholder");
+ }
+
+ // Initialization.
+ // We have to clone to create a new reference.
+ this.originalOptions = this.$select.clone()[0].options;
+ this.query = '';
+ this.searchTimeout = null;
+ this.lastToggledInput = null;
+
+ this.options.multiple = this.$select.attr('multiple') === "multiple";
+ this.options.onChange = $.proxy(this.options.onChange, this);
+ this.options.onSelectAll = $.proxy(this.options.onSelectAll, this);
+ this.options.onDeselectAll = $.proxy(this.options.onDeselectAll, this);
+ this.options.onDropdownShow = $.proxy(this.options.onDropdownShow, this);
+ this.options.onDropdownHide = $.proxy(this.options.onDropdownHide, this);
+ this.options.onDropdownShown = $.proxy(this.options.onDropdownShown, this);
+ this.options.onDropdownHidden = $.proxy(this.options.onDropdownHidden, this);
+ this.options.onInitialized = $.proxy(this.options.onInitialized, this);
+ this.options.onFiltering = $.proxy(this.options.onFiltering, this);
+
+ // Build select all if enabled.
+ this.buildContainer();
+ this.buildButton();
+ this.buildDropdown();
+ this.buildSelectAll();
+ this.buildDropdownOptions();
+ this.buildFilter();
+
+ this.updateButtonText();
+ this.updateSelectAll(true);
+
+ if (this.options.enableClickableOptGroups && this.options.multiple) {
+ this.updateOptGroups();
+ }
+
+ this.options.wasDisabled = this.$select.prop('disabled');
+ if (this.options.disableIfEmpty && $('option', this.$select).length <= 0) {
+ this.disable();
+ }
+
+ this.$select.wrap(' ').after(this.$container);
+ this.options.onInitialized(this.$select, this.$container);
+ }
+
+ Multiselect.prototype = {
+
+ defaults: {
+ /**
+ * Default text function will either print 'None selected' in case no
+ * option is selected or a list of the selected options up to a length
+ * of 3 selected options.
+ *
+ * @param {jQuery} options
+ * @param {jQuery} select
+ * @returns {String}
+ */
+ buttonText: function(options, select) {
+ if (this.disabledText.length > 0
+ && (select.prop('disabled') || (options.length == 0 && this.disableIfEmpty))) {
+
+ return this.disabledText;
+ }
+ else if (options.length === 0) {
+ return this.nonSelectedText;
+ }
+ else if (this.allSelectedText
+ && options.length === $('option', $(select)).length
+ && $('option', $(select)).length !== 1
+ && this.multiple) {
+
+ if (this.selectAllNumber) {
+ return this.allSelectedText + ' (' + options.length + ')';
+ }
+ else {
+ return this.allSelectedText;
+ }
+ }
+ else if (options.length > this.numberDisplayed) {
+ return options.length + ' ' + this.nSelectedText;
+ }
+ else {
+ var selected = '';
+ var delimiter = this.delimiterText;
+
+ options.each(function() {
+ var label = ($(this).attr('label') !== undefined) ? $(this).attr('label') : $(this).text();
+ selected += label + delimiter;
+ });
+
+ return selected.substr(0, selected.length - this.delimiterText.length);
+ }
+ },
+ /**
+ * Updates the title of the button similar to the buttonText function.
+ *
+ * @param {jQuery} options
+ * @param {jQuery} select
+ * @returns {@exp;selected@call;substr}
+ */
+ buttonTitle: function(options, select) {
+ if (options.length === 0) {
+ return this.nonSelectedText;
+ }
+ else {
+ var selected = '';
+ var delimiter = this.delimiterText;
+
+ options.each(function () {
+ var label = ($(this).attr('label') !== undefined) ? $(this).attr('label') : $(this).text();
+ selected += label + delimiter;
+ });
+ return selected.substr(0, selected.length - this.delimiterText.length);
+ }
+ },
+ checkboxName: function(option) {
+ return false; // no checkbox name
+ },
+ /**
+ * Create a label.
+ *
+ * @param {jQuery} element
+ * @returns {String}
+ */
+ optionLabel: function(element){
+ return $(element).attr('label') || $(element).text();
+ },
+ /**
+ * Create a class.
+ *
+ * @param {jQuery} element
+ * @returns {String}
+ */
+ optionClass: function(element) {
+ return $(element).attr('class') || '';
+ },
+ /**
+ * Triggered on change of the multiselect.
+ *
+ * Not triggered when selecting/deselecting options manually.
+ *
+ * @param {jQuery} option
+ * @param {Boolean} checked
+ */
+ onChange : function(option, checked) {
+
+ },
+ /**
+ * Triggered when the dropdown is shown.
+ *
+ * @param {jQuery} event
+ */
+ onDropdownShow: function(event) {
+
+ },
+ /**
+ * Triggered when the dropdown is hidden.
+ *
+ * @param {jQuery} event
+ */
+ onDropdownHide: function(event) {
+
+ },
+ /**
+ * Triggered after the dropdown is shown.
+ *
+ * @param {jQuery} event
+ */
+ onDropdownShown: function(event) {
+
+ },
+ /**
+ * Triggered after the dropdown is hidden.
+ *
+ * @param {jQuery} event
+ */
+ onDropdownHidden: function(event) {
+
+ },
+ /**
+ * Triggered on select all.
+ */
+ onSelectAll: function() {
+
+ },
+ /**
+ * Triggered on deselect all.
+ */
+ onDeselectAll: function() {
+
+ },
+ /**
+ * Triggered after initializing.
+ *
+ * @param {jQuery} $select
+ * @param {jQuery} $container
+ */
+ onInitialized: function($select, $container) {
+
+ },
+ /**
+ * Triggered on filtering.
+ *
+ * @param {jQuery} $filter
+ */
+ onFiltering: function($filter) {
+
+ },
+ enableHTML: false,
+ buttonClass: 'btn btn-default',
+ inheritClass: false,
+ buttonWidth: 'auto',
+ buttonContainer: '
',
+ dropRight: false,
+ dropUp: false,
+ selectedClass: 'active',
+ // Maximum height of the dropdown menu.
+ // If maximum height is exceeded a scrollbar will be displayed.
+ maxHeight: false,
+ includeSelectAllOption: false,
+ includeSelectAllIfMoreThan: 0,
+ selectAllText: ' Select all',
+ selectAllValue: 'multiselect-all',
+ selectAllName: false,
+ selectAllNumber: true,
+ selectAllJustVisible: true,
+ enableFiltering: false,
+ enableCaseInsensitiveFiltering: false,
+ enableFullValueFiltering: false,
+ enableClickableOptGroups: false,
+ enableCollapsibleOptGroups: false,
+ filterPlaceholder: 'Search',
+ // possible options: 'text', 'value', 'both'
+ filterBehavior: 'text',
+ includeFilterClearBtn: true,
+ preventInputChangeEvent: false,
+ nonSelectedText: 'None selected',
+ nSelectedText: 'selected',
+ allSelectedText: 'All selected',
+ numberDisplayed: 3,
+ disableIfEmpty: false,
+ disabledText: '',
+ delimiterText: ', ',
+ templates: {
+ button: ' ',
+ ul: '',
+ filter: '
',
+ filterClearBtn: ' ',
+ li: ' ',
+ divider: ' ',
+ liGroup: ' '
+ }
+ },
+
+ constructor: Multiselect,
+
+ /**
+ * Builds the container of the multiselect.
+ */
+ buildContainer: function() {
+ this.$container = $(this.options.buttonContainer);
+ this.$container.on('show.bs.dropdown', this.options.onDropdownShow);
+ this.$container.on('hide.bs.dropdown', this.options.onDropdownHide);
+ this.$container.on('shown.bs.dropdown', this.options.onDropdownShown);
+ this.$container.on('hidden.bs.dropdown', this.options.onDropdownHidden);
+ },
+
+ /**
+ * Builds the button of the multiselect.
+ */
+ buildButton: function() {
+ this.$button = $(this.options.templates.button).addClass(this.options.buttonClass);
+ if (this.$select.attr('class') && this.options.inheritClass) {
+ this.$button.addClass(this.$select.attr('class'));
+ }
+ // Adopt active state.
+ if (this.$select.prop('disabled')) {
+ this.disable();
+ }
+ else {
+ this.enable();
+ }
+
+ // Manually add button width if set.
+ if (this.options.buttonWidth && this.options.buttonWidth !== 'auto') {
+ this.$button.css({
+ 'width' : '100%', //this.options.buttonWidth,
+ 'overflow' : 'hidden',
+ 'text-overflow' : 'ellipsis'
+ });
+ this.$container.css({
+ 'width': this.options.buttonWidth
+ });
+ }
+
+ // Keep the tab index from the select.
+ var tabindex = this.$select.attr('tabindex');
+ if (tabindex) {
+ this.$button.attr('tabindex', tabindex);
+ }
+
+ this.$container.prepend(this.$button);
+ },
+
+ /**
+ * Builds the ul representing the dropdown menu.
+ */
+ buildDropdown: function() {
+
+ // Build ul.
+ this.$ul = $(this.options.templates.ul);
+
+ if (this.options.dropRight) {
+ this.$ul.addClass('pull-right');
+ }
+
+ // Set max height of dropdown menu to activate auto scrollbar.
+ if (this.options.maxHeight) {
+ // TODO: Add a class for this option to move the css declarations.
+ this.$ul.css({
+ 'max-height': this.options.maxHeight + 'px',
+ 'overflow-y': 'auto',
+ 'overflow-x': 'hidden'
+ });
+ }
+
+ if (this.options.dropUp) {
+
+ var height = Math.min(this.options.maxHeight, $('option[data-role!="divider"]', this.$select).length*26 + $('option[data-role="divider"]', this.$select).length*19 + (this.options.includeSelectAllOption ? 26 : 0) + (this.options.enableFiltering || this.options.enableCaseInsensitiveFiltering ? 44 : 0));
+ var moveCalc = height + 34;
+
+ this.$ul.css({
+ 'max-height': height + 'px',
+ 'overflow-y': 'auto',
+ 'overflow-x': 'hidden',
+ 'margin-top': "-" + moveCalc + 'px'
+ });
+ }
+
+ this.$container.append(this.$ul);
+ },
+
+ /**
+ * Build the dropdown options and binds all necessary events.
+ *
+ * Uses createDivider and createOptionValue to create the necessary options.
+ */
+ buildDropdownOptions: function() {
+
+ this.$select.children().each($.proxy(function(index, element) {
+
+ var $element = $(element);
+ // Support optgroups and options without a group simultaneously.
+ var tag = $element.prop('tagName')
+ .toLowerCase();
+
+ if ($element.prop('value') === this.options.selectAllValue) {
+ return;
+ }
+
+ if (tag === 'optgroup') {
+ this.createOptgroup(element);
+ }
+ else if (tag === 'option') {
+
+ if ($element.data('role') === 'divider') {
+ this.createDivider();
+ }
+ else {
+ this.createOptionValue(element);
+ }
+
+ }
+
+ // Other illegal tags will be ignored.
+ }, this));
+
+ // Bind the change event on the dropdown elements.
+ $('li:not(.multiselect-group) input', this.$ul).on('change', $.proxy(function(event) {
+ var $target = $(event.target);
+
+ var checked = $target.prop('checked') || false;
+ var isSelectAllOption = $target.val() === this.options.selectAllValue;
+
+ // Apply or unapply the configured selected class.
+ if (this.options.selectedClass) {
+ if (checked) {
+ $target.closest('li')
+ .addClass(this.options.selectedClass);
+ }
+ else {
+ $target.closest('li')
+ .removeClass(this.options.selectedClass);
+ }
+ }
+
+ // Get the corresponding option.
+ var value = $target.val();
+ var $option = this.getOptionByValue(value);
+
+ var $optionsNotThis = $('option', this.$select).not($option);
+ var $checkboxesNotThis = $('input', this.$container).not($target);
+
+ if (isSelectAllOption) {
+
+ if (checked) {
+ this.selectAll(this.options.selectAllJustVisible, true);
+ }
+ else {
+ this.deselectAll(this.options.selectAllJustVisible, true);
+ }
+ }
+ else {
+ if (checked) {
+ $option.prop('selected', true);
+
+ if (this.options.multiple) {
+ // Simply select additional option.
+ $option.prop('selected', true);
+ }
+ else {
+ // Unselect all other options and corresponding checkboxes.
+ if (this.options.selectedClass) {
+ $($checkboxesNotThis).closest('li').removeClass(this.options.selectedClass);
+ }
+
+ $($checkboxesNotThis).prop('checked', false);
+ $optionsNotThis.prop('selected', false);
+
+ // It's a single selection, so close.
+ this.$button.click();
+ }
+
+ if (this.options.selectedClass === "active") {
+ $optionsNotThis.closest("a").css("outline", "");
+ }
+ }
+ else {
+ // Unselect option.
+ $option.prop('selected', false);
+ }
+
+ // To prevent select all from firing onChange: #575
+ this.options.onChange($option, checked);
+
+ // Do not update select all or optgroups on select all change!
+ this.updateSelectAll();
+
+ if (this.options.enableClickableOptGroups && this.options.multiple) {
+ this.updateOptGroups();
+ }
+ }
+
+ this.$select.change();
+ this.updateButtonText();
+
+ if(this.options.preventInputChangeEvent) {
+ return false;
+ }
+ }, this));
+
+ $('li a', this.$ul).on('mousedown', function(e) {
+ if (e.shiftKey) {
+ // Prevent selecting text by Shift+click
+ return false;
+ }
+ });
+
+ $('li a', this.$ul).on('touchstart click', $.proxy(function(event) {
+ event.stopPropagation();
+
+ var $target = $(event.target);
+
+ if (event.shiftKey && this.options.multiple) {
+ if($target.is("label")){ // Handles checkbox selection manually (see https://github.com/davidstutz/bootstrap-multiselect/issues/431)
+ event.preventDefault();
+ $target = $target.find("input");
+ $target.prop("checked", !$target.prop("checked"));
+ }
+ var checked = $target.prop('checked') || false;
+
+ if (this.lastToggledInput !== null && this.lastToggledInput !== $target) { // Make sure we actually have a range
+ var from = $target.closest("li").index();
+ var to = this.lastToggledInput.closest("li").index();
+
+ if (from > to) { // Swap the indices
+ var tmp = to;
+ to = from;
+ from = tmp;
+ }
+
+ // Make sure we grab all elements since slice excludes the last index
+ ++to;
+
+ // Change the checkboxes and underlying options
+ var range = this.$ul.find("li").slice(from, to).find("input");
+
+ range.prop('checked', checked);
+
+ if (this.options.selectedClass) {
+ range.closest('li')
+ .toggleClass(this.options.selectedClass, checked);
+ }
+
+ for (var i = 0, j = range.length; i < j; i++) {
+ var $checkbox = $(range[i]);
+
+ var $option = this.getOptionByValue($checkbox.val());
+
+ $option.prop('selected', checked);
+ }
+ }
+
+ // Trigger the select "change" event
+ $target.trigger("change");
+ }
+
+ // Remembers last clicked option
+ if($target.is("input") && !$target.closest("li").is(".multiselect-item")){
+ this.lastToggledInput = $target;
+ }
+
+ $target.blur();
+ }, this));
+
+ // Keyboard support.
+ this.$container.off('keydown.multiselect').on('keydown.multiselect', $.proxy(function(event) {
+ if ($('input[type="text"]', this.$container).is(':focus')) {
+ return;
+ }
+
+ if (event.keyCode === 9 && this.$container.hasClass('open')) {
+ this.$button.click();
+ }
+ else {
+ var $items = $(this.$container).find("li:not(.divider):not(.disabled) a").filter(":visible");
+
+ if (!$items.length) {
+ return;
+ }
+
+ var index = $items.index($items.filter(':focus'));
+
+ // Navigation up.
+ if (event.keyCode === 38 && index > 0) {
+ index--;
+ }
+ // Navigate down.
+ else if (event.keyCode === 40 && index < $items.length - 1) {
+ index++;
+ }
+ else if (!~index) {
+ index = 0;
+ }
+
+ var $current = $items.eq(index);
+ $current.focus();
+
+ if (event.keyCode === 32 || event.keyCode === 13) {
+ var $checkbox = $current.find('input');
+
+ $checkbox.prop("checked", !$checkbox.prop("checked"));
+ $checkbox.change();
+ }
+
+ event.stopPropagation();
+ event.preventDefault();
+ }
+ }, this));
+
+ if (this.options.enableClickableOptGroups && this.options.multiple) {
+ $("li.multiselect-group input", this.$ul).on("change", $.proxy(function(event) {
+ event.stopPropagation();
+
+ var $target = $(event.target);
+ var checked = $target.prop('checked') || false;
+
+ var $li = $(event.target).closest('li');
+ var $group = $li.nextUntil("li.multiselect-group")
+ .not('.multiselect-filter-hidden')
+ .not('.disabled');
+
+ var $inputs = $group.find("input");
+
+ var values = [];
+ var $options = [];
+
+ if (this.options.selectedClass) {
+ if (checked) {
+ $li.addClass(this.options.selectedClass);
+ }
+ else {
+ $li.removeClass(this.options.selectedClass);
+ }
+ }
+
+ $.each($inputs, $.proxy(function(index, input) {
+ var value = $(input).val();
+ var $option = this.getOptionByValue(value);
+
+ if (checked) {
+ $(input).prop('checked', true);
+ $(input).closest('li')
+ .addClass(this.options.selectedClass);
+
+ $option.prop('selected', true);
+ }
+ else {
+ $(input).prop('checked', false);
+ $(input).closest('li')
+ .removeClass(this.options.selectedClass);
+
+ $option.prop('selected', false);
+ }
+
+ $options.push(this.getOptionByValue(value));
+ }, this))
+
+ // Cannot use select or deselect here because it would call updateOptGroups again.
+
+ this.options.onChange($options, checked);
+
+ this.updateButtonText();
+ this.updateSelectAll();
+ }, this));
+ }
+
+ if (this.options.enableCollapsibleOptGroups && this.options.multiple) {
+ $("li.multiselect-group .caret-container", this.$ul).on("click", $.proxy(function(event) {
+ var $li = $(event.target).closest('li');
+ var $inputs = $li.nextUntil("li.multiselect-group")
+ .not('.multiselect-filter-hidden');
+
+ var visible = true;
+ $inputs.each(function() {
+ visible = visible && $(this).is(':visible');
+ });
+
+ if (visible) {
+ $inputs.hide()
+ .addClass('multiselect-collapsible-hidden');
+ }
+ else {
+ $inputs.show()
+ .removeClass('multiselect-collapsible-hidden');
+ }
+ }, this));
+
+ $("li.multiselect-all", this.$ul).css('background', '#f3f3f3').css('border-bottom', '1px solid #eaeaea');
+ $("li.multiselect-all > a > label.checkbox", this.$ul).css('padding', '3px 20px 3px 35px');
+ $("li.multiselect-group > a > input", this.$ul).css('margin', '4px 0px 5px -20px');
+ }
+ },
+
+ /**
+ * Create an option using the given select option.
+ *
+ * @param {jQuery} element
+ */
+ createOptionValue: function(element) {
+ var $element = $(element);
+ if ($element.is(':selected')) {
+ $element.prop('selected', true);
+ }
+
+ // Support the label attribute on options.
+ var label = this.options.optionLabel(element);
+ var classes = this.options.optionClass(element);
+ var value = $element.val();
+ var inputType = this.options.multiple ? "checkbox" : "radio";
+
+ var $li = $(this.options.templates.li);
+ var $label = $('label', $li);
+ $label.addClass(inputType);
+ $li.addClass(classes);
+
+ if (this.options.enableHTML) {
+ $label.html(" " + label);
+ }
+ else {
+ $label.text(" " + label);
+ }
+
+ var $checkbox = $(' ').attr('type', inputType);
+
+ var name = this.options.checkboxName($element);
+ if (name) {
+ $checkbox.attr('name', name);
+ }
+
+ $label.prepend($checkbox);
+
+ var selected = $element.prop('selected') || false;
+ $checkbox.val(value);
+
+ if (value === this.options.selectAllValue) {
+ $li.addClass("multiselect-item multiselect-all");
+ $checkbox.parent().parent()
+ .addClass('multiselect-all');
+ }
+
+ $label.attr('title', $element.attr('title'));
+
+ this.$ul.append($li);
+
+ if ($element.is(':disabled')) {
+ $checkbox.attr('disabled', 'disabled')
+ .prop('disabled', true)
+ .closest('a')
+ .attr("tabindex", "-1")
+ .closest('li')
+ .addClass('disabled');
+ }
+
+ $checkbox.prop('checked', selected);
+
+ if (selected && this.options.selectedClass) {
+ $checkbox.closest('li')
+ .addClass(this.options.selectedClass);
+ }
+ },
+
+ /**
+ * Creates a divider using the given select option.
+ *
+ * @param {jQuery} element
+ */
+ createDivider: function(element) {
+ var $divider = $(this.options.templates.divider);
+ this.$ul.append($divider);
+ },
+
+ /**
+ * Creates an optgroup.
+ *
+ * @param {jQuery} group
+ */
+ createOptgroup: function(group) {
+ var label = $(group).attr("label");
+ var value = $(group).attr("value");
+ var $li = $(' ');
+
+ var classes = this.options.optionClass(group);
+ $li.addClass(classes);
+
+ if (this.options.enableHTML) {
+ $('label b', $li).html(" " + label);
+ }
+ else {
+ $('label b', $li).text(" " + label);
+ }
+
+ if (this.options.enableCollapsibleOptGroups && this.options.multiple) {
+ $('a', $li).append(' ');
+ }
+
+ if (this.options.enableClickableOptGroups && this.options.multiple) {
+ $('a label', $li).prepend(' ');
+ }
+
+ if ($(group).is(':disabled')) {
+ $li.addClass('disabled');
+ }
+
+ this.$ul.append($li);
+
+ $("option", group).each($.proxy(function($, group) {
+ this.createOptionValue(group);
+ }, this))
+ },
+
+ /**
+ * Build the select all.
+ *
+ * Checks if a select all has already been created.
+ */
+ buildSelectAll: function() {
+ if (typeof this.options.selectAllValue === 'number') {
+ this.options.selectAllValue = this.options.selectAllValue.toString();
+ }
+
+ var alreadyHasSelectAll = this.hasSelectAll();
+
+ if (!alreadyHasSelectAll && this.options.includeSelectAllOption && this.options.multiple
+ && $('option', this.$select).length > this.options.includeSelectAllIfMoreThan) {
+
+ // Check whether to add a divider after the select all.
+ if (this.options.includeSelectAllDivider) {
+ this.$ul.prepend($(this.options.templates.divider));
+ }
+
+ var $li = $(this.options.templates.li);
+ $('label', $li).addClass("checkbox");
+
+ if (this.options.enableHTML) {
+ $('label', $li).html(" " + this.options.selectAllText);
+ }
+ else {
+ $('label', $li).text(" " + this.options.selectAllText);
+ }
+
+ if (this.options.selectAllName) {
+ $('label', $li).prepend(' ');
+ }
+ else {
+ $('label', $li).prepend(' ');
+ }
+
+ var $checkbox = $('input', $li);
+ $checkbox.val(this.options.selectAllValue);
+
+ $li.addClass("multiselect-item multiselect-all");
+ $checkbox.parent().parent()
+ .addClass('multiselect-all');
+
+ this.$ul.prepend($li);
+
+ $checkbox.prop('checked', false);
+ }
+ },
+
+ /**
+ * Builds the filter.
+ */
+ buildFilter: function() {
+
+ // Build filter if filtering OR case insensitive filtering is enabled and the number of options exceeds (or equals) enableFilterLength.
+ if (this.options.enableFiltering || this.options.enableCaseInsensitiveFiltering) {
+ var enableFilterLength = Math.max(this.options.enableFiltering, this.options.enableCaseInsensitiveFiltering);
+
+ if (this.$select.find('option').length >= enableFilterLength) {
+
+ this.$filter = $(this.options.templates.filter);
+ $('input', this.$filter).attr('placeholder', this.options.filterPlaceholder);
+
+ // Adds optional filter clear button
+ if(this.options.includeFilterClearBtn) {
+ var clearBtn = $(this.options.templates.filterClearBtn);
+ clearBtn.on('click', $.proxy(function(event){
+ clearTimeout(this.searchTimeout);
+
+ this.$filter.find('.multiselect-search').val('');
+ $('li', this.$ul).show().removeClass('multiselect-filter-hidden');
+
+ this.updateSelectAll();
+
+ if (this.options.enableClickableOptGroups && this.options.multiple) {
+ this.updateOptGroups();
+ }
+
+ }, this));
+ this.$filter.find('.input-group').append(clearBtn);
+ }
+
+ this.$ul.prepend(this.$filter);
+
+ this.$filter.val(this.query).on('click', function(event) {
+ event.stopPropagation();
+ }).on('input keydown', $.proxy(function(event) {
+ // Cancel enter key default behaviour
+ if (event.which === 13) {
+ event.preventDefault();
+ }
+
+ // This is useful to catch "keydown" events after the browser has updated the control.
+ clearTimeout(this.searchTimeout);
+
+ this.searchTimeout = this.asyncFunction($.proxy(function() {
+
+ if (this.query !== event.target.value) {
+ this.query = event.target.value;
+
+ var currentGroup, currentGroupVisible;
+ $.each($('li', this.$ul), $.proxy(function(index, element) {
+ var value = $('input', element).length > 0 ? $('input', element).val() : "";
+ var text = $('label', element).text();
+
+ var filterCandidate = '';
+ if ((this.options.filterBehavior === 'text')) {
+ filterCandidate = text;
+ }
+ else if ((this.options.filterBehavior === 'value')) {
+ filterCandidate = value;
+ }
+ else if (this.options.filterBehavior === 'both') {
+ filterCandidate = text + '\n' + value;
+ }
+
+ if (value !== this.options.selectAllValue && text) {
+
+ // By default lets assume that element is not
+ // interesting for this search.
+ var showElement = false;
+
+ if (this.options.enableCaseInsensitiveFiltering) {
+ filterCandidate = filterCandidate.toLowerCase();
+ this.query = this.query.toLowerCase();
+ }
+
+ if (this.options.enableFullValueFiltering && this.options.filterBehavior !== 'both') {
+ var valueToMatch = filterCandidate.trim().substring(0, this.query.length);
+ if (this.query.indexOf(valueToMatch) > -1) {
+ showElement = true;
+ }
+ }
+ else if (filterCandidate.indexOf(this.query) > -1) {
+ showElement = true;
+ }
+
+ // Toggle current element (group or group item) according to showElement boolean.
+ $(element).toggle(showElement)
+ .toggleClass('multiselect-filter-hidden', !showElement);
+
+ // Differentiate groups and group items.
+ if ($(element).hasClass('multiselect-group')) {
+ // Remember group status.
+ currentGroup = element;
+ currentGroupVisible = showElement;
+ }
+ else {
+ // Show group name when at least one of its items is visible.
+ if (showElement) {
+ $(currentGroup).show()
+ .removeClass('multiselect-filter-hidden');
+ }
+
+ // Show all group items when group name satisfies filter.
+ if (!showElement && currentGroupVisible) {
+ $(element).show()
+ .removeClass('multiselect-filter-hidden');
+ }
+ }
+ }
+ }, this));
+ }
+
+ this.updateSelectAll();
+
+ if (this.options.enableClickableOptGroups && this.options.multiple) {
+ this.updateOptGroups();
+ }
+
+ this.options.onFiltering(event.target);
+
+ }, this), 300, this);
+ }, this));
+ }
+ }
+ },
+
+ /**
+ * Unbinds the whole plugin.
+ */
+ destroy: function() {
+ this.$container.remove();
+ this.$select.show();
+
+ // reset original state
+ this.$select.prop('disabled', this.options.wasDisabled);
+
+ this.$select.data('multiselect', null);
+ },
+
+ /**
+ * Refreshs the multiselect based on the selected options of the select.
+ */
+ refresh: function () {
+ var inputs = $.map($('li input', this.$ul), $);
+
+ $('option', this.$select).each($.proxy(function (index, element) {
+ var $elem = $(element);
+ var value = $elem.val();
+ var $input;
+ for (var i = inputs.length; 0 < i--; /**/) {
+ if (value !== ($input = inputs[i]).val())
+ continue; // wrong li
+
+ if ($elem.is(':selected')) {
+ $input.prop('checked', true);
+
+ if (this.options.selectedClass) {
+ $input.closest('li')
+ .addClass(this.options.selectedClass);
+ }
+ }
+ else {
+ $input.prop('checked', false);
+
+ if (this.options.selectedClass) {
+ $input.closest('li')
+ .removeClass(this.options.selectedClass);
+ }
+ }
+
+ if ($elem.is(":disabled")) {
+ $input.attr('disabled', 'disabled')
+ .prop('disabled', true)
+ .closest('li')
+ .addClass('disabled');
+ }
+ else {
+ $input.prop('disabled', false)
+ .closest('li')
+ .removeClass('disabled');
+ }
+ break; // assumes unique values
+ }
+ }, this));
+
+ this.updateButtonText();
+ this.updateSelectAll();
+
+ if (this.options.enableClickableOptGroups && this.options.multiple) {
+ this.updateOptGroups();
+ }
+ },
+
+ /**
+ * Select all options of the given values.
+ *
+ * If triggerOnChange is set to true, the on change event is triggered if
+ * and only if one value is passed.
+ *
+ * @param {Array} selectValues
+ * @param {Boolean} triggerOnChange
+ */
+ select: function(selectValues, triggerOnChange) {
+ if(!$.isArray(selectValues)) {
+ selectValues = [selectValues];
+ }
+
+ for (var i = 0; i < selectValues.length; i++) {
+ var value = selectValues[i];
+
+ if (value === null || value === undefined) {
+ continue;
+ }
+
+ var $option = this.getOptionByValue(value);
+ var $checkbox = this.getInputByValue(value);
+
+ if($option === undefined || $checkbox === undefined) {
+ continue;
+ }
+
+ if (!this.options.multiple) {
+ this.deselectAll(false);
+ }
+
+ if (this.options.selectedClass) {
+ $checkbox.closest('li')
+ .addClass(this.options.selectedClass);
+ }
+
+ $checkbox.prop('checked', true);
+ $option.prop('selected', true);
+
+ if (triggerOnChange) {
+ this.options.onChange($option, true);
+ }
+ }
+
+ this.updateButtonText();
+ this.updateSelectAll();
+
+ if (this.options.enableClickableOptGroups && this.options.multiple) {
+ this.updateOptGroups();
+ }
+ },
+
+ /**
+ * Clears all selected items.
+ */
+ clearSelection: function () {
+ this.deselectAll(false);
+ this.updateButtonText();
+ this.updateSelectAll();
+
+ if (this.options.enableClickableOptGroups && this.options.multiple) {
+ this.updateOptGroups();
+ }
+ },
+
+ /**
+ * Deselects all options of the given values.
+ *
+ * If triggerOnChange is set to true, the on change event is triggered, if
+ * and only if one value is passed.
+ *
+ * @param {Array} deselectValues
+ * @param {Boolean} triggerOnChange
+ */
+ deselect: function(deselectValues, triggerOnChange) {
+ if(!$.isArray(deselectValues)) {
+ deselectValues = [deselectValues];
+ }
+
+ for (var i = 0; i < deselectValues.length; i++) {
+ var value = deselectValues[i];
+
+ if (value === null || value === undefined) {
+ continue;
+ }
+
+ var $option = this.getOptionByValue(value);
+ var $checkbox = this.getInputByValue(value);
+
+ if($option === undefined || $checkbox === undefined) {
+ continue;
+ }
+
+ if (this.options.selectedClass) {
+ $checkbox.closest('li')
+ .removeClass(this.options.selectedClass);
+ }
+
+ $checkbox.prop('checked', false);
+ $option.prop('selected', false);
+
+ if (triggerOnChange) {
+ this.options.onChange($option, false);
+ }
+ }
+
+ this.updateButtonText();
+ this.updateSelectAll();
+
+ if (this.options.enableClickableOptGroups && this.options.multiple) {
+ this.updateOptGroups();
+ }
+ },
+
+ /**
+ * Selects all enabled & visible options.
+ *
+ * If justVisible is true or not specified, only visible options are selected.
+ *
+ * @param {Boolean} justVisible
+ * @param {Boolean} triggerOnSelectAll
+ */
+ selectAll: function (justVisible, triggerOnSelectAll) {
+
+ var justVisible = typeof justVisible === 'undefined' ? true : justVisible;
+ var allLis = $("li:not(.divider):not(.disabled):not(.multiselect-group)", this.$ul);
+ var visibleLis = $("li:not(.divider):not(.disabled):not(.multiselect-group):not(.multiselect-filter-hidden):not(.multiselect-collapisble-hidden)", this.$ul).filter(':visible');
+
+ if(justVisible) {
+ $('input:enabled' , visibleLis).prop('checked', true);
+ visibleLis.addClass(this.options.selectedClass);
+
+ $('input:enabled' , visibleLis).each($.proxy(function(index, element) {
+ var value = $(element).val();
+ var option = this.getOptionByValue(value);
+ $(option).prop('selected', true);
+ }, this));
+ }
+ else {
+ $('input:enabled' , allLis).prop('checked', true);
+ allLis.addClass(this.options.selectedClass);
+
+ $('input:enabled' , allLis).each($.proxy(function(index, element) {
+ var value = $(element).val();
+ var option = this.getOptionByValue(value);
+ $(option).prop('selected', true);
+ }, this));
+ }
+
+ $('li input[value="' + this.options.selectAllValue + '"]', this.$ul).prop('checked', true);
+
+ if (this.options.enableClickableOptGroups && this.options.multiple) {
+ this.updateOptGroups();
+ }
+
+ if (triggerOnSelectAll) {
+ this.options.onSelectAll();
+ }
+ },
+
+ /**
+ * Deselects all options.
+ *
+ * If justVisible is true or not specified, only visible options are deselected.
+ *
+ * @param {Boolean} justVisible
+ */
+ deselectAll: function (justVisible, triggerOnDeselectAll) {
+
+ var justVisible = typeof justVisible === 'undefined' ? true : justVisible;
+ var allLis = $("li:not(.divider):not(.disabled):not(.multiselect-group)", this.$ul);
+ var visibleLis = $("li:not(.divider):not(.disabled):not(.multiselect-group):not(.multiselect-filter-hidden):not(.multiselect-collapisble-hidden)", this.$ul).filter(':visible');
+
+ if(justVisible) {
+ $('input[type="checkbox"]:enabled' , visibleLis).prop('checked', false);
+ visibleLis.removeClass(this.options.selectedClass);
+
+ $('input[type="checkbox"]:enabled' , visibleLis).each($.proxy(function(index, element) {
+ var value = $(element).val();
+ var option = this.getOptionByValue(value);
+ $(option).prop('selected', false);
+ }, this));
+ }
+ else {
+ $('input[type="checkbox"]:enabled' , allLis).prop('checked', false);
+ allLis.removeClass(this.options.selectedClass);
+
+ $('input[type="checkbox"]:enabled' , allLis).each($.proxy(function(index, element) {
+ var value = $(element).val();
+ var option = this.getOptionByValue(value);
+ $(option).prop('selected', false);
+ }, this));
+ }
+
+ $('li input[value="' + this.options.selectAllValue + '"]', this.$ul).prop('checked', false);
+
+ if (this.options.enableClickableOptGroups && this.options.multiple) {
+ this.updateOptGroups();
+ }
+
+ if (triggerOnDeselectAll) {
+ this.options.onDeselectAll();
+ }
+ },
+
+ /**
+ * Rebuild the plugin.
+ *
+ * Rebuilds the dropdown, the filter and the select all option.
+ */
+ rebuild: function() {
+ this.$ul.html('');
+
+ // Important to distinguish between radios and checkboxes.
+ this.options.multiple = this.$select.attr('multiple') === "multiple";
+
+ this.buildSelectAll();
+ this.buildDropdownOptions();
+ this.buildFilter();
+
+ this.updateButtonText();
+ this.updateSelectAll(true);
+
+ if (this.options.enableClickableOptGroups && this.options.multiple) {
+ this.updateOptGroups();
+ }
+
+ if (this.options.disableIfEmpty && $('option', this.$select).length <= 0) {
+ this.disable();
+ }
+ else {
+ this.enable();
+ }
+
+ if (this.options.dropRight) {
+ this.$ul.addClass('pull-right');
+ }
+ },
+
+ /**
+ * The provided data will be used to build the dropdown.
+ */
+ dataprovider: function(dataprovider) {
+
+ var groupCounter = 0;
+ var $select = this.$select.empty();
+
+ $.each(dataprovider, function (index, option) {
+ var $tag;
+
+ if ($.isArray(option.children)) { // create optiongroup tag
+ groupCounter++;
+
+ $tag = $(' ').attr({
+ label: option.label || 'Group ' + groupCounter,
+ disabled: !!option.disabled
+ });
+
+ forEach(option.children, function(subOption) { // add children option tags
+ var attributes = {
+ value: subOption.value,
+ label: subOption.label || subOption.value,
+ title: subOption.title,
+ selected: !!subOption.selected,
+ disabled: !!subOption.disabled
+ };
+
+ //Loop through attributes object and add key-value for each attribute
+ for (var key in subOption.attributes) {
+ attributes['data-' + key] = subOption.attributes[key];
+ }
+ //Append original attributes + new data attributes to option
+ $tag.append($(' ').attr(attributes));
+ });
+ }
+ else {
+
+ var attributes = {
+ 'value': option.value,
+ 'label': option.label || option.value,
+ 'title': option.title,
+ 'class': option.class,
+ 'selected': !!option.selected,
+ 'disabled': !!option.disabled
+ };
+ //Loop through attributes object and add key-value for each attribute
+ for (var key in option.attributes) {
+ attributes['data-' + key] = option.attributes[key];
+ }
+ //Append original attributes + new data attributes to option
+ $tag = $(' ').attr(attributes);
+
+ $tag.text(option.label || option.value);
+ }
+
+ $select.append($tag);
+ });
+
+ this.rebuild();
+ },
+
+ /**
+ * Enable the multiselect.
+ */
+ enable: function() {
+ this.$select.prop('disabled', false);
+ this.$button.prop('disabled', false)
+ .removeClass('disabled');
+ },
+
+ /**
+ * Disable the multiselect.
+ */
+ disable: function() {
+ this.$select.prop('disabled', true);
+ this.$button.prop('disabled', true)
+ .addClass('disabled');
+ },
+
+ /**
+ * Set the options.
+ *
+ * @param {Array} options
+ */
+ setOptions: function(options) {
+ this.options = this.mergeOptions(options);
+ },
+
+ /**
+ * Merges the given options with the default options.
+ *
+ * @param {Array} options
+ * @returns {Array}
+ */
+ mergeOptions: function(options) {
+ return $.extend(true, {}, this.defaults, this.options, options);
+ },
+
+ /**
+ * Checks whether a select all checkbox is present.
+ *
+ * @returns {Boolean}
+ */
+ hasSelectAll: function() {
+ return $('li.multiselect-all', this.$ul).length > 0;
+ },
+
+ /**
+ * Update opt groups.
+ */
+ updateOptGroups: function() {
+ var $groups = $('li.multiselect-group', this.$ul)
+ var selectedClass = this.options.selectedClass;
+
+ $groups.each(function() {
+ var $options = $(this).nextUntil('li.multiselect-group')
+ .not('.multiselect-filter-hidden')
+ .not('.disabled');
+
+ var checked = true;
+ $options.each(function() {
+ var $input = $('input', this);
+
+ if (!$input.prop('checked')) {
+ checked = false;
+ }
+ });
+
+ if (selectedClass) {
+ if (checked) {
+ $(this).addClass(selectedClass);
+ }
+ else {
+ $(this).removeClass(selectedClass);
+ }
+ }
+
+ $('input', this).prop('checked', checked);
+ });
+ },
+
+ /**
+ * Updates the select all checkbox based on the currently displayed and selected checkboxes.
+ */
+ updateSelectAll: function(notTriggerOnSelectAll) {
+ if (this.hasSelectAll()) {
+ var allBoxes = $("li:not(.multiselect-item):not(.multiselect-filter-hidden):not(.multiselect-group):not(.disabled) input:enabled", this.$ul);
+ var allBoxesLength = allBoxes.length;
+ var checkedBoxesLength = allBoxes.filter(":checked").length;
+ var selectAllLi = $("li.multiselect-all", this.$ul);
+ var selectAllInput = selectAllLi.find("input");
+
+ if (checkedBoxesLength > 0 && checkedBoxesLength === allBoxesLength) {
+ selectAllInput.prop("checked", true);
+ selectAllLi.addClass(this.options.selectedClass);
+ }
+ else {
+ selectAllInput.prop("checked", false);
+ selectAllLi.removeClass(this.options.selectedClass);
+ }
+ }
+ },
+
+ /**
+ * Update the button text and its title based on the currently selected options.
+ */
+ updateButtonText: function() {
+ var options = this.getSelected();
+
+ // First update the displayed button text.
+ if (this.options.enableHTML) {
+ $('.multiselect .multiselect-selected-text', this.$container).html(this.options.buttonText(options, this.$select));
+ }
+ else {
+ $('.multiselect .multiselect-selected-text', this.$container).text(this.options.buttonText(options, this.$select));
+ }
+
+ // Now update the title attribute of the button.
+ $('.multiselect', this.$container).attr('title', this.options.buttonTitle(options, this.$select));
+ },
+
+ /**
+ * Get all selected options.
+ *
+ * @returns {jQUery}
+ */
+ getSelected: function() {
+ return $('option', this.$select).filter(":selected");
+ },
+
+ /**
+ * Gets a select option by its value.
+ *
+ * @param {String} value
+ * @returns {jQuery}
+ */
+ getOptionByValue: function (value) {
+
+ var options = $('option', this.$select);
+ var valueToCompare = value.toString();
+
+ for (var i = 0; i < options.length; i = i + 1) {
+ var option = options[i];
+ if (option.value === valueToCompare) {
+ return $(option);
+ }
+ }
+ },
+
+ /**
+ * Get the input (radio/checkbox) by its value.
+ *
+ * @param {String} value
+ * @returns {jQuery}
+ */
+ getInputByValue: function (value) {
+
+ var checkboxes = $('li input:not(.multiselect-search)', this.$ul);
+ var valueToCompare = value.toString();
+
+ for (var i = 0; i < checkboxes.length; i = i + 1) {
+ var checkbox = checkboxes[i];
+ if (checkbox.value === valueToCompare) {
+ return $(checkbox);
+ }
+ }
+ },
+
+ /**
+ * Used for knockout integration.
+ */
+ updateOriginalOptions: function() {
+ this.originalOptions = this.$select.clone()[0].options;
+ },
+
+ asyncFunction: function(callback, timeout, self) {
+ var args = Array.prototype.slice.call(arguments, 3);
+ return setTimeout(function() {
+ callback.apply(self || window, args);
+ }, timeout);
+ },
+
+ setAllSelectedText: function(allSelectedText) {
+ this.options.allSelectedText = allSelectedText;
+ this.updateButtonText();
+ }
+ };
+
+ $.fn.multiselect = function(option, parameter, extraOptions) {
+ return this.each(function() {
+ var data = $(this).data('multiselect');
+ var options = typeof option === 'object' && option;
+
+ // Initialize the multiselect.
+ if (!data) {
+ data = new Multiselect(this, options);
+ $(this).data('multiselect', data);
+ }
+
+ // Call multiselect method.
+ if (typeof option === 'string') {
+ data[option](parameter, extraOptions);
+
+ if (option === 'destroy') {
+ $(this).data('multiselect', false);
+ }
+ }
+ });
+ };
+
+ $.fn.multiselect.Constructor = Multiselect;
+
+ $(function() {
+ $("select[data-role=multiselect]").multiselect();
+ });
+
+}(window.jQuery);
diff --git a/ocl_web/static/js/project.js b/ocl_web/static/js/project.js
index 183e90b6..a0d270bc 100644
--- a/ocl_web/static/js/project.js
+++ b/ocl_web/static/js/project.js
@@ -723,6 +723,13 @@ app.controller("MappingVersionsController", function ($scope, $http) {
}
});
+// app.controller("ConceptRelationshipController", function ($scope, $http) {
+// $scope.submitRelationshipForm = function (relationshipForm, concept_relationship_url) {
+// url = concept_relationship_url + "?selected_source=1&selected_source=2";
+// window.location.href = url;
+// }
+// });
+
// Simple function to handle removing member from org
function removeMember(orgId, memId) {
alert(orgId);
diff --git a/ocl_web/static/js/springy.js b/ocl_web/static/js/springy.js
new file mode 100644
index 00000000..c93c399d
--- /dev/null
+++ b/ocl_web/static/js/springy.js
@@ -0,0 +1,731 @@
+/**
+ * Springy v2.7.1
+ *
+ * Copyright (c) 2010-2013 Dennis Hotson
+ *
+ * Permission is hereby granted, free of charge, to any person
+ * obtaining a copy of this software and associated documentation
+ * files (the "Software"), to deal in the Software without
+ * restriction, including without limitation the rights to use,
+ * copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following
+ * conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+ * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+ * OTHER DEALINGS IN THE SOFTWARE.
+ */
+(function (root, factory) {
+ if (typeof define === 'function' && define.amd) {
+ // AMD. Register as an anonymous module.
+ define(function () {
+ return (root.returnExportsGlobal = factory());
+ });
+ } else if (typeof exports === 'object') {
+ // Node. Does not work with strict CommonJS, but
+ // only CommonJS-like enviroments that support module.exports,
+ // like Node.
+ module.exports = factory();
+ } else {
+ // Browser globals
+ root.Springy = factory();
+ }
+}(this, function() {
+
+ var Springy = {};
+
+ var Graph = Springy.Graph = function() {
+ this.nodeSet = {};
+ this.nodes = [];
+ this.edges = [];
+ this.adjacency = {};
+
+ this.nextNodeId = 0;
+ this.nextEdgeId = 0;
+ this.eventListeners = [];
+ };
+
+ var Node = Springy.Node = function(id, data) {
+ this.id = id;
+ this.data = (data !== undefined) ? data : {};
+
+ // Data fields used by layout algorithm in this file:
+ // this.data.mass
+ // Data used by default renderer in springyui.js
+ // this.data.label
+ };
+
+ var Edge = Springy.Edge = function(id, source, target, data) {
+ this.id = id;
+ this.source = source;
+ this.target = target;
+ this.data = (data !== undefined) ? data : {};
+
+ // Edge data field used by layout alorithm
+ // this.data.length
+ // this.data.type
+ };
+
+ Graph.prototype.addNode = function(node) {
+ if (!(node.id in this.nodeSet)) {
+ this.nodes.push(node);
+ }
+
+ this.nodeSet[node.id] = node;
+
+ this.notify();
+ return node;
+ };
+
+ Graph.prototype.addNodes = function() {
+ // accepts variable number of arguments, where each argument
+ // is a string that becomes both node identifier and label
+ for (var i = 0; i < arguments.length; i++) {
+ var name = arguments[i];
+ var node = new Node(name, {label:name});
+ this.addNode(node);
+ }
+ };
+
+ Graph.prototype.addEdge = function(edge) {
+ var exists = false;
+ this.edges.forEach(function(e) {
+ if (edge.id === e.id) { exists = true; }
+ });
+
+ if (!exists) {
+ this.edges.push(edge);
+ }
+
+ if (!(edge.source.id in this.adjacency)) {
+ this.adjacency[edge.source.id] = {};
+ }
+ if (!(edge.target.id in this.adjacency[edge.source.id])) {
+ this.adjacency[edge.source.id][edge.target.id] = [];
+ }
+
+ exists = false;
+ this.adjacency[edge.source.id][edge.target.id].forEach(function(e) {
+ if (edge.id === e.id) { exists = true; }
+ });
+
+ if (!exists) {
+ this.adjacency[edge.source.id][edge.target.id].push(edge);
+ }
+
+ this.notify();
+ return edge;
+ };
+
+ Graph.prototype.addEdges = function() {
+ // accepts variable number of arguments, where each argument
+ // is a triple [nodeid1, nodeid2, attributes]
+ for (var i = 0; i < arguments.length; i++) {
+ var e = arguments[i];
+ var node1 = this.nodeSet[e[0]];
+ if (node1 == undefined) {
+ throw new TypeError("invalid node name: " + e[0]);
+ }
+ var node2 = this.nodeSet[e[1]];
+ if (node2 == undefined) {
+ throw new TypeError("invalid node name: " + e[1]);
+ }
+ var attr = e[2];
+
+ this.newEdge(node1, node2, attr);
+ }
+ };
+
+ Graph.prototype.newNode = function(data) {
+ var node = new Node(this.nextNodeId++, data);
+ this.addNode(node);
+ return node;
+ };
+
+ Graph.prototype.newEdge = function(source, target, data) {
+ var edge = new Edge(this.nextEdgeId++, source, target, data);
+ this.addEdge(edge);
+ return edge;
+ };
+
+
+ // add nodes and edges from JSON object
+ Graph.prototype.loadJSON = function(json) {
+ /**
+ Springy's simple JSON format for graphs.
+
+ historically, Springy uses separate lists
+ of nodes and edges:
+
+ {
+ "nodes": [
+ "center",
+ "left",
+ "right",
+ "up",
+ "satellite"
+ ],
+ "edges": [
+ ["center", "left"],
+ ["center", "right"],
+ ["center", "up"]
+ ]
+ }
+
+ **/
+ // parse if a string is passed (EC5+ browsers)
+ if (typeof json == 'string' || json instanceof String) {
+ json = JSON.parse( json );
+ }
+
+ if ('nodes' in json || 'edges' in json) {
+ this.addNodes.apply(this, json['nodes']);
+ this.addEdges.apply(this, json['edges']);
+ }
+ }
+
+
+ // find the edges from node1 to node2
+ Graph.prototype.getEdges = function(node1, node2) {
+ if (node1.id in this.adjacency
+ && node2.id in this.adjacency[node1.id]) {
+ return this.adjacency[node1.id][node2.id];
+ }
+
+ return [];
+ };
+
+ // remove a node and it's associated edges from the graph
+ Graph.prototype.removeNode = function(node) {
+ if (node.id in this.nodeSet) {
+ delete this.nodeSet[node.id];
+ }
+
+ for (var i = this.nodes.length - 1; i >= 0; i--) {
+ if (this.nodes[i].id === node.id) {
+ this.nodes.splice(i, 1);
+ }
+ }
+
+ this.detachNode(node);
+ };
+
+ // removes edges associated with a given node
+ Graph.prototype.detachNode = function(node) {
+ var tmpEdges = this.edges.slice();
+ tmpEdges.forEach(function(e) {
+ if (e.source.id === node.id || e.target.id === node.id) {
+ this.removeEdge(e);
+ }
+ }, this);
+
+ this.notify();
+ };
+
+ // remove a node and it's associated edges from the graph
+ Graph.prototype.removeEdge = function(edge) {
+ for (var i = this.edges.length - 1; i >= 0; i--) {
+ if (this.edges[i].id === edge.id) {
+ this.edges.splice(i, 1);
+ }
+ }
+
+ for (var x in this.adjacency) {
+ for (var y in this.adjacency[x]) {
+ var edges = this.adjacency[x][y];
+
+ for (var j=edges.length - 1; j>=0; j--) {
+ if (this.adjacency[x][y][j].id === edge.id) {
+ this.adjacency[x][y].splice(j, 1);
+ }
+ }
+
+ // Clean up empty edge arrays
+ if (this.adjacency[x][y].length == 0) {
+ delete this.adjacency[x][y];
+ }
+ }
+
+ // Clean up empty objects
+ if (isEmpty(this.adjacency[x])) {
+ delete this.adjacency[x];
+ }
+ }
+
+ this.notify();
+ };
+
+ /* Merge a list of nodes and edges into the current graph. eg.
+ var o = {
+ nodes: [
+ {id: 123, data: {type: 'user', userid: 123, displayname: 'aaa'}},
+ {id: 234, data: {type: 'user', userid: 234, displayname: 'bbb'}}
+ ],
+ edges: [
+ {from: 0, to: 1, type: 'submitted_design', directed: true, data: {weight: }}
+ ]
+ }
+ */
+ Graph.prototype.merge = function(data) {
+ var nodes = [];
+ data.nodes.forEach(function(n) {
+ nodes.push(this.addNode(new Node(n.id, n.data)));
+ }, this);
+
+ data.edges.forEach(function(e) {
+ var from = nodes[e.from];
+ var to = nodes[e.to];
+
+ var id = (e.directed)
+ ? (id = e.type + "-" + from.id + "-" + to.id)
+ : (from.id < to.id) // normalise id for non-directed edges
+ ? e.type + "-" + from.id + "-" + to.id
+ : e.type + "-" + to.id + "-" + from.id;
+
+ var edge = this.addEdge(new Edge(id, from, to, e.data));
+ edge.data.type = e.type;
+ }, this);
+ };
+
+ Graph.prototype.filterNodes = function(fn) {
+ var tmpNodes = this.nodes.slice();
+ tmpNodes.forEach(function(n) {
+ if (!fn(n)) {
+ this.removeNode(n);
+ }
+ }, this);
+ };
+
+ Graph.prototype.filterEdges = function(fn) {
+ var tmpEdges = this.edges.slice();
+ tmpEdges.forEach(function(e) {
+ if (!fn(e)) {
+ this.removeEdge(e);
+ }
+ }, this);
+ };
+
+
+ Graph.prototype.addGraphListener = function(obj) {
+ this.eventListeners.push(obj);
+ };
+
+ Graph.prototype.notify = function() {
+ this.eventListeners.forEach(function(obj){
+ obj.graphChanged();
+ });
+ };
+
+ // -----------
+ var Layout = Springy.Layout = {};
+ Layout.ForceDirected = function(graph, stiffness, repulsion, damping, minEnergyThreshold, maxSpeed) {
+ this.graph = graph;
+ this.stiffness = stiffness; // spring stiffness constant
+ this.repulsion = repulsion; // repulsion constant
+ this.damping = damping; // velocity damping factor
+ this.minEnergyThreshold = minEnergyThreshold || 0.01; //threshold used to determine render stop
+ this.maxSpeed = maxSpeed || Infinity; // nodes aren't allowed to exceed this speed
+
+ this.nodePoints = {}; // keep track of points associated with nodes
+ this.edgeSprings = {}; // keep track of springs associated with edges
+ };
+
+ Layout.ForceDirected.prototype.point = function(node) {
+ if (!(node.id in this.nodePoints)) {
+ var mass = (node.data.mass !== undefined) ? node.data.mass : 1.0;
+ this.nodePoints[node.id] = new Layout.ForceDirected.Point(Vector.random(), mass);
+ }
+
+ return this.nodePoints[node.id];
+ };
+
+ Layout.ForceDirected.prototype.spring = function(edge) {
+ if (!(edge.id in this.edgeSprings)) {
+ var length = (edge.data.length !== undefined) ? edge.data.length : 1.0;
+
+ var existingSpring = false;
+
+ var from = this.graph.getEdges(edge.source, edge.target);
+ from.forEach(function(e) {
+ if (existingSpring === false && e.id in this.edgeSprings) {
+ existingSpring = this.edgeSprings[e.id];
+ }
+ }, this);
+
+ if (existingSpring !== false) {
+ return new Layout.ForceDirected.Spring(existingSpring.point1, existingSpring.point2, 0.0, 0.0);
+ }
+
+ var to = this.graph.getEdges(edge.target, edge.source);
+ from.forEach(function(e){
+ if (existingSpring === false && e.id in this.edgeSprings) {
+ existingSpring = this.edgeSprings[e.id];
+ }
+ }, this);
+
+ if (existingSpring !== false) {
+ return new Layout.ForceDirected.Spring(existingSpring.point2, existingSpring.point1, 0.0, 0.0);
+ }
+
+ this.edgeSprings[edge.id] = new Layout.ForceDirected.Spring(
+ this.point(edge.source), this.point(edge.target), length, this.stiffness
+ );
+ }
+
+ return this.edgeSprings[edge.id];
+ };
+
+ // callback should accept two arguments: Node, Point
+ Layout.ForceDirected.prototype.eachNode = function(callback) {
+ var t = this;
+ this.graph.nodes.forEach(function(n){
+ callback.call(t, n, t.point(n));
+ });
+ };
+
+ // callback should accept two arguments: Edge, Spring
+ Layout.ForceDirected.prototype.eachEdge = function(callback) {
+ var t = this;
+ this.graph.edges.forEach(function(e){
+ callback.call(t, e, t.spring(e));
+ });
+ };
+
+ // callback should accept one argument: Spring
+ Layout.ForceDirected.prototype.eachSpring = function(callback) {
+ var t = this;
+ this.graph.edges.forEach(function(e){
+ callback.call(t, t.spring(e));
+ });
+ };
+
+
+ // Physics stuff
+ Layout.ForceDirected.prototype.applyCoulombsLaw = function() {
+ this.eachNode(function(n1, point1) {
+ this.eachNode(function(n2, point2) {
+ if (point1 !== point2)
+ {
+ var d = point1.p.subtract(point2.p);
+ var distance = d.magnitude() + 0.1; // avoid massive forces at small distances (and divide by zero)
+ var direction = d.normalise();
+
+ // apply force to each end point
+ point1.applyForce(direction.multiply(this.repulsion).divide(distance * distance * 0.5));
+ point2.applyForce(direction.multiply(this.repulsion).divide(distance * distance * -0.5));
+ }
+ });
+ });
+ };
+
+ Layout.ForceDirected.prototype.applyHookesLaw = function() {
+ this.eachSpring(function(spring){
+ var d = spring.point2.p.subtract(spring.point1.p); // the direction of the spring
+ var displacement = spring.length - d.magnitude();
+ var direction = d.normalise();
+
+ // apply force to each end point
+ spring.point1.applyForce(direction.multiply(spring.k * displacement * -0.5));
+ spring.point2.applyForce(direction.multiply(spring.k * displacement * 0.5));
+ });
+ };
+
+ Layout.ForceDirected.prototype.attractToCentre = function() {
+ this.eachNode(function(node, point) {
+ var direction = point.p.multiply(-1.0);
+ point.applyForce(direction.multiply(this.repulsion / 50.0));
+ });
+ };
+
+
+ Layout.ForceDirected.prototype.updateVelocity = function(timestep) {
+ this.eachNode(function(node, point) {
+ // Is this, along with updatePosition below, the only places that your
+ // integration code exist?
+ point.v = point.v.add(point.a.multiply(timestep)).multiply(this.damping);
+ if (point.v.magnitude() > this.maxSpeed) {
+ point.v = point.v.normalise().multiply(this.maxSpeed);
+ }
+ point.a = new Vector(0,0);
+ });
+ };
+
+ Layout.ForceDirected.prototype.updatePosition = function(timestep) {
+ this.eachNode(function(node, point) {
+ // Same question as above; along with updateVelocity, is this all of
+ // your integration code?
+ point.p = point.p.add(point.v.multiply(timestep));
+ });
+ };
+
+ // Calculate the total kinetic energy of the system
+ Layout.ForceDirected.prototype.totalEnergy = function(timestep) {
+ var energy = 0.0;
+ this.eachNode(function(node, point) {
+ var speed = point.v.magnitude();
+ energy += 0.5 * point.m * speed * speed;
+ });
+
+ return energy;
+ };
+
+ var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; // stolen from coffeescript, thanks jashkenas! ;-)
+
+ Springy.requestAnimationFrame = __bind(this.requestAnimationFrame ||
+ this.webkitRequestAnimationFrame ||
+ this.mozRequestAnimationFrame ||
+ this.oRequestAnimationFrame ||
+ this.msRequestAnimationFrame ||
+ (function(callback, element) {
+ this.setTimeout(callback, 10);
+ }), this);
+
+
+ /**
+ * Start simulation if it's not running already.
+ * In case it's running then the call is ignored, and none of the callbacks passed is ever executed.
+ */
+ Layout.ForceDirected.prototype.start = function(render, onRenderStop, onRenderStart) {
+ var t = this;
+
+ if (this._started) return;
+ this._started = true;
+ this._stop = false;
+
+ if (onRenderStart !== undefined) { onRenderStart(); }
+
+ Springy.requestAnimationFrame(function step() {
+ t.tick(0.03);
+
+ if (render !== undefined) {
+ render();
+ }
+
+ // stop simulation when energy of the system goes below a threshold
+ if (t._stop || t.totalEnergy() < t.minEnergyThreshold) {
+ t._started = false;
+ if (onRenderStop !== undefined) { onRenderStop(); }
+ } else {
+ Springy.requestAnimationFrame(step);
+ }
+ });
+ };
+
+ Layout.ForceDirected.prototype.stop = function() {
+ this._stop = true;
+ }
+
+ Layout.ForceDirected.prototype.tick = function(timestep) {
+ this.applyCoulombsLaw();
+ this.applyHookesLaw();
+ this.attractToCentre();
+ this.updateVelocity(timestep);
+ this.updatePosition(timestep);
+ };
+
+ // Find the nearest point to a particular position
+ Layout.ForceDirected.prototype.nearest = function(pos) {
+ var min = {node: null, point: null, distance: null};
+ var t = this;
+ this.graph.nodes.forEach(function(n){
+ var point = t.point(n);
+ var distance = point.p.subtract(pos).magnitude();
+
+ if (min.distance === null || distance < min.distance) {
+ min = {node: n, point: point, distance: distance};
+ }
+ });
+
+ return min;
+ };
+
+ // returns [bottomleft, topright]
+ Layout.ForceDirected.prototype.getBoundingBox = function() {
+ var bottomleft = new Vector(-2,-2);
+ var topright = new Vector(2,2);
+
+ this.eachNode(function(n, point) {
+ if (point.p.x < bottomleft.x) {
+ bottomleft.x = point.p.x;
+ }
+ if (point.p.y < bottomleft.y) {
+ bottomleft.y = point.p.y;
+ }
+ if (point.p.x > topright.x) {
+ topright.x = point.p.x;
+ }
+ if (point.p.y > topright.y) {
+ topright.y = point.p.y;
+ }
+ });
+
+ var padding = topright.subtract(bottomleft).multiply(0.07); // ~5% padding
+
+ return {bottomleft: bottomleft.subtract(padding), topright: topright.add(padding)};
+ };
+
+
+ // Vector
+ var Vector = Springy.Vector = function(x, y) {
+ this.x = x;
+ this.y = y;
+ };
+
+ Vector.random = function() {
+ return new Vector(10.0 * (Math.random() - 0.5), 10.0 * (Math.random() - 0.5));
+ };
+
+ Vector.prototype.add = function(v2) {
+ return new Vector(this.x + v2.x, this.y + v2.y);
+ };
+
+ Vector.prototype.subtract = function(v2) {
+ return new Vector(this.x - v2.x, this.y - v2.y);
+ };
+
+ Vector.prototype.multiply = function(n) {
+ return new Vector(this.x * n, this.y * n);
+ };
+
+ Vector.prototype.divide = function(n) {
+ return new Vector((this.x / n) || 0, (this.y / n) || 0); // Avoid divide by zero errors..
+ };
+
+ Vector.prototype.magnitude = function() {
+ return Math.sqrt(this.x*this.x + this.y*this.y);
+ };
+
+ Vector.prototype.normal = function() {
+ return new Vector(-this.y, this.x);
+ };
+
+ Vector.prototype.normalise = function() {
+ return this.divide(this.magnitude());
+ };
+
+ // Point
+ Layout.ForceDirected.Point = function(position, mass) {
+ this.p = position; // position
+ this.m = mass; // mass
+ this.v = new Vector(0, 0); // velocity
+ this.a = new Vector(0, 0); // acceleration
+ };
+
+ Layout.ForceDirected.Point.prototype.applyForce = function(force) {
+ this.a = this.a.add(force.divide(this.m));
+ };
+
+ // Spring
+ Layout.ForceDirected.Spring = function(point1, point2, length, k) {
+ this.point1 = point1;
+ this.point2 = point2;
+ this.length = length; // spring length at rest
+ this.k = k; // spring constant (See Hooke's law) .. how stiff the spring is
+ };
+
+ // Layout.ForceDirected.Spring.prototype.distanceToPoint = function(point)
+ // {
+ // // hardcore vector arithmetic.. ohh yeah!
+ // // .. see http://stackoverflow.com/questions/849211/shortest-distance-between-a-point-and-a-line-segment/865080#865080
+ // var n = this.point2.p.subtract(this.point1.p).normalise().normal();
+ // var ac = point.p.subtract(this.point1.p);
+ // return Math.abs(ac.x * n.x + ac.y * n.y);
+ // };
+
+ /**
+ * Renderer handles the layout rendering loop
+ * @param onRenderStop optional callback function that gets executed whenever rendering stops.
+ * @param onRenderStart optional callback function that gets executed whenever rendering starts.
+ */
+ var Renderer = Springy.Renderer = function(layout, clear, drawEdge, drawNode, onRenderStop, onRenderStart) {
+ this.layout = layout;
+ this.clear = clear;
+ this.drawEdge = drawEdge;
+ this.drawNode = drawNode;
+ this.onRenderStop = onRenderStop;
+ this.onRenderStart = onRenderStart;
+
+ this.layout.graph.addGraphListener(this);
+ }
+
+ Renderer.prototype.graphChanged = function(e) {
+ this.start();
+ };
+
+ /**
+ * Starts the simulation of the layout in use.
+ *
+ * Note that in case the algorithm is still or already running then the layout that's in use
+ * might silently ignore the call, and your optional done callback is never executed.
+ * At least the built-in ForceDirected layout behaves in this way.
+ *
+ * @param done An optional callback function that gets executed when the springy algorithm stops,
+ * either because it ended or because stop() was called.
+ */
+ Renderer.prototype.start = function(done) {
+ var t = this;
+ this.layout.start(function render() {
+ t.clear();
+
+ t.layout.eachEdge(function(edge, spring) {
+ t.drawEdge(edge, spring.point1.p, spring.point2.p);
+ });
+
+ t.layout.eachNode(function(node, point) {
+ t.drawNode(node, point.p);
+ });
+ }, this.onRenderStop, this.onRenderStart);
+ };
+
+ Renderer.prototype.stop = function() {
+ this.layout.stop();
+ };
+
+ // Array.forEach implementation for IE support..
+ //https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/forEach
+ if ( !Array.prototype.forEach ) {
+ Array.prototype.forEach = function( callback, thisArg ) {
+ var T, k;
+ if ( this == null ) {
+ throw new TypeError( " this is null or not defined" );
+ }
+ var O = Object(this);
+ var len = O.length >>> 0; // Hack to convert O.length to a UInt32
+ if ( {}.toString.call(callback) != "[object Function]" ) {
+ throw new TypeError( callback + " is not a function" );
+ }
+ if ( thisArg ) {
+ T = thisArg;
+ }
+ k = 0;
+ while( k < len ) {
+ var kValue;
+ if ( k in O ) {
+ kValue = O[ k ];
+ callback.call( T, kValue, k, O );
+ }
+ k++;
+ }
+ };
+ }
+
+ var isEmpty = function(obj) {
+ for (var k in obj) {
+ if (obj.hasOwnProperty(k)) {
+ return false;
+ }
+ }
+ return true;
+ };
+
+ return Springy;
+}));
diff --git a/ocl_web/static/js/springyui.js b/ocl_web/static/js/springyui.js
new file mode 100755
index 00000000..acc35eb7
--- /dev/null
+++ b/ocl_web/static/js/springyui.js
@@ -0,0 +1,394 @@
+/**
+Copyright (c) 2010 Dennis Hotson
+
+ Permission is hereby granted, free of charge, to any person
+ obtaining a copy of this software and associated documentation
+ files (the "Software"), to deal in the Software without
+ restriction, including without limitation the rights to use,
+ copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the
+ Software is furnished to do so, subject to the following
+ conditions:
+
+ The above copyright notice and this permission notice shall be
+ included in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+ OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+ OTHER DEALINGS IN THE SOFTWARE.
+*/
+
+(function() {
+
+jQuery.fn.springy = function(params) {
+ var graph = this.graph = params.graph || new Springy.Graph();
+ var nodeFont = "16px Verdana, sans-serif";
+ var edgeFont = "8px Verdana, sans-serif";
+ var stiffness = params.stiffness || 400.0;
+ var repulsion = params.repulsion || 400.0;
+ var damping = params.damping || 0.5;
+ var minEnergyThreshold = params.minEnergyThreshold || 0.00001;
+ var nodeSelected = params.nodeSelected || null;
+ var nodeImages = {};
+ var edgeLabelsUpright = true;
+
+ var canvas = this[0];
+ var ctx = canvas.getContext("2d");
+
+ var layout = this.layout = new Springy.Layout.ForceDirected(graph, stiffness, repulsion, damping, minEnergyThreshold);
+
+ // calculate bounding box of graph layout.. with ease-in
+ var currentBB = layout.getBoundingBox();
+ var targetBB = {bottomleft: new Springy.Vector(-2, -2), topright: new Springy.Vector(2, 2)};
+
+ // auto adjusting bounding box
+ Springy.requestAnimationFrame(function adjust() {
+ targetBB = layout.getBoundingBox();
+ // current gets 20% closer to target every iteration
+ currentBB = {
+ bottomleft: currentBB.bottomleft.add( targetBB.bottomleft.subtract(currentBB.bottomleft)
+ .divide(10)),
+ topright: currentBB.topright.add( targetBB.topright.subtract(currentBB.topright)
+ .divide(10))
+ };
+
+ Springy.requestAnimationFrame(adjust);
+ });
+
+ // convert to/from screen coordinates
+ var toScreen = function(p) {
+ var size = currentBB.topright.subtract(currentBB.bottomleft);
+ var sx = p.subtract(currentBB.bottomleft).divide(size.x).x * canvas.width;
+ var sy = p.subtract(currentBB.bottomleft).divide(size.y).y * canvas.height;
+ return new Springy.Vector(sx, sy);
+ };
+
+ var fromScreen = function(s) {
+ var size = currentBB.topright.subtract(currentBB.bottomleft);
+ var px = (s.x / canvas.width) * size.x + currentBB.bottomleft.x;
+ var py = (s.y / canvas.height) * size.y + currentBB.bottomleft.y;
+ return new Springy.Vector(px, py);
+ };
+
+ // half-assed drag and drop
+ var selected = null;
+ var nearest = null;
+ var dragged = null;
+
+ jQuery(canvas).mousedown(function(e) {
+ var pos = jQuery(this).offset();
+ var p = fromScreen({x: e.pageX - pos.left, y: e.pageY - pos.top});
+ selected = nearest = dragged = layout.nearest(p);
+
+ if (selected.node !== null) {
+ dragged.point.m = 10000.0;
+
+ if (nodeSelected) {
+ nodeSelected(selected.node);
+ }
+ }
+
+ renderer.start();
+ });
+
+ // Basic double click handler
+ jQuery(canvas).dblclick(function(e) {
+ var pos = jQuery(this).offset();
+ var p = fromScreen({x: e.pageX - pos.left, y: e.pageY - pos.top});
+ selected = layout.nearest(p);
+ node = selected.node;
+ if (node && node.data && node.data.ondoubleclick) {
+ node.data.ondoubleclick();
+ }
+ });
+
+ jQuery(canvas).mousemove(function(e) {
+ var pos = jQuery(this).offset();
+ var p = fromScreen({x: e.pageX - pos.left, y: e.pageY - pos.top});
+ nearest = layout.nearest(p);
+
+ if (dragged !== null && dragged.node !== null) {
+ dragged.point.p.x = p.x;
+ dragged.point.p.y = p.y;
+ }
+
+ renderer.start();
+ });
+
+ jQuery(window).bind('mouseup',function(e) {
+ dragged = null;
+ });
+
+ var getTextWidth = function(node) {
+ var text = (node.data.label !== undefined) ? node.data.label : node.id;
+ if (node._width && node._width[text])
+ return node._width[text];
+
+ ctx.save();
+ ctx.font = (node.data.font !== undefined) ? node.data.font : nodeFont;
+ var width = ctx.measureText(text).width;
+ ctx.restore();
+
+ node._width || (node._width = {});
+ node._width[text] = width;
+
+ return width;
+ };
+
+ var getTextHeight = function(node) {
+ return 16;
+ // In a more modular world, this would actually read the font size, but I think leaving it a constant is sufficient for now.
+ // If you change the font size, I'd adjust this too.
+ };
+
+ var getImageWidth = function(node) {
+ var width = (node.data.image.width !== undefined) ? node.data.image.width : nodeImages[node.data.image.src].object.width;
+ return width;
+ }
+
+ var getImageHeight = function(node) {
+ var height = (node.data.image.height !== undefined) ? node.data.image.height : nodeImages[node.data.image.src].object.height;
+ return height;
+ }
+
+ Springy.Node.prototype.getHeight = function() {
+ var height;
+ if (this.data.image == undefined) {
+ height = getTextHeight(this);
+ } else {
+ if (this.data.image.src in nodeImages && nodeImages[this.data.image.src].loaded) {
+ height = getImageHeight(this);
+ } else {height = 10;}
+ }
+ return height;
+ }
+
+ Springy.Node.prototype.getWidth = function() {
+ var width;
+ if (this.data.image == undefined) {
+ width = getTextWidth(this);
+ } else {
+ if (this.data.image.src in nodeImages && nodeImages[this.data.image.src].loaded) {
+ width = getImageWidth(this);
+ } else {width = 10;}
+ }
+ return width;
+ }
+
+ var renderer = this.renderer = new Springy.Renderer(layout,
+ function clear() {
+ ctx.clearRect(0,0,canvas.width,canvas.height);
+ },
+ function drawEdge(edge, p1, p2) {
+ var x1 = toScreen(p1).x;
+ var y1 = toScreen(p1).y;
+ var x2 = toScreen(p2).x;
+ var y2 = toScreen(p2).y;
+
+ var direction = new Springy.Vector(x2-x1, y2-y1);
+ var normal = direction.normal().normalise();
+
+ var from = graph.getEdges(edge.source, edge.target);
+ var to = graph.getEdges(edge.target, edge.source);
+
+ var total = from.length + to.length;
+
+ // Figure out edge's position in relation to other edges between the same nodes
+ var n = 0;
+ for (var i=0; i Math.PI/2 || angle < -Math.PI/2)) {
+ displacement = 8;
+ angle += Math.PI;
+ }
+ var textPos = s1.add(s2).divide(2).add(normal.multiply(displacement));
+ ctx.translate(textPos.x, textPos.y);
+ ctx.rotate(angle);
+ ctx.fillText(text, 0,-2);
+ ctx.restore();
+ }
+
+ },
+ function drawNode(node, p) {
+ var s = toScreen(p);
+
+ ctx.save();
+
+ // Pulled out the padding aspect sso that the size functions could be used in multiple places
+ // These should probably be settable by the user (and scoped higher) but this suffices for now
+ var paddingX = 6;
+ var paddingY = 6;
+
+ var contentWidth = node.getWidth();
+ var contentHeight = node.getHeight();
+ var boxWidth = contentWidth + paddingX;
+ var boxHeight = contentHeight + paddingY;
+
+ // clear background
+ ctx.clearRect(s.x - boxWidth/2, s.y - boxHeight/2, boxWidth, boxHeight);
+
+ // fill background
+ if (selected !== null && selected.node !== null && selected.node.id === node.id) {
+ ctx.fillStyle = "#FFFFE0";
+ } else if (nearest !== null && nearest.node !== null && nearest.node.id === node.id) {
+ ctx.fillStyle = "#EEEEEE";
+ } else {
+ ctx.fillStyle = "#FFFFFF";
+ }
+ ctx.fillRect(s.x - boxWidth/2, s.y - boxHeight/2, boxWidth, boxHeight);
+
+ if (node.data.image == undefined) {
+ ctx.textAlign = "left";
+ ctx.textBaseline = "top";
+ ctx.font = (node.data.font !== undefined) ? node.data.font : nodeFont;
+ ctx.fillStyle = (node.data.color !== undefined) ? node.data.color : "#000000";
+ var text = (node.data.label !== undefined) ? node.data.label : node.id;
+ ctx.fillText(text, s.x - contentWidth/2, s.y - contentHeight/2);
+ } else {
+ // Currently we just ignore any labels if the image object is set. One might want to extend this logic to allow for both, or other composite nodes.
+ var src = node.data.image.src; // There should probably be a sanity check here too, but un-src-ed images aren't exaclty a disaster.
+ if (src in nodeImages) {
+ if (nodeImages[src].loaded) {
+ // Our image is loaded, so it's safe to draw
+ ctx.drawImage(nodeImages[src].object, s.x - contentWidth/2, s.y - contentHeight/2, contentWidth, contentHeight);
+ }
+ }else{
+ // First time seeing an image with this src address, so add it to our set of image objects
+ // Note: we index images by their src to avoid making too many duplicates
+ nodeImages[src] = {};
+ var img = new Image();
+ nodeImages[src].object = img;
+ img.addEventListener("load", function () {
+ // HTMLImageElement objects are very finicky about being used before they are loaded, so we set a flag when it is done
+ nodeImages[src].loaded = true;
+ });
+ img.src = src;
+ }
+ }
+ ctx.restore();
+ }
+ );
+
+ renderer.start();
+
+ // helpers for figuring out where to draw arrows
+ function intersect_line_line(p1, p2, p3, p4) {
+ var denom = ((p4.y - p3.y)*(p2.x - p1.x) - (p4.x - p3.x)*(p2.y - p1.y));
+
+ // lines are parallel
+ if (denom === 0) {
+ return false;
+ }
+
+ var ua = ((p4.x - p3.x)*(p1.y - p3.y) - (p4.y - p3.y)*(p1.x - p3.x)) / denom;
+ var ub = ((p2.x - p1.x)*(p1.y - p3.y) - (p2.y - p1.y)*(p1.x - p3.x)) / denom;
+
+ if (ua < 0 || ua > 1 || ub < 0 || ub > 1) {
+ return false;
+ }
+
+ return new Springy.Vector(p1.x + ua * (p2.x - p1.x), p1.y + ua * (p2.y - p1.y));
+ }
+
+ function intersect_line_box(p1, p2, p3, w, h) {
+ var tl = {x: p3.x, y: p3.y};
+ var tr = {x: p3.x + w, y: p3.y};
+ var bl = {x: p3.x, y: p3.y + h};
+ var br = {x: p3.x + w, y: p3.y + h};
+
+ var result;
+ if (result = intersect_line_line(p1, p2, tl, tr)) { return result; } // top
+ if (result = intersect_line_line(p1, p2, tr, br)) { return result; } // right
+ if (result = intersect_line_line(p1, p2, br, bl)) { return result; } // bottom
+ if (result = intersect_line_line(p1, p2, bl, tl)) { return result; } // left
+
+ return false;
+ }
+
+ return this;
+}
+
+})();
diff --git a/ocl_web/templates/base.html b/ocl_web/templates/base.html
index 680da5ca..fad549bb 100644
--- a/ocl_web/templates/base.html
+++ b/ocl_web/templates/base.html
@@ -25,6 +25,7 @@
+
@@ -38,6 +39,9 @@
+
+
+
{% block angular %}
{# was 1.2.9 #}
diff --git a/ocl_web/templates/concepts/concept_base.html b/ocl_web/templates/concepts/concept_base.html
index 828e41cc..72e9a619 100644
--- a/ocl_web/templates/concepts/concept_base.html
+++ b/ocl_web/templates/concepts/concept_base.html
@@ -261,10 +261,12 @@ - selected - selected Mappings
History
+ Relationship
Added the latest versions of concepts/mappings to the collection. Future updates will not be added automatically.
diff --git a/ocl_web/templates/concepts/concept_relationship.html b/ocl_web/templates/concepts/concept_relationship.html
new file mode 100644
index 00000000..80976058
--- /dev/null
+++ b/ocl_web/templates/concepts/concept_relationship.html
@@ -0,0 +1,186 @@
+{% extends "concepts/concept_base.html" %}
+{% load i18n %}
+{% load ocl_tags %}
+{% load bootstrap3 %}
+
+
+{% block tab-content %}
+
+
+
+
+ {% if concept.owner_type == 'Organization' %}
+ {% url 'concept-relationship' org=concept.owner source=concept.source concept=concept.id as concept_relationship_url %}
+ {% else %}
+ {% url 'concept-relationship' user=concept.owner source=concept.source concept=concept.id as concept_relationship_url %}
+ {% endif %}
+
+
+
+
+
+
+ {% for mapping in mappings %}
+ {{ mapping.id }}
+ {% endfor %}
+
+
+
+
+
+
+
+
+
Mappings
+
+ {% if concept.has_direct_mappings %}
+
+
+
+
+ Relationship
+ Source
+ Code
+ Name
+
+
+
+ {% for mapping in mappings|dictsort:"map_type" %}
+ {% if mapping.is_direct_mapping %}
+ {% if mapping.to_source_owner_type == 'Organization' %}
+ {% url 'org-home' org=mapping.to_source_owner as to_concept_owner_url %}
+ {% url 'source-home' org=mapping.to_source_owner source=mapping.to_source_name as to_concept_source_url %}
+ {% if mapping.is_internal_mapping %}
+ {% url 'concept-home' org=mapping.to_source_owner source=mapping.to_source_name concept=mapping.to_concept_code as to_concept_url %}
+ {% endif %}
+ {% else %}
+ {% url 'users:detail' mapping.to_source_owner as to_concept_owner_url %}
+ {% url 'source-home' user=mapping.to_source_owner source=mapping.to_source_name as to_concept_source_url %}
+ {% if mapping.is_internal_mapping %}
+ {% url 'concept-home' user=mapping.to_source_owner source=mapping.to_source_name concept=mapping.to_concept_code as to_concept_url %}
+ {% endif %}
+ {% endif %}
+
+
+ {% if mapping.is_external_mapping %} {% else %} {% endif %}
+ {{ mapping.map_type }}
+ {{ mapping.to_source_owner }} / {{ mapping.to_source_name }}
+ {% if mapping.is_internal_mapping %}{{ mapping.to_concept_code }} {% else %}{{ mapping.to_concept_code }}{% endif %}
+ {{ mapping.to_concept_name|default:"-" }}
+
+ {% endif %}
+ {% endfor %}
+
+
+ {% else %}
+
No direct mappings
+ {% endif %}
+
+
+
+
Inverse Mappings
+
+ {% if concept.has_inverse_mappings %}
+
+
+
+
+ Relationship
+ Source
+ Code
+ Name
+
+
+
+ {% for mapping in mappings|dictsort:"map_type" %}
+ {% if mapping.is_inverse_mapping %}
+ {% if mapping.to_source_owner_type == 'Organization' %}
+ {% url 'org-home' org=mapping.from_source_owner as from_concept_owner_url %}
+ {% url 'source-home' org=mapping.from_source_owner source=mapping.from_source_name as from_concept_source_url %}
+ {% url 'concept-home' org=mapping.from_source_owner source=mapping.from_source_name concept=mapping.from_concept_code as from_concept_url %}
+ {% else %}
+ {% url 'users:detail' mapping.from_source_owner as from_concept_owner_url %}
+ {% url 'source-home' user=mapping.from_source_owner source=mapping.from_source_name as from_concept_source_url %}
+ {% url 'concept-home' user=mapping.from_source_owner source=mapping.from_source_name concept=mapping.from_concept_code as from_concept_url %}
+ {% endif %}
+
+
+ {% if mapping.is_external_mapping %} {% else %} {% endif %}
+ {{ mapping.map_type }}
+ {{ mapping.from_source_owner }} / {{ mapping.from_source_name }}
+ {{ mapping.from_concept_code }}
+ {{ mapping.from_concept_name|default:"-" }}
+
+ {% endif %}
+ {% endfor %}
+
+
+ {% else %}
+
No inverse mappings
+ {% endif %}
+
+
+
+
+
+
+
+
+
+{% endblock tab-content %}
+
+
+{% block resource-debug %}
+
URL kwargs {{ kwargs|pprint }}
+
URL Parameters {{ url_params|pprint }}
+
Concept {{ concept|pprint }}
+
Mappings {{ mappings|pprint }}
+{% endblock resource-debug %}
+
+
+{% block extrajavascript %}
+
+{% endblock extrajavascript %}
From 3f5e3f81843f4681703ec8d8a1ae9726c11d3977 Mon Sep 17 00:00:00 2001
From: hao555sky <836095186@qq.com>
Date: Tue, 22 Aug 2017 20:27:54 +0800
Subject: [PATCH 4/4] finish the final objective
---
ocl_web/apps/concepts/views.py | 36 +--
ocl_web/apps/mappings/views.py | 1 +
ocl_web/config/orgs_urls.py | 6 +-
ocl_web/static/js/project.js | 9 +-
ocl_web/templates/base.html | 1 +
.../concepts/concept_relationship.html | 255 ++++++++----------
6 files changed, 125 insertions(+), 183 deletions(-)
diff --git a/ocl_web/apps/concepts/views.py b/ocl_web/apps/concepts/views.py
index 4a16917f..5daee22f 100644
--- a/ocl_web/apps/concepts/views.py
+++ b/ocl_web/apps/concepts/views.py
@@ -57,21 +57,18 @@ def get_concept_details(self, owner_type, owner_id, source_id, concept_id,
raise ValueError(
'Must specify only a source version or a concept version. Both were specified.')
elif source_version_id:
- print('11111')
search_response = api.get(
owner_type, owner_id,
'sources', source_id, source_version_id,
'concepts', concept_id,
params=params)
elif concept_version_id:
- print('22222')
search_response = api.get(
owner_type, owner_id,
'sources', source_id,
'concepts', concept_id, concept_version_id,
params=params)
else:
- print('33333')
search_response = api.get(
owner_type, owner_id,
'sources', source_id,
@@ -408,7 +405,7 @@ def get_context_data(self, *args, **kwargs):
api = OclApi(self.request, debug=True, facets=True)
selected_sources = self.request.GET.getlist('selected_source')
- print('selected_sources: ', selected_sources)
+ print('selected_sources: ', selected_sources)
print(len(selected_sources))
@@ -420,32 +417,16 @@ def get_context_data(self, *args, **kwargs):
source_version_id=self.source_version_id, concept_version_id=self.concept_version_id,
include_mappings=True, include_inverse_mappings=True)
- mappings.extend(concept['mappings'])
+ if concept.get('mappings', None):
+ mappings.extend(concept.get('mappings'))
if len(selected_sources) != 0:
for source_id in selected_sources:
search_response = api.get(self.owner_type, self.owner_id, 'sources', source_id, 'mappings')
for mapping in search_response.json()['results']:
- if (self.proper_owner_type == mapping['to_source_owner_type'] and
- self.owner_id == mapping['to_source_owner'] and
- self.source_id == mapping['to_source_name'] and
- self.concept_id == mapping['to_concept_code']):
- mapping['is_inverse_mapping'] = True
- concept['has_inverse_mappings'] = True
- mapping['is_direct_mapping'] = False
- else:
- mapping['is_direct_mapping'] = True
- mapping['is_inverse_mapping'] = False
- concept['has_direct_mappings'] = True
- if mapping['to_concept_url']:
- mapping['is_internal_mapping'] = True
- mapping['is_external_mapping'] = False
- else:
- mapping['is_internal_mapping'] = False
- mapping['is_external_mapping'] = True
-
- print('search_response : ', mapping)
- mappings.extend(search_response.json()['results'])
+ if mapping['from_concept_url'] == concept['url'] or mapping['to_concept_url'] == concept['url']:
+ mappings.append(mapping)
+ print('search_response : ', mapping)
print('\n\n')
if self.request.user.is_authenticated():
@@ -453,7 +434,9 @@ def get_context_data(self, *args, **kwargs):
all_sources = _get_org_or_user_sources_list2(self.request, str(self.request.user))
- print('mappings: ', mappings)
+ for mapping in mappings:
+ print('mapping: ', mapping)
+ print('\n\n')
print('\n\n')
# Set the context
@@ -461,6 +444,7 @@ def get_context_data(self, *args, **kwargs):
context['url_params'] = self.request.GET
context['selected_tab'] = 'Relationship'
context['concept'] = concept
+ context['concept1'] = json.dumps(concept)
context['mappings'] = json.dumps(mappings)
context['all_sources'] = all_sources
diff --git a/ocl_web/apps/mappings/views.py b/ocl_web/apps/mappings/views.py
index ff925398..2db9146b 100644
--- a/ocl_web/apps/mappings/views.py
+++ b/ocl_web/apps/mappings/views.py
@@ -161,6 +161,7 @@ def get_context_data(self, *args, **kwargs):
return context
+
class MappingVersionsView(UserOrOrgMixin, MappingReadBaseView):
"""`
Mapping Details view.
diff --git a/ocl_web/config/orgs_urls.py b/ocl_web/config/orgs_urls.py
index 82c1391b..7ac1a2e7 100644
--- a/ocl_web/config/orgs_urls.py
+++ b/ocl_web/config/orgs_urls.py
@@ -30,7 +30,7 @@
SourceVersionsNewView, SourceVersionsEditView, SourceVersionsRetireView, SourceDeleteView, SourceVersionEditJsonView, SourceVersionDeleteView)
from apps.concepts.views import (
ConceptDetailsView, ConceptMappingsView, ConceptHistoryView, ConceptEditView, ConceptDiffView,
- ConceptRetireView, ConceptNewView, ConceptForkView, ConceptDescView, ConceptNameView)
+ ConceptRetireView, ConceptNewView, ConceptForkView, ConceptDescView, ConceptNameView, ConceptRelationshipView)
from apps.mappings.views import (
MappingDetailsView, MappingNewView, MappingForkView, MappingEditView, MappingRetireView, MappingVersionsView)
from apps.collections.views import CollectionDetailView, CollectionCreateView, CollectionEditView, CollectionAboutView, \
@@ -213,6 +213,10 @@
url(r'^(?P
[a-zA-Z0-9\-\.]+)/sources/(?P[a-zA-Z0-9\-\.]+)/concepts/(?P[a-zA-Z0-9\-\.]+)/history/$', # pylint: disable=C0301
ConceptHistoryView.as_view(), name='concept-history'),
+ # /orgs/:org/sources/:source/concepts/:concept/relationship/
+ url(r'^(?P[a-zA-Z0-9\-\.]+)/sources/(?P[a-zA-Z0-9\-\.]+)/concepts/(?P[a-zA-Z0-9\-\.]+)/relationship/$',# pylint: disable=C0301
+ ConceptRelationshipView.as_view(), name='concept-relationship'),
+
# /orgs/:org/sources/:source/concepts/:concept/diff/
url(r'^(?P[a-zA-Z0-9\-\.]+)/sources/(?P[a-zA-Z0-9\-\.]+)/concepts/(?P[a-zA-Z0-9\-\.]+)/diff/$', # pylint: disable=C0301
ConceptDiffView.as_view(), name='concept-version-diff'),
diff --git a/ocl_web/static/js/project.js b/ocl_web/static/js/project.js
index a0d270bc..075a1e68 100644
--- a/ocl_web/static/js/project.js
+++ b/ocl_web/static/js/project.js
@@ -723,12 +723,9 @@ app.controller("MappingVersionsController", function ($scope, $http) {
}
});
-// app.controller("ConceptRelationshipController", function ($scope, $http) {
-// $scope.submitRelationshipForm = function (relationshipForm, concept_relationship_url) {
-// url = concept_relationship_url + "?selected_source=1&selected_source=2";
-// window.location.href = url;
-// }
-// });
+app.controller("ConceptRelationshipController", function ($scope, $http) {
+ pass;
+});
// Simple function to handle removing member from org
function removeMember(orgId, memId) {
diff --git a/ocl_web/templates/base.html b/ocl_web/templates/base.html
index fad549bb..1cf2c1c9 100644
--- a/ocl_web/templates/base.html
+++ b/ocl_web/templates/base.html
@@ -40,6 +40,7 @@
+
diff --git a/ocl_web/templates/concepts/concept_relationship.html b/ocl_web/templates/concepts/concept_relationship.html
index 80976058..644776d8 100644
--- a/ocl_web/templates/concepts/concept_relationship.html
+++ b/ocl_web/templates/concepts/concept_relationship.html
@@ -5,141 +5,62 @@
{% block tab-content %}
-
-
+
{% if concept.owner_type == 'Organization' %}
{% url 'concept-relationship' org=concept.owner source=concept.source concept=concept.id as concept_relationship_url %}
{% else %}
{% url 'concept-relationship' user=concept.owner source=concept.source concept=concept.id as concept_relationship_url %}
{% endif %}
-
-
-
-
-
- {% for mapping in mappings %}
- {{ mapping.id }}
- {% endfor %}
-
-
-
-
-
-
-
-
-
Mappings
-
- {% if concept.has_direct_mappings %}
-
-
-
-
- Relationship
- Source
- Code
- Name
-
-
-
- {% for mapping in mappings|dictsort:"map_type" %}
- {% if mapping.is_direct_mapping %}
- {% if mapping.to_source_owner_type == 'Organization' %}
- {% url 'org-home' org=mapping.to_source_owner as to_concept_owner_url %}
- {% url 'source-home' org=mapping.to_source_owner source=mapping.to_source_name as to_concept_source_url %}
- {% if mapping.is_internal_mapping %}
- {% url 'concept-home' org=mapping.to_source_owner source=mapping.to_source_name concept=mapping.to_concept_code as to_concept_url %}
- {% endif %}
- {% else %}
- {% url 'users:detail' mapping.to_source_owner as to_concept_owner_url %}
- {% url 'source-home' user=mapping.to_source_owner source=mapping.to_source_name as to_concept_source_url %}
- {% if mapping.is_internal_mapping %}
- {% url 'concept-home' user=mapping.to_source_owner source=mapping.to_source_name concept=mapping.to_concept_code as to_concept_url %}
- {% endif %}
- {% endif %}
-
-
- {% if mapping.is_external_mapping %} {% else %} {% endif %}
- {{ mapping.map_type }}
- {{ mapping.to_source_owner }} / {{ mapping.to_source_name }}
- {% if mapping.is_internal_mapping %}{{ mapping.to_concept_code }} {% else %}{{ mapping.to_concept_code }}{% endif %}
- {{ mapping.to_concept_name|default:"-" }}
-
- {% endif %}
- {% endfor %}
-
-
- {% else %}
-
No direct mappings
- {% endif %}
-
-
-
-
Inverse Mappings
-
- {% if concept.has_inverse_mappings %}
-
-
-
-
- Relationship
- Source
- Code
- Name
-
-
-
- {% for mapping in mappings|dictsort:"map_type" %}
- {% if mapping.is_inverse_mapping %}
- {% if mapping.to_source_owner_type == 'Organization' %}
- {% url 'org-home' org=mapping.from_source_owner as from_concept_owner_url %}
- {% url 'source-home' org=mapping.from_source_owner source=mapping.from_source_name as from_concept_source_url %}
- {% url 'concept-home' org=mapping.from_source_owner source=mapping.from_source_name concept=mapping.from_concept_code as from_concept_url %}
- {% else %}
- {% url 'users:detail' mapping.from_source_owner as from_concept_owner_url %}
- {% url 'source-home' user=mapping.from_source_owner source=mapping.from_source_name as from_concept_source_url %}
- {% url 'concept-home' user=mapping.from_source_owner source=mapping.from_source_name concept=mapping.from_concept_code as from_concept_url %}
- {% endif %}
-
-
- {% if mapping.is_external_mapping %} {% else %} {% endif %}
- {{ mapping.map_type }}
- {{ mapping.from_source_owner }} / {{ mapping.from_source_name }}
- {{ mapping.from_concept_code }}
- {{ mapping.from_concept_name|default:"-" }}
-
- {% endif %}
- {% endfor %}
-
-
- {% else %}
-
No inverse mappings
- {% endif %}
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
Tip
+
+
The Concept Relations tab displays all direct and inverse mappings stored in this default source and sources the user selected.
+
+
+
+
+
+
+
{% endblock tab-content %}
@@ -157,29 +78,63 @@ Mappings {{ mappings|pprint }}
$(document).ready(function() {
$('#selected_source').multiselect();
-// var mappings = {{ mappings | safe }};
-
-// var graph = new Springy.Graph();
-//
-// for(var i=0; i