<commit_before>/*
 * jQuery Plugin: Tokenizing Autocomplete Text Entry
 * Version 1.6.0
 *
 * Copyright (c) 2009 James Smith (http://loopj.com)
 * Licensed jointly under the GPL and MIT licenses,
 * choose which one suits your project best!
 *
 */

(function ($) {
// Default settings
var DEFAULT_SETTINGS = {
    // Search settings
    method: "GET",
    queryParam: "q",
    searchDelay: 300,
    minChars: 1,
    propertyToSearch: "name",
    jsonContainer: null,
    contentType: "json",

	// Prepopulation settings
    prePopulate: null,
    processPrePopulate: false,

    // Display settings
    hintText: "Type in a search term",
    noResultsText: "No results",
    searchingText: "Searching...",
    deleteText: "×",
    animateDropdown: true,
    theme: null,
    resultsFormatter: function(item){ return "
" + item[this.propertyToSearch]+ "
" },
    tokenFormatter: function(item) { return "

" + item[this.propertyToSearch] + "

" },

    // Tokenization settings
    tokenLimit: null,
    tokenDelimiter: ",",
    preventDuplicates: false,
    tokenValue: "id",

    // Callbacks
    onResult: null,
    onAdd: null,
    onDelete: null,
    onReady: null,

    // Other settings
    idPrefix: "token-input-",

	// Allow New Value
	allowNewItems : true ,
	allowNewItemsPrefix : 'custom-',

};

// Default classes to use when theming
var DEFAULT_CLASSES = {
    tokenList: "token-input-list",
    token: "token-input-token",
    tokenDelete: "token-input-delete-token",
    selectedToken: "token-input-selected-token",
    highlightedToken: "token-input-highlighted-token",
    dropdown: "token-input-dropdown",
    dropdownItem: "token-input-dropdown-item",
    dropdownItem2: "token-input-dropdown-item2",
    selectedDropdownItem: "token-input-selected-dropdown-item",
    inputToken: "token-input-input-token"
};

// Input box position "enum"
var POSITION = {
    BEFORE: 0,
    AFTER: 1,
    END: 2
};

// Keys "enum"
var KEY = {
    BACKSPACE: 8,
    TAB: 9,
    ENTER: 13,
    ESCAPE: 27,
    SPACE: 32,
    PAGE_UP: 33,
    PAGE_DOWN: 34,
    END: 35,
    HOME: 36,
    LEFT: 37,
    UP: 38,
    RIGHT: 39,
    DOWN: 40,
    NUMPAD_ENTER: 108,
    COMMA: 188
};

// Additional public (exposed) methods
var methods = {
    init: function(url_or_data_or_function, options) {
        var settings = $.extend({}, DEFAULT_SETTINGS, options || {});

        return this.each(function () {
            $(this).data("tokenInputObject", new $.TokenList(this, url_or_data_or_function, settings));
        });
    },
    clear: function() {
        this.data("tokenInputObject").clear();
        return this;
    },
    add: function(item) {
        this.data("tokenInputObject").add(item);
        return this;
    },
    remove: function(item) {
        this.data("tokenInputObject").remove(item);
        return this;
    },
    get: function() {
        return this.data("tokenInputObject").getTokens();
    }
}

// Expose the .tokenInput function to jQuery as a plugin
$.fn.tokenInput = function (method) {
    // Method calling and initialization logic
    if(methods[method]) {
        return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
    } else {
        return methods.init.apply(this, arguments);
    }
};

// TokenList class for each input
$.TokenList = function (input, url_or_data, settings) {
    //
    // Initialization
    //

    // Configure the data source
    if($.type(url_or_data) === "string" || $.type(url_or_data) === "function") {
        // Set the url to query against
        settings.url = url_or_data;

        // If the URL is a function, evaluate it here to do our initalization work
        var url = computeURL();

        // Make a smart guess about cross-domain if it wasn't explicitly specified
        if(settings.crossDomain === undefined) {
            if(url.indexOf("://") === -1) {
                settings.crossDomain = false;
            } else {
                settings.crossDomain = (location.href.split(/\/+/g)[1] !== url.split(/\/+/g)[1]);
            }
        }
    } else if(typeof(url_or_data) === "object") {
        // Set the local data to search through
        settings.local_data = url_or_data;
    }

    // Build class names
    if(settings.classes) {
        // Use custom class names
        settings.classes = $.extend({}, DEFAULT_CLASSES, settings.classes);
    } else if(settings.theme) {
        // Use theme-suffixed default class names
        settings.classes = {};
        $.each(DEFAULT_CLASSES, function(key, value) {
            settings.classes[key] = value + "-" + settings.theme;
        });
    } else {
        settings.classes = DEFAULT_CLASSES;
    }

    // Save the tokens
    var saved_tokens = [];

    // Keep track of the number of tokens in the list
    var token_count = 0;

    // Basic cache to save on db hits
    var cache = new $.TokenList.Cache();

    // Keep track of the timeout, old vals
    var timeout;
    var input_val;

    // Create a new text input an attach keyup events
    var input_box = $("<input type=\"text\"  autocomplete=\"off\">")
        .css({
            outline: "none"
        })
        .attr("id", settings.idPrefix + input.id)
        .focus(function () {
            if (settings.tokenLimit === null || settings.tokenLimit !== token_count) {
                show_dropdown_hint();
            }
        })
        .blur(function () {
            hide_dropdown();
            // $(this).val("");
        })
        .bind("keyup keydown blur update", resize_input)
        .keydown(function (event) {
            var previous_token;
            var next_token;

            switch(event.keyCode) {
                case KEY.LEFT:
                case KEY.RIGHT:
                case KEY.UP:
                case KEY.DOWN:
                    if(!$(this).val()) {
                        previous_token = input_token.prev();
                        next_token = input_token.next();

                        if((previous_token.length && previous_token.get(0) === selected_token) || (next_token.length && next_token.get(0) === selected_token)) {
                            // Check if there is a previous/next token and it is selected
                            if(event.keyCode === KEY.LEFT || event.keyCode === KEY.UP) {
                                deselect_token($(selected_token), POSITION.BEFORE);
                            } else {
                                deselect_token($(selected_token), POSITION.AFTER);
                            }
                        } else if((event.keyCode === KEY.LEFT || event.keyCode === KEY.UP) && previous_token.length) {
                            // We are moving left, select the previous token if it exists
                            select_token($(previous_token.get(0)));
                        } else if((event.keyCode === KEY.RIGHT || event.keyCode === KEY.DOWN) && next_token.length) {
                            // We are moving right, select the next token if it exists
                            select_token($(next_token.get(0)));
                        }
                    } else {
                        var dropdown_item = null;

                        if(event.keyCode === KEY.DOWN || event.keyCode === KEY.RIGHT) {
                            dropdown_item = $(selected_dropdown_item).next();
                        } else {
                            dropdown_item = $(selected_dropdown_item).prev();
                        }

                        if(dropdown_item.length) {
                            select_dropdown_item(dropdown_item);
                        }
                        return false;
                    }
                    break;

                case KEY.BACKSPACE:
                    previous_token = input_token.prev();

                    if(!$(this).val().length) {
                        if(selected_token) {
                            delete_token($(selected_token));
                            hidden_input.change();
                        } else if(previous_token.length) {
                            select_token($(previous_token.get(0)));
                        }

                        return false;
                    } else if($(this).val().length === 1) {
                        hide_dropdown();
                    } else {
                        // set a timeout just long enough to let this function finish.
                        setTimeout(function(){do_search();}, 5);
                    }
                    break;

                case KEY.TAB:
                case KEY.ENTER:
                case KEY.NUMPAD_ENTER:
									if(selected_dropdown_item) {
                    add_token($(selected_dropdown_item).data("tokeninput"));
                    hidden_input.change();
                  	return false;
                  }
				  				else if( settings.allowNewItems && $(this).val()) {
										var item = {};
										item[settings.tokenValue] = settings.allowNewItemsPrefix+$(this).val();
										item[settings.propertyToSearch] = $(this).val();

										add_token(item);
										return false;
									  }
					                  break;
									break;
                case KEY.COMMA:
                  //if(selected_dropdown_item) {
                  //  add_token($(selected_dropdown_item).data("tokeninput"));
                  //  hidden_input.change();
                  // return false;
                  //}
				  				//else
									if( settings.allowNewItems && $(this).val())
									{
										var item = {};
										item[settings.tokenValue] = settings.allowNewItemsPrefix+$(this).val();
										item[settings.propertyToSearch] = $(this).val();

										add_token(item);
										return false;
									  }
					                 break;

			         case KEY.ESCAPE:
                 hide_dropdown();
                 return true;

               default:
                   if(String.fromCharCode(event.which)) {
                       // set a timeout just long enough to let this function finish.
                       setTimeout(function(){do_search();}, 5);
                   }
                   break;
			            }
					        });

    // Keep a reference to the original input box
    var hidden_input = $(input)
                           .hide()
                           .val("")
                           .focus(function () {
                               input_box.focus();
                           })
                           .blur(function () {
                               input_box.blur();
                           });

    // Keep a reference to the selected token and dropdown item
    var selected_token = null;
    var selected_token_index = 0;
    var selected_dropdown_item = null;

    // The list to store the token items in
    var token_list = $("
")
        .addClass(settings.classes.tokenList)
        .click(function (event) {
            var li = $(event.target).closest("li");
            if(li && li.get(0) && $.data(li.get(0), "tokeninput")) {
                toggle_select_token(li);
            } else {
                // Deselect selected token
                if(selected_token) {
                    deselect_token($(selected_token), POSITION.END);
                }

                // Focus input box
                input_box.focus();
            }
        })
        .mouseover(function (event) {
            var li = $(event.target).closest("li");
            if(li && selected_token !== this) {
                li.addClass(settings.classes.highlightedToken);
            }
        })
        .mouseout(function (event) {
            var li = $(event.target).closest("li");
            if(li && selected_token !== this) {
                li.removeClass(settings.classes.highlightedToken);
            }
        })
        .insertBefore(hidden_input);

    // The token holding the input box
    var input_token = $("
")
        .addClass(settings.classes.inputToken)
        .appendTo(token_list)
        .append(input_box);

    // The list to store the dropdown items in
    var dropdown = $("
")
        .addClass(settings.classes.dropdown)
        .appendTo("body")
        .hide();

    // Magic element to help us resize the text input
    var input_resizer = $("<tester/>")
        .insertAfter(input_box)
        .css({
            position: "absolute",
            top: -9999,
            left: -9999,
            width: "auto",
            fontSize: input_box.css("fontSize"),
            fontFamily: input_box.css("fontFamily"),
            fontWeight: input_box.css("fontWeight"),
            letterSpacing: input_box.css("letterSpacing"),
            whiteSpace: "nowrap"
        });

    // Pre-populate list if items exist
    hidden_input.val("");
    var li_data = settings.prePopulate || hidden_input.data("pre");
    if(settings.processPrePopulate && $.isFunction(settings.onResult)) {
        li_data = settings.onResult.call(hidden_input, li_data);
    }
    if(li_data && li_data.length) {
        $.each(li_data, function (index, value) {
            insert_token(value);
            checkTokenLimit();
        });
    }

    // Initialization is done
    if($.isFunction(settings.onReady)) {
        settings.onReady.call();
    }

    //
    // Public functions
    //

    this.clear = function() {
        token_list.children("li").each(function() {
            if ($(this).children("input").length === 0) {
                delete_token($(this));
            }
        });
    }

    this.add = function(item) {
        add_token(item);
    }

    this.remove = function(item) {
        token_list.children("li").each(function() {
            if ($(this).children("input").length === 0) {
                var currToken = $(this).data("tokeninput");
                var match = true;
                for (var prop in item) {
                    if (item[prop] !== currToken[prop]) {
                        match = false;
                        break;
                    }
                }
                if (match) {
                    delete_token($(this));
                }
            }
        });
    }

    this.getTokens = function() {
        return saved_tokens;
    }

    //
    // Private functions
    //

    function checkTokenLimit() {
        if(settings.tokenLimit !== null && token_count >= settings.tokenLimit) {
            input_box.hide();
            hide_dropdown();
            return;
        }
    }

    function resize_input() {
        if(input_val === (input_val = input_box.val())) {return;}

        // Enter new content into resizer and resize input accordingly
        var escaped = input_val.replace(/&/g, '&').replace(/\s/g,' ').replace(/</g, '<').replace(/>/g, '>');
        input_resizer.html(escaped);
        input_box.width(input_resizer.width() + 30);
    }

    function is_printable_character(keycode) {
        return ((keycode >= 48 && keycode <= 90) ||     // 0-1a-z
                (keycode >= 96 && keycode <= 111) ||    // numpad 0-9 + - / * .
                (keycode >= 186 && keycode <= 192) ||   // ; = , - . / ^
                (keycode >= 219 && keycode <= 222));    // ( \ ) '
    }

    // Inner function to a token to the list
    function insert_token(item) {
        var this_token = settings.tokenFormatter(item);
        this_token = $(this_token)
          .addClass(settings.classes.token)
          .insertBefore(input_token);

        // The 'delete token' button
        $("" + settings.deleteText + "")
            .addClass(settings.classes.tokenDelete)
            .appendTo(this_token)
            .click(function () {
                delete_token($(this).parent());
                hidden_input.change();
                return false;
            });

        // Store data on the token
        var token_data = item;
        $.data(this_token.get(0), "tokeninput", item);

        // Save this token for duplicate checking
        saved_tokens = saved_tokens.slice(0,selected_token_index).concat([token_data]).concat(saved_tokens.slice(selected_token_index));
        selected_token_index++;

        // Update the hidden input
        update_hidden_input(saved_tokens, hidden_input);

        token_count += 1;

        // Check the token limit
        if(settings.tokenLimit !== null && token_count >= settings.tokenLimit) {
            input_box.hide();
            hide_dropdown();
        }

        return this_token;
    }

    // Add a token to the token list based on user input
    function add_token (item) {
        var callback = settings.onAdd;

        // See if the token already exists and select it if we don't want duplicates
        if(token_count > 0 && settings.preventDuplicates) {
            var found_existing_token = null;
            token_list.children().each(function () {
                var existing_token = $(this);
                var existing_data = $.data(existing_token.get(0), "tokeninput");
                if(existing_data && existing_data.id === item.id) {
                    found_existing_token = existing_token;
                    return false;
                }
            });

            if(found_existing_token) {
                select_token(found_existing_token);
                input_token.insertAfter(found_existing_token);
                input_box.focus();
                return;
            }
        }

        // Insert the new tokens
        if(settings.tokenLimit == null || token_count < settings.tokenLimit) {
            insert_token(item);
            checkTokenLimit();
        }

        // Clear input box
        input_box.val("");

        // Don't show the help dropdown, they've got the idea
        hide_dropdown();

        // Execute the onAdd callback if defined
        if($.isFunction(callback)) {
            callback.call(hidden_input,item);
        }
    }

    // Select a token in the token list
    function select_token (token) {
        token.addClass(settings.classes.selectedToken);
        selected_token = token.get(0);

        // Hide input box
        input_box.val("");

        // Hide dropdown if it is visible (eg if we clicked to select token)
        hide_dropdown();
    }

    // Deselect a token in the token list
    function deselect_token (token, position) {
        token.removeClass(settings.classes.selectedToken);
        selected_token = null;

        if(position === POSITION.BEFORE) {
            input_token.insertBefore(token);
            selected_token_index--;
        } else if(position === POSITION.AFTER) {
            input_token.insertAfter(token);
            selected_token_index++;
        } else {
            input_token.appendTo(token_list);
            selected_token_index = token_count;
        }

        // Show the input box and give it focus again
        input_box.focus();
    }

    // Toggle selection of a token in the token list
    function toggle_select_token(token) {
        var previous_selected_token = selected_token;

        if(selected_token) {
            deselect_token($(selected_token), POSITION.END);
        }

        if(previous_selected_token === token.get(0)) {
            deselect_token(token, POSITION.END);
        } else {
            select_token(token);
        }
    }

    // Delete a token from the token list
    function delete_token (token) {
        // Remove the id from the saved list
        var token_data = $.data(token.get(0), "tokeninput");
        var callback = settings.onDelete;

        var index = token.prevAll().length;
        if(index > selected_token_index) index--;

        // Delete the token
        token.remove();
        selected_token = null;

        // Show the input box and give it focus again
        input_box.focus();

        // Remove this token from the saved list
        saved_tokens = saved_tokens.slice(0,index).concat(saved_tokens.slice(index+1));
        if(index < selected_token_index) selected_token_index--;

        // Update the hidden input
        update_hidden_input(saved_tokens, hidden_input);

        token_count -= 1;

        if(settings.tokenLimit !== null) {
            input_box
                .show()
                .val("")
                .focus();
        }

        // Execute the onDelete callback if defined
        if($.isFunction(callback)) {
            callback.call(hidden_input,token_data);
        }
    }

    // Update the hidden input box value
    function update_hidden_input(saved_tokens, hidden_input) {
        var token_values = $.map(saved_tokens, function (el) {
            if(typeof settings.tokenValue == 'function')
              return settings.tokenValue.call(this, el);

            return el[settings.tokenValue];
        });
        hidden_input.val(token_values.join(settings.tokenDelimiter));

    }

    // Hide and clear the results dropdown
    function hide_dropdown () {
        dropdown.hide().empty();
        selected_dropdown_item = null;
    }

    function show_dropdown() {
        dropdown
            .css({
                position: "absolute",
                top: $(token_list).offset().top + $(token_list).outerHeight(),
                left: $(token_list).offset().left,
                'z-index': 999
            })
            .show();
    }

    function show_dropdown_searching () {
        if(settings.searchingText) {
            dropdown.html("
"+settings.searchingText+"
");
            show_dropdown();
        }
    }

    function show_dropdown_hint () {
        if(settings.hintText) {
            dropdown.html("
"+settings.hintText+"
");
            show_dropdown();
        }
    }

    function show_dropdown_warn (v) {
        if(v) {
            dropdown.html("
"+v+"
");
            show_dropdown();
        }
    }

    // Highlight the query part of the search term
    function highlight_term(value, term) {
        return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "$1");
    }

    function find_value_and_highlight_term(template, value, term) {
        return template.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + value + ")(?![^<>]*>)(?![^&;]+;)", "g"), highlight_term(value, term));
    }

    // Populate the results dropdown with some results
    function populate_dropdown (query, results) {
        if(results && results.length) {
            dropdown.empty();
            var dropdown_ul = $("
")
                .appendTo(dropdown)
                .mouseover(function (event) {
                    select_dropdown_item($(event.target).closest("li"));
                })
                .mousedown(function (event) {
                    add_token($(event.target).closest("li").data("tokeninput"));
                    hidden_input.change();
                    return false;
                })
                .hide();

            $.each(results, function(index, value) {
                var this_li = settings.resultsFormatter(value);

                this_li = find_value_and_highlight_term(this_li ,value[settings.propertyToSearch], query);

                this_li = $(this_li).appendTo(dropdown_ul);

                if(index % 2) {
                    this_li.addClass(settings.classes.dropdownItem);
                } else {
                    this_li.addClass(settings.classes.dropdownItem2);
                }

                if(index === 0) {
                    select_dropdown_item(this_li);
                }

                $.data(this_li.get(0), "tokeninput", value);
            });

            show_dropdown();

            if(settings.animateDropdown) {
                dropdown_ul.slideDown("fast");
            } else {
                dropdown_ul.show();
            }
        } else {
            if(settings.noResultsText) {
                dropdown.html("
"+settings.noResultsText+"
");
                show_dropdown();
            }
        }
    }

    // Highlight an item in the results dropdown
    function select_dropdown_item (item) {
        if(item) {
            if(selected_dropdown_item) {
                deselect_dropdown_item($(selected_dropdown_item));
            }

            item.addClass(settings.classes.selectedDropdownItem);
            selected_dropdown_item = item.get(0);
        }
    }

    // Remove highlighting from an item in the results dropdown
    function deselect_dropdown_item (item) {
        item.removeClass(settings.classes.selectedDropdownItem);
        selected_dropdown_item = null;
    }

    // Do a search and show the "searching" dropdown if the input is longer
    // than settings.minChars
    function do_search() {
        var query = input_box.val().toLowerCase();

        if(query && query.length) {
            if(selected_token) {
                deselect_token($(selected_token), POSITION.AFTER);
            }

            if(query.length >= settings.minChars) {
                show_dropdown_searching();
                clearTimeout(timeout);

                timeout = setTimeout(function(){
                    run_search(query);
                }, settings.searchDelay);
            } else {
                hide_dropdown();
            }
        }
    }

    // Do the actual search
    function run_search(query) {
        var cache_key = query + computeURL();
        var cached_results = cache.get(cache_key);
        if(cached_results) {
            populate_dropdown(query, cached_results);
        } else {
            // Are we doing an ajax search or local data search?
            if(settings.url) {
                var url = computeURL();
                // Extract exisiting get params
                var ajax_params = {};
                ajax_params.data = {};
                if(url.indexOf("?") > -1) {
                    var parts = url.split("?");
                    ajax_params.url = parts[0];

                    var param_array = parts[1].split("&");
                    $.each(param_array, function (index, value) {
                        var kv = value.split("=");
                        ajax_params.data[kv[0]] = kv[1];
                    });
                } else {
                    ajax_params.url = url;
                }

                // Prepare the request
                ajax_params.data[settings.queryParam] = query;
                ajax_params.type = settings.method;
                ajax_params.dataType = settings.contentType;
                if(settings.crossDomain) {
                    ajax_params.dataType = "jsonp";
                }

                // Attach the success callback
                ajax_params.success = function(results) {
                  if($.isFunction(settings.onResult)) {
                      results = settings.onResult.call(hidden_input, results);
                  }
                  cache.add(cache_key, settings.jsonContainer ? results[settings.jsonContainer] : results);

                  // only populate the dropdown if the results are associated with the active search query
                  if(input_box.val().toLowerCase() === query) {
                      populate_dropdown(query, settings.jsonContainer ? results[settings.jsonContainer] : results);
                  }
                };

                // Make the request
                $.ajax(ajax_params);
            } else if(settings.local_data) {
                // Do the search through local data
                var results = $.grep(settings.local_data, function (row) {
                    return row[settings.propertyToSearch].toLowerCase().indexOf(query.toLowerCase()) > -1;
                });

                if($.isFunction(settings.onResult)) {
                    results = settings.onResult.call(hidden_input, results);
                }
                cache.add(cache_key, results);
                populate_dropdown(query, results);
            }
        }
    }

    // compute the dynamic URL
    function computeURL() {
        var url = settings.url;
        if(typeof settings.url == 'function') {
            url = settings.url.call();
        }
        return url;
    }
};

// Really basic cache for the results
$.TokenList.Cache = function (options) {
    var settings = $.extend({
        max_size: 500
    }, options);

    var data = {};
    var size = 0;

    var flush = function () {
        data = {};
        size = 0;
    };

    this.add = function (query, results) {
        if(size > settings.max_size) {
            flush();
        }

        if(!data[query]) {
            size += 1;
        }

        data[query] = results;
    };

    this.get = function (query) {
        return data[query];
    };
};
}(jQuery));<commit_msg>Removing old tokeninput lib<commit_after><|endoftext|>


<commit_before>;(function (global) {
  'use strict'

  var $ = global.jQuery
  var GOVUK = global.GOVUK || {}

  function ShowHideContent () {
    var self = this

    // Radio and Checkbox selectors
    var selectors = {
      namespace: 'ShowHideContent',
      radio: '[data-target] > input[type="radio"]',
      checkbox: '[data-target] > input[type="checkbox"]'
    }

    // Escape name attribute for use in DOM selector
    function escapeElementName (str) {
      var result = str.replace('[', '\\[').replace(']', '\\]')
      return result
    }

    // Adds ARIA attributes to control + associated content
    function initToggledContent () {
      var $control = $(this)
      var $content = getToggledContent($control)

      // Set aria-controls and defaults
      if ($content.length) {
        $control.attr('aria-controls', $content.attr('id'))
        $control.attr('aria-expanded', 'false')
        $content.attr('aria-hidden', 'true')
      }
    }

    // Return toggled content for control
    function getToggledContent ($control) {
      var id = $control.attr('aria-controls')

      // ARIA attributes aren't set before init
      if (!id) {
        id = $control.closest('[data-target]').data('target')
      }

      // Find show/hide content by id
      return $('#' + id)
    }

    // Show toggled content for control
    function showToggledContent ($control, $content) {
      // Show content
      if ($content.hasClass('js-hidden')) {
        $content.removeClass('js-hidden')
        $content.attr('aria-hidden', 'false')

        // If the controlling input, update aria-expanded
        if ($control.attr('aria-controls')) {
          $control.attr('aria-expanded', 'true')
        }
      }
    }

    // Hide toggled content for control
    function hideToggledContent ($control, $content) {
      $content = $content || getToggledContent($control)

      // Hide content
      if (!$content.hasClass('js-hidden')) {
        $content.addClass('js-hidden')
        $content.attr('aria-hidden', 'true')

        // If the controlling input, update aria-expanded
        if ($control.attr('aria-controls')) {
          $control.attr('aria-expanded', 'false')
        }
      }
    }

    // Handle radio show/hide
    function handleRadioContent ($control, $content) {
      // All radios in this group which control content
      var selector = selectors.radio + '[name=' + escapeElementName($control.attr('name')) + '][aria-controls]'
      var $form = $control.closest('form')
      var $radios = $form.length ? $form.find(selector) : $(selector)

      // Hide content for radios in group
      $radios.each(function () {
        hideToggledContent($(this))
      })

      // Select content for this control
      if ($control.is('[aria-controls]')) {
        showToggledContent($control, $content)
      }
    }

    // Handle checkbox show/hide
    function handleCheckboxContent ($control, $content) {
      // Show checkbox content
      if ($control.is(':checked')) {
        showToggledContent($control, $content)
      } else { // Hide checkbox content
        hideToggledContent($control, $content)
      }
    }

    // Set up event handlers etc
    function init ($container, elementSelector, eventSelectors, handler) {
      $container = $container || $(document.body)

      // Handle control clicks
      function deferred () {
        var $control = $(this)
        handler($control, getToggledContent($control))
      }

      // Prepare ARIA attributes
      var $controls = $(elementSelector)
      $controls.each(initToggledContent)

      // Handle events
      $.each(eventSelectors, function (idx, eventSelector) {
        $container.on('click.' + selectors.namespace, eventSelector, deferred)
      })

      // Any already :checked on init?
      if ($controls.is(':checked')) {
        $controls.filter(':checked').each(deferred)
      }
    }

    // Get event selectors for all radio groups
    function getEventSelectorsForRadioGroups () {
      var radioGroups = []

      // Build an array of radio group selectors
      return $(selectors.radio).map(function () {
        var groupName = $(this).attr('name')

        if ($.inArray(groupName, radioGroups) === -1) {
          radioGroups.push(groupName)
          return 'input[type="radio"][name="' + $(this).attr('name') + '"]'
        }
        return null
      })
    }

    // Set up radio show/hide content for container
    self.showHideRadioToggledContent = function ($container) {
      init($container, selectors.radio, getEventSelectorsForRadioGroups(), handleRadioContent)
    }

    // Set up checkbox show/hide content for container
    self.showHideCheckboxToggledContent = function ($container) {
      init($container, selectors.checkbox, [selectors.checkbox], handleCheckboxContent)
    }

    // Remove event handlers
    self.destroy = function ($container) {
      $container = $container || $(document.body)
      $container.off('.' + selectors.namespace)
    }
  }

  ShowHideContent.prototype.init = function ($container) {
    this.showHideRadioToggledContent($container)
    this.showHideCheckboxToggledContent($container)
  }

  GOVUK.ShowHideContent = ShowHideContent
  global.GOVUK = GOVUK
})(window)
<commit_msg>Fix minor issue with escaping nested form fields<commit_after>;(function (global) {
  'use strict'

  var $ = global.jQuery
  var GOVUK = global.GOVUK || {}

  function ShowHideContent () {
    var self = this

    // Radio and Checkbox selectors
    var selectors = {
      namespace: 'ShowHideContent',
      radio: '[data-target] > input[type="radio"]',
      checkbox: '[data-target] > input[type="checkbox"]'
    }

    // Escape name attribute for use in DOM selector
    function escapeElementName (str) {
      var result = str.replace(/\[/g, '\\[').replace(/\]/g, '\\]')
      return result
    }

    // Adds ARIA attributes to control + associated content
    function initToggledContent () {
      var $control = $(this)
      var $content = getToggledContent($control)

      // Set aria-controls and defaults
      if ($content.length) {
        $control.attr('aria-controls', $content.attr('id'))
        $control.attr('aria-expanded', 'false')
        $content.attr('aria-hidden', 'true')
      }
    }

    // Return toggled content for control
    function getToggledContent ($control) {
      var id = $control.attr('aria-controls')

      // ARIA attributes aren't set before init
      if (!id) {
        id = $control.closest('[data-target]').data('target')
      }

      // Find show/hide content by id
      return $('#' + id)
    }

    // Show toggled content for control
    function showToggledContent ($control, $content) {
      // Show content
      if ($content.hasClass('js-hidden')) {
        $content.removeClass('js-hidden')
        $content.attr('aria-hidden', 'false')

        // If the controlling input, update aria-expanded
        if ($control.attr('aria-controls')) {
          $control.attr('aria-expanded', 'true')
        }
      }
    }

    // Hide toggled content for control
    function hideToggledContent ($control, $content) {
      $content = $content || getToggledContent($control)

      // Hide content
      if (!$content.hasClass('js-hidden')) {
        $content.addClass('js-hidden')
        $content.attr('aria-hidden', 'true')

        // If the controlling input, update aria-expanded
        if ($control.attr('aria-controls')) {
          $control.attr('aria-expanded', 'false')
        }
      }
    }

    // Handle radio show/hide
    function handleRadioContent ($control, $content) {
      // All radios in this group which control content
      var selector = selectors.radio + '[name=' + escapeElementName($control.attr('name')) + '][aria-controls]'
      var $form = $control.closest('form')
      var $radios = $form.length ? $form.find(selector) : $(selector)

      // Hide content for radios in group
      $radios.each(function () {
        hideToggledContent($(this))
      })

      // Select content for this control
      if ($control.is('[aria-controls]')) {
        showToggledContent($control, $content)
      }
    }

    // Handle checkbox show/hide
    function handleCheckboxContent ($control, $content) {
      // Show checkbox content
      if ($control.is(':checked')) {
        showToggledContent($control, $content)
      } else { // Hide checkbox content
        hideToggledContent($control, $content)
      }
    }

    // Set up event handlers etc
    function init ($container, elementSelector, eventSelectors, handler) {
      $container = $container || $(document.body)

      // Handle control clicks
      function deferred () {
        var $control = $(this)
        handler($control, getToggledContent($control))
      }

      // Prepare ARIA attributes
      var $controls = $(elementSelector)
      $controls.each(initToggledContent)

      // Handle events
      $.each(eventSelectors, function (idx, eventSelector) {
        $container.on('click.' + selectors.namespace, eventSelector, deferred)
      })

      // Any already :checked on init?
      if ($controls.is(':checked')) {
        $controls.filter(':checked').each(deferred)
      }
    }

    // Get event selectors for all radio groups
    function getEventSelectorsForRadioGroups () {
      var radioGroups = []

      // Build an array of radio group selectors
      return $(selectors.radio).map(function () {
        var groupName = $(this).attr('name')

        if ($.inArray(groupName, radioGroups) === -1) {
          radioGroups.push(groupName)
          return 'input[type="radio"][name="' + $(this).attr('name') + '"]'
        }
        return null
      })
    }

    // Set up radio show/hide content for container
    self.showHideRadioToggledContent = function ($container) {
      init($container, selectors.radio, getEventSelectorsForRadioGroups(), handleRadioContent)
    }

    // Set up checkbox show/hide content for container
    self.showHideCheckboxToggledContent = function ($container) {
      init($container, selectors.checkbox, [selectors.checkbox], handleCheckboxContent)
    }

    // Remove event handlers
    self.destroy = function ($container) {
      $container = $container || $(document.body)
      $container.off('.' + selectors.namespace)
    }
  }

  ShowHideContent.prototype.init = function ($container) {
    this.showHideRadioToggledContent($container)
    this.showHideCheckboxToggledContent($container)
  }

  GOVUK.ShowHideContent = ShowHideContent
  global.GOVUK = GOVUK
})(window)
<|endoftext|>


<commit_before>/**
 * Copyright 2013-2019 the original author or authors from the JHipster project.
 *
 * This file is part of the JHipster project, see http://www.jhipster.tech/
 * for more information.
 *
 * 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.
 */

const ERROR_CASES = {
  applications: {
    NoApplication: 'No application',
    NoName: 'No name',
    NoVersion: 'No generator version',
    NoAuthenticationType: 'No authentication type',
    NoBuildTool: 'No build tool',
    NoChosenLanguage: 'No chosen language when selecting i18n option',
    ShouldSkipClient: 'Client generation should be skipped for microservice and UAA applications',
    ShouldNotSkipServer: 'Server generation should not be skipped for microservice and UAA applications',
    IllegalSkipServer: 'A database type and authentication type should be defined when using skip server',
    NoUAAAppFolderPath: 'No UAA application folder path'
  },
  deployments: {
    NoDeployment: 'No deployment',
    NoDeploymentType: 'No deployment type',
    NoApplications: 'No applications',
    NoRepository: 'No Docker repository'
  },
  entities: {
    NoEntity: 'No entity',
    NoName: 'No entity name',
    NoTableName: 'No table name',
    NoFields: 'No fields object',
    ReservedWordAsName: 'The entity name cannot be a reserved keyword',
    ReservedWordAsTableName: 'The entity table name cannot be a reserved keyword'
  },
  fields: {
    NoField: 'No field',
    NoName: 'No field name',
    NoType: 'No field type',
    ReservedWordAsName: 'The field name cannot be a reserved keyword'
  },
  validations: {
    NoValidation: 'No validation',
    NoName: 'No validation name',
    WrongValidation: 'Wrong validation',
    NoValue: 'No value'
  },
  enums: {
    NoEnum: 'No enumeration',
    NoName: 'No enumeration name',
    ReservedWordAsName: 'The enum name cannot be a reserved keyword'
  },
  relationships: {
    NoRelationship: 'No relationship',
    WrongType: 'Wrong type'
  },
  options: {
    NoOption: 'No option',
    NoName: 'No option name',
    NoEntityNames: 'No entity names',
    NilInEntityNames: 'Nil value in entity names',
    NoExcludedNames: 'No excluded names',
    NilInExcludedNames: 'Nil value in excluded names',
    NoType: 'No type'
  }
};

module.exports = {
  ErrorCases: ERROR_CASES
};
<commit_msg>Removed useless file<commit_after><|endoftext|>


<commit_before>//Array - gallery of species
      var SpeciesGallery =  [
        {
        name: 'Isbjørn',
          eng: 'Polar bear',
          family: 'Ursus maritimus',
          image:  'info/img/isbjorn.jpg',
          link: 'http://www.npolar.no/en/species/polar-bear.html',
          rights: ''
      },
      {
          name: 'Hvalross',
          eng: 'Walrus',
          family: 'Odobenus rosmarus',
          image:  'info/img/hvalross.jpg',
          link: 'http://www.npolar.no/en/species/walrus.html',
          rights: ''
      },
      {
          name: 'Storkobbe',
          eng: 'Bearded seal',
          family: 'Erignathus barbatus',
          image: 'info/img/storkobbe.jpg',
          link: 'http://www.npolar.no/en/species/bearded-seal.html',
          rights: ''
      },
      {
          name: 'Steinkobbe',
          eng: 'Harbor seal',
          family: 'Phoca vitulina',
          image:  'info/img/steinkobbe.jpg',
          link: 'http://www.npolar.no/en/species/harbour-seal.html',
          rights: ''
      },
      {
        name: 'Grønlandssel',
          eng: 'Harp seal',
          family: 'Phoca groenlandica',
          image:  'info/img/gronlandssel.jpg',
          link: 'http://www.npolar.no/en/species/harp-seal.html',
          rights: 'Av Virginia State Parks staff - IMG_6380Uploaded by AlbertHerring, CC BY 2.0, https://commons.wikimedia.org/w/index.php?curid=29362929'
      },
      {
          name: 'Klappmyss',
          eng: 'Hooded seal',
          family: 'Cystophora cristata',
          image:  'info/img/klappmyss.jpg',
          link: 'http://www.npolar.no/en/species/hooded-seal.html',
          rights: 'Kit M. Kovacs & Christian Lydersen / Norwegian Polar Institute'
      },
      {
          name: 'Ringsel',
          eng: 'Ringed seal',
          family: 'Pusa hispida',
          image:  'info/img/ringsel.jpg',
          link: 'http://www.npolar.no/en/species/ringed-seal.html',
          rights: 'Kit Kovacs / Norwegian Polar Institute'
      },
      { name: 'Hvithval',
          eng: 'White whale',
          family: 'Delphinapterus leucas',
          image:  'info/img/hvithval.jpg',
          link: 'http://www.npolar.no/en/species/white-whale.html',
          rights: 'Einar Johansen / Norwegian Polar Institute'
      },
      {  name: 'Blåhval',
          eng: 'Blue whale',
          family: 'Balaenoptera musculus',
          image:  'info/img/blahval.jpg',
          link: 'http://www.npolar.no/en/species/blue-whale.html',
          rights: 'By NOAA Photo Library - anim1754, Public Domain, https://commons.wikimedia.org/w/index.php?curid=17942391'
      },
      { name: 'Grønlandshval',
          eng: 'Bowhead whale',
          family: 'Balaena mysticetus',
          image:  'info/img/gronlandshval.jpg',
          link: 'http://www.npolar.no/en/species/bowhead-whale.html',
          rights: 'By Bering Land Bridge National Preserve - bowhead-1 Kate Stafford edit, CC BY-SA 2.0, https://commons.wikimedia.org/w/index.php?curid=44326238'
      },
      { name: 'Vågehval',
          eng: 'Common minke whale',
          family: 'Balaenoptera acutorostrata',
          image:  'info/img/vagehval.jpg',
          link: 'http://www.npolar.no/en/species/minke-whale.html',
          rights: 'By NOAA - http://www.noaanews.noaa.gov/stories2006/s2743.htm, Public Domain, https://commons.wikimedia.org/w/index.php?curid=25240111'
      },
      { name: 'Finnhval',
          eng: 'Fin whale',
          family: 'Balaenoptera physalus',
          image:  'info/img/finnhval.jpg',
          link: 'http://www.npolar.no/en/species/fin-whale.html',
          rights: 'By Aqqa Rosing-Asvid - Visit Greenland - Flickr: Finhval, CC BY 2.0, https://commons.wikimedia.org/w/index.php?curid=23241116'
      },
      { name: 'Knølhval',
          eng: 'Humpback whale',
          family: 'Megaptera novaeangliae',
          image:  'info/img/knolhval.jpg',
          link: 'http://www.npolar.no/en/species/humpback-whale.html',
          rights: 'Stein Ø. Nilsen / tromsofoto.net'
      },
      { name: 'Spekkhugger',
          eng: 'Killer whale',
          family: 'Orcinus orca',
          image:  'info/img/spekkhogger.jpg',
          link: 'http://www.npolar.no/en/species/killer-whale.html',
          rights: 'By Robert Pittman - NOAA (http://www.afsc.noaa.gov/Quarterly/amj2005/divrptsNMML3.htm]), Public Domain, https://commons.wikimedia.org/w/index.php?curid=1433661'
      },
      { name: 'Narhval',
          eng: 'Narwhal',
          family: 'Monodon monoceros',
          image:  'info/img/narhval.jpg',
          link: 'http://www.npolar.no/en/species/narwhal.html',
          rights: 'By Dr. Kristin Laidre, Polar Science Center, UW NOAA/OAR/OER - NOAA Photolib Library, Public Domain, https://commons.wikimedia.org/w/index.php?curid=45807231'
      },
      { name: 'Nebbhval',
          eng: 'Northern northern-bottlenose-whale',
          family: 'Hyperoodon ampullatus',
          image:  'info/img/nebbhval.jpg',
          link: 'http://www.npolar.no/en/species/northern-bottlenose-whale.html',
          rights: 'NOAA photo library, https://www.flickr.com/photos/noaaphotolib/5020535408/'
      },
      { name: 'Grindhval',
          eng: 'Pilot whale',
          family: 'Globicephala melas',
          image:  'info/img/grindhval.jpg',
          link: 'http://www.npolar.no/en/species/pilot-whale.html',
          rights: 'By Barney Moss - Watching Whales 4, CC BY 2.0, https://commons.wikimedia.org/w/index.php?curid=15225022'
      },
      { name: 'Seihval',
          eng: 'Sei whale',
          family: 'Balaenoptera borealis',
          image:  'info/img/seihval.jpg',
          link: 'http://www.npolar.no/en/species/sei-whale.html',
          rights:'By Christin Khan, NOAA / NEFSC - http://cbkhan.blogspot.com/, Public Domain, https://commons.wikimedia.org/w/index.php?curid=34101579'
      },
      { name: 'Spermhval',
          eng: 'Sperm whale',
          family: 'Physeter macrocephalus',
          image:  'info/img/spermhval.jpg',
          link: 'http://www.npolar.no/en/species/sperm-whale.html',
          rights: 'By Gabriel Barathieu - http://www.flickr.com/photos/barathieu/7277953560/, CC BY-SA 2.0, https://commons.wikimedia.org/w/index.php?curid=24212362'
      },
      { name: 'Kvitnos',
          eng:'White beaked dolphin',
          family: 'Lagenorhynchus albirostris',
          image:  'info/img/kvitnos.jpg',
          link: 'http://www.npolar.no/en/species/white-beaked-dolphin.html',
          rights: 'By Hannah Beker - Own work, CC BY-SA 3.0, https://commons.wikimedia.org/w/index.php?curid=2587609'
      }];

module.exports = SpeciesGallery;<commit_msg>added photo rights<commit_after>//Array - gallery of species
      var SpeciesGallery =  [
        {
        name: 'Isbjørn',
          eng: 'Polar bear',
          family: 'Ursus maritimus',
          image:  'info/img/isbjorn.jpg',
          link: 'http://www.npolar.no/en/species/polar-bear.html',
          rights: 'Jon Aars / Norwegian Polar Institute'
      },
      {
          name: 'Hvalross',
          eng: 'Walrus',
          family: 'Odobenus rosmarus',
          image:  'info/img/hvalross.jpg',
          link: 'http://www.npolar.no/en/species/walrus.html',
          rights: 'Tore Nordstad / Norwegian Polar Institute'
      },
      {
          name: 'Storkobbe',
          eng: 'Bearded seal',
          family: 'Erignathus barbatus',
          image: 'info/img/storkobbe.jpg',
          link: 'http://www.npolar.no/en/species/bearded-seal.html',
          rights: 'Geir Wing Gabrielsen / Norwegian Polar Institute'
      },
      {
          name: 'Steinkobbe',
          eng: 'Harbor seal',
          family: 'Phoca vitulina',
          image:  'info/img/steinkobbe.jpg',
          link: 'http://www.npolar.no/en/species/harbour-seal.html',
          rights: 'Max König / Norwegian Polar Institute'
      },
      {
        name: 'Grønlandssel',
          eng: 'Harp seal',
          family: 'Phoca groenlandica',
          image:  'info/img/gronlandssel.jpg',
          link: 'http://www.npolar.no/en/species/harp-seal.html',
          rights: 'Av Virginia State Parks staff - IMG_6380Uploaded by AlbertHerring, CC BY 2.0, https://commons.wikimedia.org/w/index.php?curid=29362929'
      },
      {
          name: 'Klappmyss',
          eng: 'Hooded seal',
          family: 'Cystophora cristata',
          image:  'info/img/klappmyss.jpg',
          link: 'http://www.npolar.no/en/species/hooded-seal.html',
          rights: 'Kit M. Kovacs & Christian Lydersen / Norwegian Polar Institute'
      },
      {
          name: 'Ringsel',
          eng: 'Ringed seal',
          family: 'Pusa hispida',
          image:  'info/img/ringsel.jpg',
          link: 'http://www.npolar.no/en/species/ringed-seal.html',
          rights: 'Kit Kovacs / Norwegian Polar Institute'
      },
      { name: 'Hvithval',
          eng: 'White whale',
          family: 'Delphinapterus leucas',
          image:  'info/img/hvithval.jpg',
          link: 'http://www.npolar.no/en/species/white-whale.html',
          rights: 'Einar Johansen / Norwegian Polar Institute'
      },
      {  name: 'Blåhval',
          eng: 'Blue whale',
          family: 'Balaenoptera musculus',
          image:  'info/img/blahval.jpg',
          link: 'http://www.npolar.no/en/species/blue-whale.html',
          rights: 'By NOAA Photo Library - anim1754, Public Domain, https://commons.wikimedia.org/w/index.php?curid=17942391'
      },
      { name: 'Grønlandshval',
          eng: 'Bowhead whale',
          family: 'Balaena mysticetus',
          image:  'info/img/gronlandshval.jpg',
          link: 'http://www.npolar.no/en/species/bowhead-whale.html',
          rights: 'By Bering Land Bridge National Preserve - bowhead-1 Kate Stafford edit, CC BY-SA 2.0, https://commons.wikimedia.org/w/index.php?curid=44326238'
      },
      { name: 'Vågehval',
          eng: 'Common minke whale',
          family: 'Balaenoptera acutorostrata',
          image:  'info/img/vagehval.jpg',
          link: 'http://www.npolar.no/en/species/minke-whale.html',
          rights: 'By NOAA - http://www.noaanews.noaa.gov/stories2006/s2743.htm, Public Domain, https://commons.wikimedia.org/w/index.php?curid=25240111'
      },
      { name: 'Finnhval',
          eng: 'Fin whale',
          family: 'Balaenoptera physalus',
          image:  'info/img/finnhval.jpg',
          link: 'http://www.npolar.no/en/species/fin-whale.html',
          rights: 'By Aqqa Rosing-Asvid - Visit Greenland - Flickr: Finhval, CC BY 2.0, https://commons.wikimedia.org/w/index.php?curid=23241116'
      },
      { name: 'Knølhval',
          eng: 'Humpback whale',
          family: 'Megaptera novaeangliae',
          image:  'info/img/knolhval.jpg',
          link: 'http://www.npolar.no/en/species/humpback-whale.html',
          rights: 'Stein Ø. Nilsen / tromsofoto.net'
      },
      { name: 'Spekkhugger',
          eng: 'Killer whale',
          family: 'Orcinus orca',
          image:  'info/img/spekkhogger.jpg',
          link: 'http://www.npolar.no/en/species/killer-whale.html',
          rights: 'By Robert Pittman - NOAA (http://www.afsc.noaa.gov/Quarterly/amj2005/divrptsNMML3.htm]), Public Domain, https://commons.wikimedia.org/w/index.php?curid=1433661'
      },
      { name: 'Narhval',
          eng: 'Narwhal',
          family: 'Monodon monoceros',
          image:  'info/img/narhval.jpg',
          link: 'http://www.npolar.no/en/species/narwhal.html',
          rights: 'Magnus Andersen / Norwegian Polar Institute'
      },
      { name: 'Nebbhval',
          eng: 'Northern northern-bottlenose-whale',
          family: 'Hyperoodon ampullatus',
          image:  'info/img/nebbhval.jpg',
          link: 'http://www.npolar.no/en/species/northern-bottlenose-whale.html',
          rights: 'NOAA photo library, https://www.flickr.com/photos/noaaphotolib/5020535408/'
      },
      { name: 'Grindhval',
          eng: 'Pilot whale',
          family: 'Globicephala melas',
          image:  'info/img/grindhval.jpg',
          link: 'http://www.npolar.no/en/species/pilot-whale.html',
          rights: 'By Barney Moss - Watching Whales 4, CC BY 2.0, https://commons.wikimedia.org/w/index.php?curid=15225022'
      },
      { name: 'Seihval',
          eng: 'Sei whale',
          family: 'Balaenoptera borealis',
          image:  'info/img/seihval.jpg',
          link: 'http://www.npolar.no/en/species/sei-whale.html',
          rights:'By Christin Khan, NOAA / NEFSC - http://cbkhan.blogspot.com/, Public Domain, https://commons.wikimedia.org/w/index.php?curid=34101579'
      },
      { name: 'Spermhval',
          eng: 'Sperm whale',
          family: 'Physeter macrocephalus',
          image:  'info/img/spermhval.jpg',
          link: 'http://www.npolar.no/en/species/sperm-whale.html',
          rights: 'By Gabriel Barathieu - http://www.flickr.com/photos/barathieu/7277953560/, CC BY-SA 2.0, https://commons.wikimedia.org/w/index.php?curid=24212362'
      },
      { name: 'Kvitnos',
          eng:'White beaked dolphin',
          family: 'Lagenorhynchus albirostris',
          image:  'info/img/kvitnos.jpg',
          link: 'http://www.npolar.no/en/species/white-beaked-dolphin.html',
          rights: 'By Hannah Beker - Own work, CC BY-SA 3.0, https://commons.wikimedia.org/w/index.php?curid=2587609'
      }];

module.exports = SpeciesGallery;<|endoftext|>


<commit_before>// Showcase, Simple display case for images. Copyright (c) 2008 Flurin Egger, DigitPaint, MIT Style License.
// Needs MooTools (http://mootools.net) (Core, Class, Class.Extras, Array, String, Function, Number, Element and Element.Event)
var $any;

var Showcase = new Class({
  labels : {
    next : "next »",
    previous : "&laquo previous",
    currentScreen: "This is screen:"
  },
  // Constructor
  // ==== Parameters:
  // el<id,element>:: Element or ID of the container element which contains Images
  //                  or blocks of HTML with class "object"
  // showCaseTitleEl<id,element>:: The ID of the title element (will be injected into the navigation bar)
  // [labels<Hash>]:: Alternative labels for showcase navigation
  //--
	initialize : function(el,showcaseTitleEl){
		this.container = $(el);
		this.showcaseTitleEl = $(showcaseTitleEl);
		this.images = $A([]);
		this.container.getChildren().each(function(img){
			if(img.get('tag') == "img" || img.hasClass("object")){this.images.push(img); img.dispose(); }
		}.bind(this));
		this.container.empty();

		var c = this._getWindowAnchor.attempt(this);
		if(c){ this.current = c -1; } else {	this.current = 0;	}

		this._create();
		this.navigate(this.current);
	},
	navigate : function(nr){
		if(nr > this.images.length){nr = 0;}
		if(nr < 0){nr = this.images.length - 1;}
		this.current = nr;

		var img = this.images[nr];
		if(!img){return false;}

		var title = $any(img.getProperty("title"),img.getProperty("alt"));

		this.container.empty();
		this.container.adopt(img.clone());
		this._setNrAndTitle(nr + 1,title);
		return true;
	},
	next : function(){
		this.navigate(this.current + 1);
	},
	previous : function(){
		this.navigate(this.current - 1);
	},
	_setNrAndTitle : function(nr,title){
		if(this.titleEl){this.titleEl.set("html",$any(title,""));}
		if(this.screenNrEl){this.screenNrEl.set("html",$any("" + nr, ""));}
	},
	_getWindowAnchor : function(){
		if(window.location.hash && window.location.hash.trim !== ""){
			return window.location.hash.replace("#","").toInt();
		} else {
			return 0;
		}
	},
	_create : function(){
    //

    //
Your title here

    //  This is screen: 0
    //  Screen title (will be replaced)
    //
    //    < vorige
    //
    //    volgende >
    //
    //

    var navigation = new Element("div",{"id":"navigation"});
    this.showcaseTitleEl.inject(navigation);

    navigation.appendText(this.labels.currentScreen + " ");
    this.screenNrEl = new Element("span", {"id": "screen-nr"});
    this.screenNrEl.inject(navigation);
    navigation.appendText(" ");

    this.titleEl = new Element("span",{"id": "screen-title"});
    this.titleEl.inject(navigation);

    var screenNav = new Element("span", {"id": "screen-navigation"});
    screenNav.inject(navigation);

    screenNav.adopt(new Element("a",{"html": this.labels.previous,"href":"#","events": {"click": this.previous.bindWithEvent(this)}}));
    this.screenPages = new Element("span", {"id": "screen-pages","html": " "});
    screenNav.adopt(this.screenPages);
    screenNav.adopt(new Element("a",{"html": this.labels.next,"href":"#","events": {"click": this.next.bindWithEvent(this)}}));

    navigation.inject(document.body,"top");
	  this._createPages();
	},
	_createPages : function(){
		if(!this.screenPages){return false;}
		this.images.each(function(img,i){
			var l = new Element("a",{'href': '#'+(i+1), "html": "" + (i+1), "events": {"click": this.navigate.bind(this,i) }});
			this.screenPages.adopt(l);
		}.bind(this));
	}

});

$any = function(){
	var r = $A(arguments).filter(function(e){
		if(e && $type(e) == "string" && e.trim !== ""){
			return true;
		}
	},this);
	if(r.length > 0){	return r[0]; } else {	return ""; }
};<commit_msg>Fixed disposal of the image elements and cloning of the elements when putting them back. They get removed on container.empty() anyway.<commit_after>// Showcase, Simple display case for images. Copyright (c) 2008 Flurin Egger, DigitPaint, MIT Style License.
// Needs MooTools (http://mootools.net) (Core, Class, Class.Extras, Array, String, Function, Number, Element and Element.Event)
var $any;

var Showcase = new Class({
  labels : {
    next : "next »",
    previous : "&laquo previous",
    currentScreen: "This is screen:"
  },
  // Constructor
  // ==== Parameters:
  // el<id,element>:: Element or ID of the container element which contains Images
  //                  or blocks of HTML with class "object"
  // showCaseTitleEl<id,element>:: The ID of the title element (will be injected into the navigation bar)
  // [labels<Hash>]:: Alternative labels for showcase navigation
  //--
	initialize : function(el,showcaseTitleEl){
		this.container = $(el);
		this.showcaseTitleEl = $(showcaseTitleEl);
		this.images = $A([]);
		this.container.getChildren().each(function(img){
			if(img.get('tag') == "img" || img.hasClass("object")){this.images.push(img); }
		}.bind(this));
		this.container.empty();

		var c = this._getWindowAnchor.attempt(this);
		if(c){ this.current = c -1; } else {	this.current = 0;	}

		this._create();
		this.navigate(this.current);
	},
	navigate : function(nr){
		if(nr > this.images.length){nr = 0;}
		if(nr < 0){nr = this.images.length - 1;}
		this.current = nr;

		var img = this.images[nr];
		if(!img){return false;}

		var title = $any(img.getProperty("title"),img.getProperty("alt"));

		this.container.empty();
		this.container.adopt(img);
		this._setNrAndTitle(nr + 1,title);
		return true;
	},
	next : function(){
		this.navigate(this.current + 1);
	},
	previous : function(){
		this.navigate(this.current - 1);
	},
	_setNrAndTitle : function(nr,title){
		if(this.titleEl){this.titleEl.set("html",$any(title,""));}
		if(this.screenNrEl){this.screenNrEl.set("html",$any("" + nr, ""));}
	},
	_getWindowAnchor : function(){
		if(window.location.hash && window.location.hash.trim !== ""){
			return window.location.hash.replace("#","").toInt();
		} else {
			return 0;
		}
	},
	_create : function(){
    //

    //
Your title here

    //  This is screen: 0
    //  Screen title (will be replaced)
    //
    //    < vorige
    //
    //    volgende >
    //
    //

    var navigation = new Element("div",{"id":"navigation"});
    this.showcaseTitleEl.inject(navigation);

    navigation.appendText(this.labels.currentScreen + " ");
    this.screenNrEl = new Element("span", {"id": "screen-nr"});
    this.screenNrEl.inject(navigation);
    navigation.appendText(" ");

    this.titleEl = new Element("span",{"id": "screen-title"});
    this.titleEl.inject(navigation);

    var screenNav = new Element("span", {"id": "screen-navigation"});
    screenNav.inject(navigation);

    screenNav.adopt(new Element("a",{"html": this.labels.previous,"href":"#","events": {"click": this.previous.bindWithEvent(this)}}));
    this.screenPages = new Element("span", {"id": "screen-pages","html": " "});
    screenNav.adopt(this.screenPages);
    screenNav.adopt(new Element("a",{"html": this.labels.next,"href":"#","events": {"click": this.next.bindWithEvent(this)}}));

    navigation.inject(document.body,"top");
	  this._createPages();
	},
	_createPages : function(){
		if(!this.screenPages){return false;}
		this.images.each(function(img,i){
			var l = new Element("a",{'href': '#'+(i+1), "html": "" + (i+1), "events": {"click": this.navigate.bind(this,i) }});
			this.screenPages.adopt(l);
		}.bind(this));
	}

});

$any = function(){
	var r = $A(arguments).filter(function(e){
		if(e && $type(e) == "string" && e.trim !== ""){
			return true;
		}
	},this);
	if(r.length > 0){	return r[0]; } else {	return ""; }
};<|endoftext|>


<commit_before>// Edit from https://github.com/zalmoxisus/remote-redux-devtools/blob/master/src/devTools.js

import { stringify, parse } from 'jsan';
import instrument from 'redux-devtools-instrument';
import { evalAction, getActionsArray } from 'remotedev-utils';

function configureStore(next, subscriber, options) {
  return instrument(subscriber, options)(next);
}

const monitorActions = [ // To be skipped for relaying actions
  '@@redux/INIT', 'TOGGLE_ACTION', 'SWEEP', 'IMPORT_STATE', 'SET_ACTIONS_ACTIVE',
];

let store = {};
let lastAction;
let filters;
let isExcess;
let started;
let actionCreators;

function init(options) {
  if (options.filters) {
    filters = options.filters;
  }
  if (options.actionCreators) {
    actionCreators = () => getActionsArray(options.actionCreators);
  }
}

function isFiltered(action) {
  if (!action || !action.action || !action.action.type) return false;
  return (
    (filters.whitelist && !action.action.type.match(filters.whitelist.join('|'))) ||
    (filters.blacklist && action.action.type.match(filters.blacklist.join('|')))
  );
}

function filterStagedActions(state) {
  if (!filters) return state;

  const filteredStagedActionIds = [];
  const filteredComputedStates = [];

  state.stagedActionIds.forEach((id, idx) => {
    if (!isFiltered(state.actionsById[id])) {
      filteredStagedActionIds.push(id);
      filteredComputedStates.push(state.computedStates[idx]);
    }
  });

  return {
    ...state,
    stagedActionIds: filteredStagedActionIds,
    computedStates: filteredComputedStates,
  };
}

function getLiftedState() {
  return filterStagedActions(store.liftedStore.getState());
}

function relay(type, state, action, nextActionId) {
  if (filters && isFiltered(action)) return;
  const message = {
    type,
    id: 'redux-native-devtools',
  };
  if (state) message.payload = type === 'ERROR' ? state : stringify(state);
  if (type === 'ACTION') {
    message.action = stringify(action);
    message.isExcess = isExcess;
    message.nextActionId = nextActionId;
  } else if (action) {
    message.action = stringify(action);
  }
  postMessage({ __IS_REDUX_NATIVE_MESSAGE__: true, content: message });
}

function dispatchRemotely(action) {
  try {
    const result = evalAction(action, actionCreators);
    store.dispatch(result);
  } catch (e) {
    relay('ERROR', e.message);
  }
}

function handleMessages(message) {
  if (message.type === 'IMPORT') {
    store.liftedStore.dispatch({
      type: 'IMPORT_STATE',
      nextLiftedState: parse(message.state),
    });
  }
  if (message.type === 'UPDATE' || message.type === 'IMPORT') {
    relay('STATE', getLiftedState());
  }
  if (message.type === 'ACTION') {
    dispatchRemotely(message.action);
  } else if (message.type === 'DISPATCH') {
    store.liftedStore.dispatch(message.action);
  }
}

function start() {
  if (started) return;
  started = true;

  self.addEventListener('message', message => {
    const { method, content } = message.data;
    if (method === 'emitReduxMessage') {
      handleMessages(content);
    }
  });
  if (typeof actionCreators === 'function') actionCreators = actionCreators();
  relay('STATE', getLiftedState(), actionCreators);

  // Because the worker message not have notify the remote JS runtime
  // we need to regularly update JS runtime
  global.__RND_INTERVAL__ = setInterval(function(){}, 222); // eslint-disable-line
}

function monitorReducer(state = {}, action) {
  lastAction = action.type;
  return state;
}

function handleChange(state, liftedState, maxAge) {
  const nextActionId = liftedState.nextActionId;
  const liftedAction = liftedState.actionsById[nextActionId - 1];
  const action = liftedAction.action;

  if (action.type === '@@INIT') {
    relay('INIT', state, { timestamp: Date.now() });
  } else if (monitorActions.indexOf(lastAction) === -1) {
    if (lastAction === 'JUMP_TO_STATE') return;
    relay('ACTION', state, liftedAction, nextActionId);
    if (!isExcess && maxAge) isExcess = liftedState.stagedActionIds.length >= maxAge;
  } else {
    relay('STATE', filterStagedActions(liftedState));
  }
}

const reduxNatieDevToools = (options = {}) => {
  init(options);
  const maxAge = options.maxAge || 30;
  return next => (reducer, initialState) => {
    store = configureStore(
      next, monitorReducer, { maxAge }
    )(reducer, initialState);

    start();
    store.subscribe(() => {
      handleChange(store.getState(), store.liftedStore.getState(), maxAge);
    });
    return store;
  };
};

reduxNatieDevToools.updateStore = newStore => {
  store = newStore;
};

export default reduxNatieDevToools;
<commit_msg>Update reduxNativeDevTools enhancer from upstream<commit_after>// Edit from https://github.com/zalmoxisus/remote-redux-devtools/blob/master/src/devTools.js

import { stringify, parse } from 'jsan';
import instrument from 'redux-devtools-instrument';
import { evalAction, getActionsArray } from 'remotedev-utils';
import { isFiltered, filterStagedActions, filterState } from 'remotedev-utils/lib/filters';

function configureStore(next, subscriber, options) {
  return instrument(subscriber, options)(next);
}

const monitorActions = [ // To be skipped for relaying actions
  '@@redux/INIT', 'TOGGLE_ACTION', 'SWEEP', 'IMPORT_STATE', 'SET_ACTIONS_ACTIVE',
];

let store = {};
let lastAction;
let filters;
let isExcess;
let started;
let actionCreators;
let stateSanitizer;
let actionSanitizer;

function init(options) {
  if (options.filters) {
    filters = options.filters;
  }
  if (options.actionCreators) {
    actionCreators = () => getActionsArray(options.actionCreators);
  }
  stateSanitizer = options.stateSanitizer;
  actionSanitizer = options.actionSanitizer;
}

function getLiftedState() {
  return filterStagedActions(store.liftedStore.getState());
}

function relay(type, state, action, nextActionId) {
  if (filters && isFiltered(action)) return;
  const message = {
    type,
    id: 'redux-native-devtools',
  };
  if (state) {
    message.payload = type === 'ERROR' ?
      state :
      stringify(filterState(state, type, filters, stateSanitizer, actionSanitizer, nextActionId));
  }
  if (type === 'ACTION') {
    message.action = stringify(
      !actionSanitizer ? action : actionSanitizer(action.action, nextActionId - 1)
    );
    message.isExcess = isExcess;
    message.nextActionId = nextActionId;
  } else if (action) {
    message.action = stringify(action);
  }
  postMessage({ __IS_REDUX_NATIVE_MESSAGE__: true, content: message });
}

function dispatchRemotely(action) {
  try {
    const result = evalAction(action, actionCreators);
    store.dispatch(result);
  } catch (e) {
    relay('ERROR', e.message);
  }
}

function handleMessages(message) {
  if (message.type === 'IMPORT') {
    store.liftedStore.dispatch({
      type: 'IMPORT_STATE',
      nextLiftedState: parse(message.state),
    });
  }
  if (message.type === 'UPDATE' || message.type === 'IMPORT') {
    relay('STATE', getLiftedState());
  }
  if (message.type === 'ACTION') {
    dispatchRemotely(message.action);
  } else if (message.type === 'DISPATCH') {
    store.liftedStore.dispatch(message.action);
  }
}

function start() {
  if (started) return;
  started = true;

  self.addEventListener('message', message => {
    const { method, content } = message.data;
    if (method === 'emitReduxMessage') {
      handleMessages(content);
    }
  });
  if (typeof actionCreators === 'function') actionCreators = actionCreators();
  relay('STATE', getLiftedState(), actionCreators);

  // Because the worker message not have notify the remote JS runtime
  // we need to regularly update JS runtime
  global.__RND_INTERVAL__ = setInterval(function(){}, 222); // eslint-disable-line
}

function monitorReducer(state = {}, action) {
  lastAction = action.type;
  return state;
}

function handleChange(state, liftedState, maxAge) {
  const nextActionId = liftedState.nextActionId;
  const liftedAction = liftedState.actionsById[nextActionId - 1];
  const action = liftedAction.action;

  if (action.type === '@@INIT') {
    relay('INIT', state, { timestamp: Date.now() });
  } else if (monitorActions.indexOf(lastAction) === -1) {
    if (lastAction === 'JUMP_TO_STATE') return;
    relay('ACTION', state, liftedAction, nextActionId);
    if (!isExcess && maxAge) isExcess = liftedState.stagedActionIds.length >= maxAge;
  } else {
    relay('STATE', filterStagedActions(liftedState));
  }
}

const reduxNatieDevToools = (options = {}) => {
  init(options);
  const maxAge = options.maxAge || 30;
  return next => (reducer, initialState) => {
    store = configureStore(
      next, monitorReducer, { maxAge }
    )(reducer, initialState);

    start();
    store.subscribe(() => {
      handleChange(store.getState(), store.liftedStore.getState(), maxAge);
    });
    return store;
  };
};

reduxNatieDevToools.updateStore = newStore => {
  store = newStore;
};

export default reduxNatieDevToools;
<|endoftext|>


<commit_before>/*
 * graphite.js: Stream responsible for sending metrics on data events to graphite.
 *
 * @obazoud
 *
 * Important: set mulitplex to false to create only one Graphite client
 *
 * godot.createServer({
 *   type: 'tcp',
 *   multiplex: false,
 *   reactors: [
 *     godot.reactor()
 *       .graphite({
 *         url: 'plaintext://carbon.hostedgraphite.com:2003',
 *         prefix: 'xxxx.godot',
 *        })
 *       .console()
 *   ]
 * }).listen(1337);
 *
 */

var utile = require('utile'),
    graphite = require('graphite'),
    ReadWriteStream = require('../common/read-write-stream');

//
// ### function Graphite (options)
// #### @options {Object} Options for sending data to Graphite.
// ####   @options.url      {string} Graphite url.
// ####   @options.prefix   {string} Graphite prefix added to all metrics.
// Constructor function for the Graphite stream responsible for sending
// metrics on data events.
//
var Graphite = module.exports = function Graphite(options) {
  if (!options || !options.url || !options.prefix) {
    throw new Error('options.url and options.prefix are required');
  }

  ReadWriteStream.call(this);

  this.url      = options.url;
  this.prefix   = options.prefix   || 'godot';
  this.interval = options.interval || 60000;
  this.meta     = options.meta     || null;
  this._last    = 0;

  this.client  = options.client  || graphite.createClient(this.url);
};

//
// Inherit from ReadWriteStream.
//
utile.inherits(Graphite, ReadWriteStream);

//
// ### function write (data)
// #### @data {Object} JSON to send metric with
// Sends a metric with the specified `data`.
//
Graphite.prototype.write = function (data) {
  var self    = this,
      now     = new Date(),
      metrics = {},
      metricName;

  //
  // Return immediately if we have sent a matric
  // in a time period less than `this.interval`.
  //
  if (this.interval && this._last
      && (now - this._last) <= this.interval) {
    return;
  }

  metricName = utile.format("%s.%s.%s.%s",
    this.prefix,
    data.host.replace(/\./g, '_'),
    data.service.replace(/\./g, '_').replace(/\//g, '.'),
    data.state
  );

  metrics[metricName] = this.meta ? data.meta[this.meta] : data.metric;
  this.client.write(metrics, data.time, function (err) {
    self._last = now;

    return err
      ? self.emit('error', err)
      : self.emit('data', data);
  });
};
<commit_msg>[fix] dont rely on `state` being in the data object and dont block the data from flowing through the stream in the graphite reactor<commit_after>/*
 * graphite.js: Stream responsible for sending metrics on data events to graphite.
 *
 * @obazoud
 *
 * Important: set mulitplex to false to create only one Graphite client
 *
 * godot.createServer({
 *   type: 'tcp',
 *   multiplex: false,
 *   reactors: [
 *     godot.reactor()
 *       .graphite({
 *         url: 'plaintext://carbon.hostedgraphite.com:2003',
 *         prefix: 'xxxx.godot',
 *        })
 *       .console()
 *   ]
 * }).listen(1337);
 *
 */

var utile = require('utile'),
    graphite = require('graphite'),
    ReadWriteStream = require('../common/read-write-stream');

//
// ### function Graphite (options)
// #### @options {Object} Options for sending data to Graphite.
// ####   @options.url      {string} Graphite url.
// ####   @options.prefix   {string} Graphite prefix added to all metrics.
// Constructor function for the Graphite stream responsible for sending
// metrics on data events.
//
var Graphite = module.exports = function Graphite(options) {
  if (!options || !options.url || !options.prefix) {
    throw new Error('options.url and options.prefix are required');
  }

  ReadWriteStream.call(this);

  this.url      = options.url;
  this.prefix   = options.prefix   || 'godot';
  this.interval = options.interval || 60000;
  this.meta     = options.meta     || null;
  this._last    = 0;

  this.client  = options.client  || graphite.createClient(this.url);
};

//
// Inherit from ReadWriteStream.
//
utile.inherits(Graphite, ReadWriteStream);

//
// ### function write (data)
// #### @data {Object} JSON to send metric with
// Sends a metric with the specified `data`.
//
Graphite.prototype.write = function (data) {
  var self    = this,
      now     = new Date(),
      metrics = {},
      metricName;

  //
  // Return immediately if we have sent a matric
  // in a time period less than `this.interval`.
  //
  if (this.interval && this._last
      && (now - this._last) <= this.interval) {
    return;
  }

  metricName = utile.format("%s.%s.%s",
    this.prefix,
    data.host.replace(/\./g, '_'),
    data.service.replace(/\./g, '_').replace(/\//g, '.')
  );

  metrics[metricName] = this.meta ? data.meta[this.meta] : data.metric;
  this.client.write(metrics, data.time, function (err) {
    self._last = now;
    if (err) { return self.emit('error', err) }
  });

  self.emit('data', data);
};
<|endoftext|>


<commit_before>import React from 'react';
import axios from 'axios';

import UserSearchForm from './UserSearchForm';
import UserList from './UserList';
import DangerError from './DangerError';
import style from './style';

class UserBrowser extends React.Component {
	constructor() {
		super();
		this.state = {
			users: [],
			userBrowseError: null
		};

		this.handleUserSubmit = this.handleUserSubmit.bind(this);
		this.onTooBroadSearch = this.onTooBroadSearch.bind(this);
	}

	componentWillMount() {
		axios.get(`${this.props.route.healthUrl}`)
			.catch((error) => {
				this.setState({
					users: [],
					userBrowseError: 'O servidor não está a ser executado. Prima Ctrl+Alt+F e volte a abrir a página.'
				});
				return Promise.reject();
			})
			.then(res => {
				if (!res.data.connected) {
					this.setState({
						userBrowseError: 'O servidor não consegue ligar à base de dados. Contacte o suporte técnico.'
					});
				} else {
					this.setState({
						userBrowseError: null
					});
				}
			}, () => { /* do nothing */ });
	}

	render() {
		return (

				<UserSearchForm onUserSubmit={ this.handleUserSubmit } onTooBroadSearch={ this.onTooBroadSearch } />
				<UserList data={ this.state.users } />
				<DangerError data={ this.state.userBrowseError } />

		);
	}

	onTooBroadSearch() {
		this.setState({
			users: [],
			userBrowseError: null
		});
	}

	handleUserSubmit(userSearch) {
		axios.get(`${this.props.route.userSearchUrl}`, {params: {userSearch}})
			.catch((error) => {
				this.setState({
					users: [],
					userBrowseError: error.response.data
				});
				return Promise.reject();
			})
			.then(res => {
				this.setState({
					users: res.data,
					userBrowseError: null
				});
			});
	}
}

export default UserBrowser;<commit_msg>Change 'no server connection' message<commit_after>import React from 'react';
import axios from 'axios';

import UserSearchForm from './UserSearchForm';
import UserList from './UserList';
import DangerError from './DangerError';
import style from './style';

class UserBrowser extends React.Component {
	constructor() {
		super();
		this.state = {
			users: [],
			userBrowseError: null
		};

		this.handleUserSubmit = this.handleUserSubmit.bind(this);
		this.onTooBroadSearch = this.onTooBroadSearch.bind(this);
	}

	componentWillMount() {
		axios.get(`${this.props.route.healthUrl}`)
			.catch((error) => {
				this.setState({
					users: [],
					userBrowseError: 'O servidor não está a ser executado'
				});
				return Promise.reject();
			})
			.then(res => {
				if (!res.data.connected) {
					this.setState({
						userBrowseError: 'O servidor não consegue ligar à base de dados. Contacte o suporte técnico.'
					});
				} else {
					this.setState({
						userBrowseError: null
					});
				}
			}, () => { /* do nothing */ });
	}

	render() {
		return (

				<UserSearchForm onUserSubmit={ this.handleUserSubmit } onTooBroadSearch={ this.onTooBroadSearch } />
				<UserList data={ this.state.users } />
				<DangerError data={ this.state.userBrowseError } />

		);
	}

	onTooBroadSearch() {
		this.setState({
			users: [],
			userBrowseError: null
		});
	}

	handleUserSubmit(userSearch) {
		axios.get(`${this.props.route.userSearchUrl}`, {params: {userSearch}})
			.catch((error) => {
				this.setState({
					users: [],
					userBrowseError: error.response.data
				});
				return Promise.reject();
			})
			.then(res => {
				this.setState({
					users: res.data,
					userBrowseError: null
				});
			});
	}
}

export default UserBrowser;<|endoftext|>


<commit_before>(function() {
  'use strict';

  function histogram(args) {
    this.init = function(args) {
      this.args = args;

      raw_data_transformation(args);
      process_histogram(args);
      init(args);

      new MG.scale_factory(args)
        .namespace('x')
        .numericalDomainFromData()
        .numericalRange('bottom');

      var baselines = (args.baselines || []).map(function(d) {
        return d[args.y_accessor]
      });

      new MG.scale_factory(args)
        .namespace('y')
        .zeroBottom(true)
        .inflateDomain(true)
        .numericalDomainFromData(baselines)
        .numericalRange('left');

      x_axis(args);
      y_axis(args);

      this.mainPlot();
      this.markers();
      this.rollover();
      this.windowListeners();

      return this;
    };

    this.mainPlot = function() {
      var svg = mg_get_svg_child_of(args.target);

      //remove the old histogram, add new one
      svg.selectAll('.mg-histogram').remove();

      var g = svg.append('g')
        .attr('class', 'mg-histogram');

      var bar = g.selectAll('.mg-bar')
        .data(args.data[0])
        .enter().append('g')
        .attr('class', 'mg-bar')
        .attr('transform', function(d) {
          return "translate(" + args.scales.X(d[args.x_accessor]).toFixed(2) + "," + args.scales.Y(d[args.y_accessor]).toFixed(2) + ")";
        });

      //draw bars
      bar.append('rect')
        .attr('x', 1)
        .attr('width', function(d, i) {
          if (args.data[0].length === 1) {
            return (args.scalefns.xf(args.data[0][0]) - args.bar_margin).toFixed(0);
          } else if (i !== args.data[0].length - 1) {
            return (args.scalefns.xf(args.data[0][i + 1]) - args.scalefns.xf(d)).toFixed(0);
          } else {
            return (args.scalefns.xf(args.data[0][1]) - args.scalefns.xf(args.data[0][0])).toFixed(0);
          }
        })
        .attr('height', function(d) {
          if (d[args.y_accessor] === 0) {
            return 0;
          }

          return (args.height - args.bottom - args.buffer - args.scales.Y(d[args.y_accessor])).toFixed(2);
        });

      return this;
    };

    this.markers = function() {
      markers(args);
      return this;
    };

    this.rollover = function() {
      var svg = mg_get_svg_child_of(args.target);

      if (svg.selectAll('.mg-active-datapoint-container').nodes().length === 0) {
        mg_add_g(svg, 'mg-active-datapoint-container');
      }

      //remove the old rollovers if they already exist
      svg.selectAll('.mg-rollover-rect').remove();
      svg.selectAll('.mg-active-datapoint').remove();

      var g = svg.append('g')
        .attr('class', 'mg-rollover-rect');

      //draw rollover bars
      var bar = g.selectAll('.mg-bar')
        .data(args.data[0])
        .enter().append('g')
        .attr('class', function(d, i) {
          if (args.linked) {
            return 'mg-rollover-rects roll_' + i;
          } else {
            return 'mg-rollover-rects';
          }
        })
        .attr('transform', function(d) {
          return "translate(" + (args.scales.X(d[args.x_accessor])) + "," + 0 + ")";
        });

      bar.append('rect')
        .attr('x', 1)
        .attr('y', args.buffer + args.title_y_position)
        .attr('width', function(d, i) {
          //if data set is of length 1
          if (args.data[0].length === 1) {
            return (args.scalefns.xf(args.data[0][0]) - args.bar_margin).toFixed(0);
          } else if (i !== args.data[0].length - 1) {
            return (args.scalefns.xf(args.data[0][i + 1]) - args.scalefns.xf(d)).toFixed(0);
          } else {
            return (args.scalefns.xf(args.data[0][1]) - args.scalefns.xf(args.data[0][0])).toFixed(0);
          }
        })
        .attr('height', function(d) {
          return args.height;
        })
        .attr('opacity', 0)
        .on('mouseover', this.rolloverOn(args))
        .on('mouseout', this.rolloverOff(args))
        .on('mousemove', this.rolloverMove(args));

      return this;
    };

    this.rolloverOn = function(args) {
      var svg = mg_get_svg_child_of(args.target);

      return function(d, i) {
        svg.selectAll('text')
          .filter(function(g, j) {
            return d === g;
          })
          .attr('opacity', 0.3);

        var fmt = args.processed.xax_format || MG.time_format(args.utc_time, '%b %e, %Y');
        var num = format_rollover_number(args);

        svg.selectAll('.mg-bar rect')
          .filter(function(d, j) {
            return j === i;
          })
          .classed('active', true);

        //trigger mouseover on all matching bars
        if (args.linked && !MG.globals.link) {
          MG.globals.link = true;

          //trigger mouseover on matching bars in .linked charts
          d3.selectAll('.mg-rollover-rects.roll_' + i + ' rect')
            .each(function(d) { //use existing i
              d3.select(this).on('mouseover')(d, i);
            });
        }

        //update rollover text
        if (args.show_rollover_text) {
          var mo = mg_mouseover_text(args, { svg: svg });
          var row = mo.mouseover_row();
          row.text('\u259F  ').elem()
            .classed('hist-symbol', true);

          row.text(mg_format_x_mouseover(args, d)); // x
          row.text(mg_format_y_mouseover(args, d, args.time_series === false));
        }

        if (args.mouseover) {
          mg_setup_mouseover_container(svg, args);
          args.mouseover(d, i);
        }
      };
    };

    this.rolloverOff = function(args) {
      var svg = mg_get_svg_child_of(args.target);

      return function(d, i) {
        if (args.linked && MG.globals.link) {
          MG.globals.link = false;

          //trigger mouseout on matching bars in .linked charts
          d3.selectAll('.mg-rollover-rects.roll_' + i + ' rect')
            .each(function(d) { //use existing i
              d3.select(this).on('mouseout')(d, i);
            });
        }

        //reset active bar
        svg.selectAll('.mg-bar rect')
          .classed('active', false);

        //reset active data point text
        mg_clear_mouseover_container(svg);

        if (args.mouseout) {
          args.mouseout(d, i);
        }
      };
    };

    this.rolloverMove = function(args) {
      return function(d, i) {
        if (args.mousemove) {
          args.mousemove(d, i);
        }
      };
    };

    this.windowListeners = function() {
      mg_window_listeners(this.args);
      return this;
    };

    this.init(args);
  }

  var defaults = {
    binned: false,
    bins: null,
    processed_x_accessor: 'x',
    processed_y_accessor: 'y',
    processed_dx_accessor: 'dx',
    bar_margin: 1
  };

  MG.register('histogram', histogram, defaults);
}).call(this);
<commit_msg>Testing replacing var with const<commit_after>(function() {
  'use strict';

  function histogram(args) {
    this.init = function(args) {
      this.args = args;

      raw_data_transformation(args);
      process_histogram(args);
      init(args);

      new MG.scale_factory(args)
        .namespace('x')
        .numericalDomainFromData()
        .numericalRange('bottom');

      var baselines = (args.baselines || []).map(function(d) {
        return d[args.y_accessor]
      });

      new MG.scale_factory(args)
        .namespace('y')
        .zeroBottom(true)
        .inflateDomain(true)
        .numericalDomainFromData(baselines)
        .numericalRange('left');

      x_axis(args);
      y_axis(args);

      this.mainPlot();
      this.markers();
      this.rollover();
      this.windowListeners();

      return this;
    };

    this.mainPlot = function() {
      const svg = mg_get_svg_child_of(args.target);

      //remove the old histogram, add new one
      svg.selectAll('.mg-histogram').remove();

      var g = svg.append('g')
        .attr('class', 'mg-histogram');

      var bar = g.selectAll('.mg-bar')
        .data(args.data[0])
        .enter().append('g')
        .attr('class', 'mg-bar')
        .attr('transform', function(d) {
          return "translate(" + args.scales.X(d[args.x_accessor]).toFixed(2) + "," + args.scales.Y(d[args.y_accessor]).toFixed(2) + ")";
        });

      //draw bars
      bar.append('rect')
        .attr('x', 1)
        .attr('width', function(d, i) {
          if (args.data[0].length === 1) {
            return (args.scalefns.xf(args.data[0][0]) - args.bar_margin).toFixed(0);
          } else if (i !== args.data[0].length - 1) {
            return (args.scalefns.xf(args.data[0][i + 1]) - args.scalefns.xf(d)).toFixed(0);
          } else {
            return (args.scalefns.xf(args.data[0][1]) - args.scalefns.xf(args.data[0][0])).toFixed(0);
          }
        })
        .attr('height', function(d) {
          if (d[args.y_accessor] === 0) {
            return 0;
          }

          return (args.height - args.bottom - args.buffer - args.scales.Y(d[args.y_accessor])).toFixed(2);
        });

      return this;
    };

    this.markers = function() {
      markers(args);
      return this;
    };

    this.rollover = function() {
      var svg = mg_get_svg_child_of(args.target);

      if (svg.selectAll('.mg-active-datapoint-container').nodes().length === 0) {
        mg_add_g(svg, 'mg-active-datapoint-container');
      }

      //remove the old rollovers if they already exist
      svg.selectAll('.mg-rollover-rect').remove();
      svg.selectAll('.mg-active-datapoint').remove();

      var g = svg.append('g')
        .attr('class', 'mg-rollover-rect');

      //draw rollover bars
      var bar = g.selectAll('.mg-bar')
        .data(args.data[0])
        .enter().append('g')
        .attr('class', function(d, i) {
          if (args.linked) {
            return 'mg-rollover-rects roll_' + i;
          } else {
            return 'mg-rollover-rects';
          }
        })
        .attr('transform', function(d) {
          return "translate(" + (args.scales.X(d[args.x_accessor])) + "," + 0 + ")";
        });

      bar.append('rect')
        .attr('x', 1)
        .attr('y', args.buffer + args.title_y_position)
        .attr('width', function(d, i) {
          //if data set is of length 1
          if (args.data[0].length === 1) {
            return (args.scalefns.xf(args.data[0][0]) - args.bar_margin).toFixed(0);
          } else if (i !== args.data[0].length - 1) {
            return (args.scalefns.xf(args.data[0][i + 1]) - args.scalefns.xf(d)).toFixed(0);
          } else {
            return (args.scalefns.xf(args.data[0][1]) - args.scalefns.xf(args.data[0][0])).toFixed(0);
          }
        })
        .attr('height', function(d) {
          return args.height;
        })
        .attr('opacity', 0)
        .on('mouseover', this.rolloverOn(args))
        .on('mouseout', this.rolloverOff(args))
        .on('mousemove', this.rolloverMove(args));

      return this;
    };

    this.rolloverOn = function(args) {
      var svg = mg_get_svg_child_of(args.target);

      return function(d, i) {
        svg.selectAll('text')
          .filter(function(g, j) {
            return d === g;
          })
          .attr('opacity', 0.3);

        var fmt = args.processed.xax_format || MG.time_format(args.utc_time, '%b %e, %Y');
        var num = format_rollover_number(args);

        svg.selectAll('.mg-bar rect')
          .filter(function(d, j) {
            return j === i;
          })
          .classed('active', true);

        //trigger mouseover on all matching bars
        if (args.linked && !MG.globals.link) {
          MG.globals.link = true;

          //trigger mouseover on matching bars in .linked charts
          d3.selectAll('.mg-rollover-rects.roll_' + i + ' rect')
            .each(function(d) { //use existing i
              d3.select(this).on('mouseover')(d, i);
            });
        }

        //update rollover text
        if (args.show_rollover_text) {
          var mo = mg_mouseover_text(args, { svg: svg });
          var row = mo.mouseover_row();
          row.text('\u259F  ').elem()
            .classed('hist-symbol', true);

          row.text(mg_format_x_mouseover(args, d)); // x
          row.text(mg_format_y_mouseover(args, d, args.time_series === false));
        }

        if (args.mouseover) {
          mg_setup_mouseover_container(svg, args);
          args.mouseover(d, i);
        }
      };
    };

    this.rolloverOff = function(args) {
      var svg = mg_get_svg_child_of(args.target);

      return function(d, i) {
        if (args.linked && MG.globals.link) {
          MG.globals.link = false;

          //trigger mouseout on matching bars in .linked charts
          d3.selectAll('.mg-rollover-rects.roll_' + i + ' rect')
            .each(function(d) { //use existing i
              d3.select(this).on('mouseout')(d, i);
            });
        }

        //reset active bar
        svg.selectAll('.mg-bar rect')
          .classed('active', false);

        //reset active data point text
        mg_clear_mouseover_container(svg);

        if (args.mouseout) {
          args.mouseout(d, i);
        }
      };
    };

    this.rolloverMove = function(args) {
      return function(d, i) {
        if (args.mousemove) {
          args.mousemove(d, i);
        }
      };
    };

    this.windowListeners = function() {
      mg_window_listeners(this.args);
      return this;
    };

    this.init(args);
  }

  var defaults = {
    binned: false,
    bins: null,
    processed_x_accessor: 'x',
    processed_y_accessor: 'y',
    processed_dx_accessor: 'dx',
    bar_margin: 1
  };

  MG.register('histogram', histogram, defaults);
}).call(this);
<|endoftext|>