diff --git a/invenio/templates/page.html b/invenio/templates/page.html index 5fea41a13e..f7abc13093 100644 --- a/invenio/templates/page.html +++ b/invenio/templates/page.html @@ -34,6 +34,7 @@ {# Global CSS #} {%- css 'css/bootstrap.css', '00-invenio' -%} {%- css 'css/bootstrap-responsive.min.css', '00-invenio' -%} +{%- css 'css/bootstrap-multiselect.css', '00-invenio' -%} {%- css 'css/token-input.css', '00-invenio' -%} {%- css 'css/token-input-facebook.css', '00-invenio' -%} {%- css 'css/b2s-common.css', '00-invenio' -%} @@ -42,6 +43,7 @@ {# Global Javascript files #} {%- js 'js/jquery.min.js', '00-invenio' -%} {%- js 'js/bootstrap.js', '00-invenio' -%} +{%- js 'js/bootstrap-multiselect.js', '00-invenio' -%} {%- js 'js/jquery.tokeninput.js', '00-invenio' -%} {%- js 'js/invenio.js', '00-invenio' -%} diff --git a/simplestore/etc/static/css/bootstrap-multiselect.css b/simplestore/etc/static/css/bootstrap-multiselect.css new file mode 100644 index 0000000000..4d8bd5c8b7 --- /dev/null +++ b/simplestore/etc/static/css/bootstrap-multiselect.css @@ -0,0 +1 @@ +.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>label.multiselect-group{margin:0;padding:3px 20px;height:100%;font-weight:700}.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} \ No newline at end of file diff --git a/simplestore/etc/static/css/simplestore-style.css b/simplestore/etc/static/css/simplestore-style.css index 6568dc6208..d581472928 100755 --- a/simplestore/etc/static/css/simplestore-style.css +++ b/simplestore/etc/static/css/simplestore-style.css @@ -199,6 +199,7 @@ } #meta-fields { + overflow: visible; text-align: left; } @@ -298,3 +299,30 @@ a.description:hover span { border:10px solid #666; background-color:#666; color:#fff } + +.plus, .minus { + width:30px; + height:30px; + overflow:hidden; +} + +.plus { + background: url(/img/plus.png); +} + +.minus { + background: url(/img/minus.png); +} + +.add_field { + float:left; + width:240px; +} + +.collapse.in { + overflow: visible; +} + +.multiselect { + width:284px; +} \ No newline at end of file diff --git a/simplestore/etc/static/img/minus.png b/simplestore/etc/static/img/minus.png new file mode 100644 index 0000000000..896824ca94 Binary files /dev/null and b/simplestore/etc/static/img/minus.png differ diff --git a/simplestore/etc/static/img/plus.png b/simplestore/etc/static/img/plus.png new file mode 100644 index 0000000000..267ea64b53 Binary files /dev/null and b/simplestore/etc/static/img/plus.png differ diff --git a/simplestore/etc/static/js/bootstrap-multiselect.js b/simplestore/etc/static/js/bootstrap-multiselect.js new file mode 100644 index 0000000000..852042416f --- /dev/null +++ b/simplestore/etc/static/js/bootstrap-multiselect.js @@ -0,0 +1,994 @@ +/** + * bootstrap-multiselect.js + * https://github.com/davidstutz/bootstrap-multiselect + * + * Copyright 2012 - 2014 David Stutz + * + * Dual licensed under the BSD-3-Clause and the Apache License, Version 2.0. + */ +!function($) { + + "use strict";// jshint ;_; + + if (typeof ko !== 'undefined' && ko.bindingHandlers && !ko.bindingHandlers.multiselect) { + ko.bindingHandlers.multiselect = { + + init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { + + var listOfSelectedItems = allBindingsAccessor().selectedOptions, + config = ko.utils.unwrapObservable(valueAccessor()); + + $(element).multiselect(config); + + if (isObservableArray(listOfSelectedItems)) { + // Subscribe to the selectedOptions: ko.observableArray + listOfSelectedItems.subscribe(function (changes) { + var addedArray = [], deletedArray = []; + changes.forEach(function (change) { + switch (change.status) { + case 'added': + addedArray.push(change.value); + break; + case 'deleted': + deletedArray.push(change.value); + break; + } + }); + if (addedArray.length > 0) { + $(element).multiselect('select', addedArray); + }; + if (deletedArray.length > 0) { + $(element).multiselect('deselect', deletedArray); + }; + }, null, "arrayChange"); + } + }, + + update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { + + var listOfItems = allBindingsAccessor().options, + ms = $(element).data('multiselect'), + config = ko.utils.unwrapObservable(valueAccessor()); + + if (isObservableArray(listOfItems)) { + // Subscribe to the options: ko.observableArray incase it changes later + listOfItems.subscribe(function (theArray) { + $(element).multiselect('rebuild'); + }); + } + + if (!ms) { + $(element).multiselect(config); + } + else { + ms.updateOriginalOptions(); + } + } + }; + } + + function isObservableArray(obj) { + return ko.isObservable(obj) && !(obj.destroyAll === undefined); + } + + /** + * Constructor to create a new multiselect using the given select. + * + * @param {jQuery} select + * @param {Object} options + * @returns {Multiselect} + */ + function Multiselect(select, options) { + + this.options = this.mergeOptions(options); + this.$select = $(select); + + // Initialization. + // We have to clone to create a new reference. + this.originalOptions = this.$select.clone()[0].options; + this.query = ''; + this.searchTimeout = null; + + this.options.multiple = this.$select.attr('multiple') === "multiple"; + this.options.onChange = $.proxy(this.options.onChange, this); + this.options.onDropdownShow = $.proxy(this.options.onDropdownShow, this); + this.options.onDropdownHide = $.proxy(this.options.onDropdownHide, this); + + // Build select all if enabled. + this.buildContainer(); + this.buildButton(); + this.buildSelectAll(); + this.buildDropdown(); + this.buildDropdownOptions(); + this.buildFilter(); + + this.updateButtonText(); + this.updateSelectAll(); + + this.$select.hide().after(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 (options.length === 0) { + return this.nonSelectedText + ' '; + } + else { + if (options.length > this.numberDisplayed) { + return options.length + ' ' + this.nSelectedText + ' '; + } + else { + var selected = ''; + options.each(function() { + var label = ($(this).attr('label') !== undefined) ? $(this).attr('label') : $(this).html(); + + selected += label + ', '; + }); + return selected.substr(0, selected.length - 2) + ' '; + } + } + }, + /** + * 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 = ''; + options.each(function () { + selected += $(this).text() + ', '; + }); + return selected.substr(0, selected.length - 2); + } + }, + /** + * Create a label. + * + * @param {jQuery} element + * @returns {String} + */ + label: function(element){ + return $(element).attr('label') || $(element).html(); + }, + /** + * 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) { + + }, + buttonClass: 'btn btn-default', + dropRight: false, + selectedClass: 'active', + buttonWidth: 'auto', + buttonContainer: '
', + // Maximum height of the dropdown menu. + // If maximum height is exceeded a scrollbar will be displayed. + maxHeight: false, + checkboxName: 'multiselect', + includeSelectAllOption: false, + includeSelectAllIfMoreThan: 0, + selectAllText: ' Select all', + selectAllValue: 'multiselect-all', + enableFiltering: false, + enableCaseInsensitiveFiltering: false, + filterPlaceholder: 'Search', + // possible options: 'text', 'value', 'both' + filterBehavior: 'text', + preventInputChangeEvent: false, + nonSelectedText: 'None selected', + nSelectedText: 'selected', + numberDisplayed: 3, + templates: { + button: '', + ul: '', + filter: '
', + 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); + }, + + /** + * Builds the button of the multiselect. + */ + buildButton: function() { + this.$button = $(this.options.templates.button).addClass(this.options.buttonClass); + + // 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' : 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' + }); + } + + this.$container.append(this.$ul); + }, + + /** + * Build the dropdown options and binds all nessecary events. + * Uses createDivider and createOptionValue to create the necessary options. + */ + buildDropdownOptions: function() { + + this.$select.children().each($.proxy(function(index, element) { + + // Support optgroups and options without a group simultaneously. + var tag = $(element).prop('tagName') + .toLowerCase(); + + 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 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.parents('li') + .addClass(this.options.selectedClass); + } + else { + $target.parents('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) { + var values = []; + + // Select the visible checkboxes except the "select-all" and possible divider. + var availableInputs = $('li input[value!="' + this.options.selectAllValue + '"][data-role!="divider"]', this.$ul).filter(':visible'); + for (var i = 0, j = availableInputs.length; i < j; i++) { + values.push(availableInputs[i].value); + } + + if (checked) { + this.select(values); + } + else { + this.deselect(values); + } + } + + 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).parents('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.parents("a").css("outline", ""); + } + } + else { + // Unselect option. + $option.prop('selected', false); + } + + this.$select.change(); + this.options.onChange($option, checked); + + this.updateButtonText(); + this.updateSelectAll(); + + if(this.options.preventInputChangeEvent) { + return false; + } + }, this)); + + $('li a', this.$ul).on('touchstart click', function(event) { + event.stopPropagation(); + + var $target = $(event.target); + + if (event.shiftKey) { + var checked = $target.prop('checked') || false; + + if (checked) { + var prev = $target.parents('li:last') + .siblings('li[class="active"]:first'); + + var currentIdx = $target.parents('li') + .index(); + var prevIdx = prev.index(); + + if (currentIdx > prevIdx) { + $target.parents("li:last").prevUntil(prev).each( + function() { + $(this).find("input:first").prop("checked", true) + .trigger("change"); + } + ); + } + else { + $target.parents("li:last").nextUntil(prev).each( + function() { + $(this).find("input:first").prop("checked", true) + .trigger("change"); + } + ); + } + } + } + + $target.blur(); + }); + + // Keyboard support. + this.$container.on('keydown', $.proxy(function(event) { + if ($('input[type="text"]', this.$container).is(':focus')) { + return; + } + if ((event.keyCode === 9 || event.keyCode === 27) + && this.$container.hasClass('open')) { + + // Close on tab or escape. + this.$button.click(); + } + else { + var $items = $(this.$container).find("li:not(.divider):visible a"); + + 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)); + }, + + /** + * Create an option using the given select option. + * + * @param {jQuery} element + */ + createOptionValue: function(element) { + if ($(element).is(':selected')) { + $(element).prop('selected', true); + } + + // Support the label attribute on options. + var label = this.options.label(element); + var value = $(element).val(); + var inputType = this.options.multiple ? "checkbox" : "radio"; + + var $li = $(this.options.templates.li); + $('label', $li).addClass(inputType); + $('label', $li).append(''); + + var selected = $(element).prop('selected') || false; + var $checkbox = $('input', $li); + $checkbox.val(value); + + if (value === this.options.selectAllValue) { + $checkbox.parent().parent() + .addClass('multiselect-all'); + } + + $('label', $li).append(" " + label); + + this.$ul.append($li); + + if ($(element).is(':disabled')) { + $checkbox.attr('disabled', 'disabled') + .prop('disabled', true) + .parents('li') + .addClass('disabled'); + } + + $checkbox.prop('checked', selected); + + if (selected && this.options.selectedClass) { + $checkbox.parents('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 groupName = $(group).prop('label'); + + // Add a header for the group. + var $li = $(this.options.templates.liGroup); + $('label', $li).text(groupName); + + this.$ul.append($li); + + if ($(group).is(':disabled')) { + $li.addClass('disabled'); + } + + // Add the options of the group. + $('option', group).each($.proxy(function(index, element) { + this.createOptionValue(element); + }, this)); + }, + + /** + * Build the selct all. + * Checks if a select all ahs already been created. + */ + buildSelectAll: function() { + var alreadyHasSelectAll = this.hasSelectAll(); + + if (!alreadyHasSelectAll && this.options.includeSelectAllOption && this.options.multiple + && $('option[data-role!="divider"]', this.$select).length > this.options.includeSelectAllIfMoreThan) { + + // Check whether to add a divider after the select all. + if (this.options.includeSelectAllDivider) { + this.$select.prepend(''); + } + }, + + /** + * 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); + this.$ul.prepend(this.$filter); + + this.$filter.val(this.query).on('click', function(event) { + event.stopPropagation(); + }).on('input keydown', $.proxy(function(event) { + // 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; + + $.each($('li', this.$ul), $.proxy(function(index, element) { + var value = $('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.toLowerCase().indexOf(this.query.toLowerCase()) > -1) { + showElement = true; + } + else if (filterCandidate.indexOf(this.query) > -1) { + showElement = true; + } + + if (showElement) { + $(element).show(); + } + else { + $(element).hide(); + } + } + }, this)); + } + + // TODO: check whether select all option needs to be updated. + }, this), 300, this); + }, this)); + } + } + }, + + /** + * Unbinds the whole plugin. + */ + destroy: function() { + this.$container.remove(); + this.$select.show(); + this.$select.data('multiselect', null); + }, + + /** + * Refreshs the multiselect based on the selected options of the select. + */ + refresh: function() { + $('option', this.$select).each($.proxy(function(index, element) { + var $input = $('li input', this.$ul).filter(function() { + return $(this).val() === $(element).val(); + }); + + if ($(element).is(':selected')) { + $input.prop('checked', true); + + if (this.options.selectedClass) { + $input.parents('li') + .addClass(this.options.selectedClass); + } + } + else { + $input.prop('checked', false); + + if (this.options.selectedClass) { + $input.parents('li') + .removeClass(this.options.selectedClass); + } + } + + if ($(element).is(":disabled")) { + $input.attr('disabled', 'disabled') + .prop('disabled', true) + .parents('li') + .addClass('disabled'); + } + else { + $input.prop('disabled', false) + .parents('li') + .removeClass('disabled'); + } + }, this)); + + this.updateButtonText(); + this.updateSelectAll(); + }, + + /** + * Select all options of the given values. + * + * @param {Array} selectValues + */ + select: function(selectValues) { + if(!$.isArray(selectValues)) { + selectValues = [selectValues]; + } + + for (var i = 0; i < selectValues.length; i++) { + var value = selectValues[i]; + + var $option = this.getOptionByValue(value); + var $checkbox = this.getInputByValue(value); + + if (this.options.selectedClass) { + $checkbox.parents('li') + .addClass(this.options.selectedClass); + } + + $checkbox.prop('checked', true); + $option.prop('selected', true); + } + + this.updateButtonText(); + }, + + /** + * Clears all selected items + * + */ + clearSelection: function () { + + var selected = this.getSelected(); + + if (selected.length) { + + var arry = []; + + for (var i = 0; i < selected.length; i = i + 1) { + arry.push(selected[i].value); + } + + this.deselect(arry); + this.$select.change(); + } + }, + + /** + * Deselects all options of the given values. + * + * @param {Array} deselectValues + */ + deselect: function(deselectValues) { + if(!$.isArray(deselectValues)) { + deselectValues = [deselectValues]; + } + + for (var i = 0; i < deselectValues.length; i++) { + + var value = deselectValues[i]; + + var $option = this.getOptionByValue(value); + var $checkbox = this.getInputByValue(value); + + if (this.options.selectedClass) { + $checkbox.parents('li') + .removeClass(this.options.selectedClass); + } + + $checkbox.prop('checked', false); + $option.prop('selected', false); + } + + this.updateButtonText(); + }, + + /** + * Rebuild the plugin. + * Rebuilds the dropdown, the filter and the select all option. + */ + rebuild: function() { + this.$ul.html(''); + + // Remove select all option in select. + $('option[value="' + this.options.selectAllValue + '"]', this.$select).remove(); + + // 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(); + }, + + /** + * The provided data will be used to build the dropdown. + * + * @param {Array} dataprovider + */ + dataprovider: function(dataprovider) { + var optionDOM = ""; + dataprovider.forEach(function (option) { + optionDOM += ''; + }); + + this.$select.html(optionDOM); + 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, options); + }, + + /** + * Checks whether a select all option is present. + * + * @returns {Boolean} + */ + hasSelectAll: function() { + return $('option[value="' + this.options.selectAllValue + '"]', this.$select).length > 0; + }, + + /** + * Updates the select all option based on the currently selected options. + */ + updateSelectAll: function() { + if (this.hasSelectAll()) { + var selected = this.getSelected(); + + if (selected.length === $('option:not([data-role=divider])', this.$select).length - 1) { + this.select(this.options.selectAllValue); + } + else { + this.deselect(this.options.selectAllValue); + } + } + }, + + /** + * 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. + $('button', this.$container).html(this.options.buttonText(options, this.$select)); + + // Now update the title attribute of the button. + $('button', this.$container).attr('title', this.options.buttonTitle(options, this.$select)); + + }, + + /** + * Get all selected options. + * + * @returns {jQUery} + */ + getSelected: function() { + return $('option[value!="' + this.options.selectAllValue + '"]:selected', this.$select).filter(function() { + return $(this).prop('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', 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); + } + }; + + $.fn.multiselect = function(option, parameter) { + 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); + + if (option === 'destroy') { + $(this).data('multiselect', false); + } + } + }); + }; + + $.fn.multiselect.Constructor = Multiselect; + + $(function() { + $("select[data-role=multiselect]").multiselect(); + }); + +}(window.jQuery); diff --git a/simplestore/lib/simplestore_marc_handler.py b/simplestore/lib/simplestore_marc_handler.py index a8e56337f6..26b6025727 100644 --- a/simplestore/lib/simplestore_marc_handler.py +++ b/simplestore/lib/simplestore_marc_handler.py @@ -42,11 +42,12 @@ def add_basic_fields(rec, form, email): if form['title']: record_add_field(rec, '245', subfields=[('a', remove_html_markup(form['title']))]) - if form['creator']: - for kw in form['creator'].split(';'): - if kw and not kw.isspace(): - record_add_field(rec, '100', subfields=[('a', remove_html_markup(kw.strip()))]) - + if form['creator']: + fields = form.getlist('creator') + for f in fields: + if f and not f.isspace(): + record_add_field(rec, '100', subfields=[('a', remove_html_markup(f.strip()))]) + if form['domain']: record_add_field(rec, '980', subfields=[('a', remove_html_markup(form['domain']))]) pubfields = [] @@ -75,14 +76,18 @@ def add_basic_fields(rec, form, email): subfields=[('a', remove_html_markup(kw.strip()))]) if form['contributors']: - for kw in form['contributors'].split(';'): - record_add_field(rec, '700', subfields=[('a', remove_html_markup(kw.strip()))]) + fields = form.getlist('contributors') + for f in fields: + if f and not f.isspace(): + record_add_field(rec, '700', subfields=[('a', remove_html_markup(f.strip()))]) record_add_field(rec, '546', subfields=[('a', remove_html_markup(form['language']))]) # copying zenodo here, but I don't think 980 is the right MARC field if form['resource_type']: - record_add_field(rec, '980', subfields=[('a', remove_html_markup(form['resource_type']))]) + fields = form.getlist('resource_type') + for f in fields: + record_add_field(rec, '980', subfields=[('a', remove_html_markup(form['resource_type']))]) if form['alternate_identifier']: record_add_field(rec, '024', @@ -166,9 +171,12 @@ def add_domain_fields(rec, form): if fs.name != 'Generic': # TODO: this is brittle; get from somewhere for k in (fs.optional_fields + fs.basic_fields): if form[k]: - record_add_field(rec, '690', - subfields=[('a', k), ('b', form[k])]) - + fields = form.getlist(k) + for f in fields: + if f and not f.isspace(): + record_add_field(rec, '690', + subfields=[('a', k), ('b', f)]) + def add_epic_pid(rec, recid, checksum): """ Adds EPIC PID to the record. If registration fails, can diff --git a/simplestore/lib/simplestore_model/HTML5ModelConverter.py b/simplestore/lib/simplestore_model/HTML5ModelConverter.py index e7e2687f00..06d2eeeb9d 100644 --- a/simplestore/lib/simplestore_model/HTML5ModelConverter.py +++ b/simplestore/lib/simplestore_model/HTML5ModelConverter.py @@ -180,11 +180,17 @@ def __init__(self, placeholder="", **kwargs): class SelectWithInput(Select): def __call__(self, field, **kwargs): kwargs.setdefault('id', field.id) - html = [' 1: + html.append('class="multiselect" multiple="multiple" ') + html.append('%s>' % html_params(name=field.name, **kwargs)) + for val, label, selected in field.iter_choices(): html.append(self.render_option(val, label, selected)) html.append('') - html.append('' + if field.other: + html.append('' .format(html_params(name=field.name+"_input"), html_params(id=field.name+"_input"))) return HTMLString(''.join(html)) @@ -192,14 +198,46 @@ def __call__(self, field, **kwargs): class SelectFieldWithInput(SelectField): widget = SelectWithInput() + cardinality = "" + filtering = "" + other = "" - def __init__(self, other="", **field_args): - self.field_args = field_args + def __init__(self, other="", filtering="", cardinality="1", + data_provide="", data_source="", **field_args): # make list of tuples for SelectField (only once) - if isinstance(self.field_args['choices'][0], basestring): - self.field_args['choices'] = [(x,x) for x in field_args['choices']] - self.field_args['choices'].append(('other', other)) + self.cardinality = cardinality + self.other = other + self.filtering = filtering + if isinstance(data_source[0], basestring): + field_args['choices'] = [(x,x) for x in data_source] + field_args['choices'].append(('other', other)) super(SelectFieldWithInput, self).__init__(**field_args) + + +class AddFieldInput(Input): + input_type = "text" + + def __call__(self, field, **kwargs): + kwargs.setdefault('id', field.id) + html = ['
    '] + html.append('
    ') + html.append('' + .format(field.placeholder, self.html_params(name=field.name, **kwargs))) + html.append('
    ' + .format(field.placeholder, field.cardinality, field.name)) + html.append('
    ') + html.append('
    ') + return HTMLString(''.join(html)) + +class AddField(StringField): + widget = AddFieldInput() + placeholder = "" + cardinality = "" + + def __init__(self, cardinality="n", placeholder="", **field_args): + self.placeholder = placeholder + self.cardinality = cardinality + super(AddField, self).__init__(**field_args) class HiddenInput(Input): @@ -269,19 +307,17 @@ def conv_String(self, field_args, **extra): if hidden: return hidden - if 'placeholder' in field_args: - return PlaceholderStringField(**field_args) - if 'data_provide' in field_args: - return TypeAheadStringField(**field_args) - - # SelectField - if 'choices' in field_args: - if 'other' in field_args: + if field_args['data_provide'] == 'typeahead': + return TypeAheadStringField(**field_args) + + if field_args['data_provide'] == 'select': return SelectFieldWithInput(**field_args) + + if 'cardinality' in field_args: + return AddField(**field_args) - if isinstance(field_args['choices'][0], basestring): - field_args['choices'] = [(x,x) for x in field_args['choices']] - return SelectField(**field_args) + if 'placeholder' in field_args: + return PlaceholderStringField(**field_args) return StringField(**field_args) diff --git a/simplestore/lib/simplestore_model/model.py b/simplestore/lib/simplestore_model/model.py index 82d19823f9..d601351c11 100644 --- a/simplestore/lib/simplestore_model/model.py +++ b/simplestore/lib/simplestore_model/model.py @@ -44,7 +44,7 @@ class SubmissionMetadata(db.Model): id = db.Column(db.Integer, primary_key=True) description = db.Column(db.Text(), nullable=False) - creator = db.Column(db.String(256)) # split on ; + creator = db.Column(db.String(256)) title = db.Column(db.String(256), nullable=False) open_access = db.Column(db.Boolean(), default=True) @@ -55,7 +55,7 @@ class SubmissionMetadata(db.Model): keywords = db.Column(db.String(256)) # split on , # optional - contributors = db.Column(db.String(256)) # split on ; + contributors = db.Column(db.String(256)) #language = db.Column(db.Enum(*babel.core.LOCALE_ALIASES.keys())) language = db.Column(db.String(128), default=language_default) resource_type = db.Column(db.String(256)) # XXX should be extracted to a separate class @@ -63,7 +63,7 @@ class SubmissionMetadata(db.Model): version = db.Column(db.String(128)) basic_fields = ['title', 'description', 'creator', 'open_access', - 'licence', 'publisher', 'publication_date','language', 'keywords'] + 'licence', 'publisher', 'publication_date', 'language', 'keywords'] optional_fields = ['contributors', 'resource_type', 'alternate_identifier', 'version'] @@ -137,7 +137,8 @@ def __init__(self): 'will not be public, however the metadata will be.' } self.field_args['contributors'] = { - 'placeholder': 'contributor 1; contributor 2; ...', + 'placeholder': 'contributor', + 'cardinality': 'n', 'description': 'A semicolon separated list of all other ' +\ 'contributors. Mention all ' +\ @@ -145,13 +146,14 @@ def __init__(self): } self.field_args['language'] = { 'hidden': True, - 'value': self.language_default + 'value': self.language_default, # 'description': # 'The name of the language the document is written in.' } self.field_args['resource_type'] = { - 'choices': ['Text', 'Image', 'Video'], # choices -> SelectField - 'other': 'Other...', # other -> dynamic input text field + 'data_provide': 'select', + 'cardinality': 'n', + 'data_source': ['Text', 'Image', 'Video', 'Other'], 'description': 'Select the type of the resource.' } @@ -161,7 +163,8 @@ def __init__(self): 'Any kind of other reference such as a URN, URI or an ISBN number.' } self.field_args['creator'] = { - 'placeholder': 'author 1; author 2; ... ', + 'placeholder': 'author', + 'cardinality': 'n', 'description': 'A semicolon separated list of authors of the resource.' } @@ -244,4 +247,9 @@ def is_external_attr(n): args['field_args'][f['name']]['placeholder'] = f.get('placeholder') if 'value' in f: args['field_args'][f['name']]['value'] = f.get('value') + if 'other' in f: + args['field_args'][f['name']]['other'] = f.get('other') + if 'cardinality' in f: + args['field_args'][f['name']]['cardinality'] = f.get('cardinality') + return type(clsname, (SubmissionMetadata,), args)