<commit_before>/**
This is a collection of javascript functions and whatnot
under the spree namespace that do stuff we find helpful.
Hopefully, this will evolve into a propper class.
**/

/* global AUTH_TOKEN, order_number, Sortable */

jQuery(function ($) {
  // Add some tips
  $('.with-tip').tooltip()

  $('.js-show-index-filters').click(function () {
    $('.filter-well').slideToggle()
    $(this).parents('.filter-wrap').toggleClass('collapsed')
  })

  // Off Canvas Sidebar Functionality
  var sidebarOpen    = $('#sidebar-open')
  var sidebarClose   = $('#sidebar-close')
  var body            = $('body')
  var activeItem     = $('#main-sidebar').find('.selected')
  var modalBackdrop  = $('#multi-backdrop')

  function closeAllMenus() {
    $(body).removeClass()
    body.addClass('admin')
    modalBackdrop.removeClass('show')
  }
  modalBackdrop.click(closeAllMenus)

  activeItem.closest('.nav-sidebar').addClass('active-option')
  activeItem.closest('.nav-pills').addClass('in show')

  function openMenu() {
    body.addClass('sidebar-open modal-open')
    modalBackdrop.addClass('show')
  }

  function closeMenu() {
    body.removeClass('sidebar-open modal-open')
    modalBackdrop.removeClass('show')
  }

  sidebarOpen.click(openMenu)
  sidebarClose.click(closeMenu)

  // Contextual Sidebar Menu Functionality
  var contextualSidebarMenuToggle    = $('#contextual-menu-open')

  function openContextualToggle() {
    if (document.body.classList.contains('contextualSideMenu-open')) {
      body.removeClass('contextualSideMenu-open modal-open')
      modalBackdrop.removeClass('show')
    } else {
      body.addClass('contextualSideMenu-open modal-open')
      modalBackdrop.addClass('show')
    }
  }

  contextualSidebarMenuToggle.click(openContextualToggle)

  // TODO: remove this js temp behaviour and fix this decent
  // Temp quick search
  // When there was a search term, copy it
  $('.js-quick-search').val($('.js-quick-search-target').val())
  // Catch the quick search form submit and submit the real form
  $('#quick-search').submit(function () {
    $('.js-quick-search-target').val($('.js-quick-search').val())
    $('#table-filter form').submit()
    return false
  })

  // Replace ▼ and ▲ in sort_link with nicer icons
  $('.sort_link').each(function () {
    // Remove the &nbsp in the text
    var sortLinkText = $(this).text().replace('\xA0', '')

    if (sortLinkText.indexOf('▼') >= 0) {
      $(this).text(sortLinkText.replace('▼', ''))
      $(this).append('')
    } else if (sortLinkText.indexOf('▲') >= 0) {
      $(this).text(sortLinkText.replace('▲', ''))
      $(this).append('')
    }
  })

  // Clickable ransack filters
  $('.js-add-filter').click(function () {
    var ransackField = $(this).data('ransack-field')
    var ransackValue = $(this).data('ransack-value')

    $('#' + ransackField).val(ransackValue)
    $('#table-filter form').submit()
  })

  $(document).on('click', '.js-delete-filter', function () {
    var ransackField = $(this).parents('.js-filter').data('ransack-field')

    $('#' + ransackField).val('')
    $('#table-filter form').submit()
  })

  function ransackField (value) {
    switch (value) {
      case 'Date Range':
        return 'Start'
      case '':
        return 'Stop'
      default:
        return value.trim()
    }
  }

  $('.js-filterable').each(function () {
    var $this = $(this)

    if ($this.val()) {
      var ransackValue, filter
      var ransackFieldId = $this.attr('id')
      var label = $('label[for="' + ransackFieldId + '"]')

      if ($this.is('select')) {
        ransackValue = $this.find('option:selected').text()
      } else {
        ransackValue = $this.val()
      }

      label = ransackField(label.text()) + ': ' + ransackValue

      filter = '' + label + ''
      $(".js-filters").append(filter).show()
    }
  })

  // per page dropdown
  // preserves all selected filters / queries supplied by user
  // changes only per_page value
  $('.js-per-page-select').change(function () {
    var form = $(this).closest('.js-per-page-form')
    var url = form.attr('action')
    var value = $(this).val().toString()
    if (url.match(/\?/)) {
      url += '&per_page=' + value
    } else {
      url += '?per_page=' + value
    }
    window.location = url
  })

  // injects per_page settings to all available search forms
  // so when user changes some filters / queries per_page is preserved
  $(document).ready(function () {
    var perPageDropdown = $('.js-per-page-select:first')
    if (perPageDropdown.length) {
      var perPageValue = perPageDropdown.val().toString()
      var perPageInput = '<input type="hidden" name="per_page" value=' + perPageValue + ' />'
      $('#table-filter form').append(perPageInput)
    }
  })

  // Make flash messages disappear
  setTimeout(function () { $('.alert-auto-disappear').slideUp() }, 5000)
})

$.fn.visible = function (cond) { this[ cond ? 'show' : 'hide' ]() }
// eslint-disable-next-line camelcase
function show_flash (type, message) {
  var flashDiv = $('.alert-' + type)
  if (flashDiv.length === 0) {
    flashDiv = $('
')
    $('#content').prepend(flashDiv)
  }
  flashDiv.html(message).show().delay(10000).slideUp()
}

// Apply to individual radio button that makes another element visible when checked
$.fn.radioControlsVisibilityOfElement = function (dependentElementSelector) {
  if (!this.get(0)) { return }
  var showValue = this.get(0).value
  var radioGroup = $("input[name='" + this.get(0).name + "']")
  radioGroup.each(function () {
    $(this).click(function () {
      // eslint-disable-next-line eqeqeq
      $(dependentElementSelector).visible(this.checked && this.value == showValue)
    })
    if (this.checked) { this.click() }
  })
}
// eslint-disable-next-line camelcase
function handle_date_picker_fields () {
  $('.datepicker').datepicker({
    dateFormat: Spree.translations.date_picker,
    dayNames: Spree.translations.abbr_day_names,
    dayNamesMin: Spree.translations.abbr_day_names,
    firstDay: Spree.translations.first_day,
    monthNames: Spree.translations.month_names,
    prevText: Spree.translations.previous,
    nextText: Spree.translations.next,
    showOn: 'focus',
    showAnim: ''
  })

  // Correctly display range dates
  $('.date-range-filter .datepicker-from').datepicker('option', 'onSelect', function (selectedDate) {
    $('.date-range-filter .datepicker-to').datepicker('option', 'minDate', selectedDate)
  })
  $('.date-range-filter .datepicker-to').datepicker('option', 'onSelect', function (selectedDate) {
    $('.date-range-filter .datepicker-from').datepicker('option', 'maxDate', selectedDate)
  })
}

$(document).ready(function() {
  handle_date_picker_fields()
  $('.observe_field').on('change', function() {
    target = $(this).data('update')
    $(target).hide()
    $.ajax({
      dataType: 'html',
      url: $(this).data('base-url') + encodeURIComponent($(this).val()),
      type: 'GET'
    }).done(function (data) {
      $(target).html(data)
      $(target).show()
    })
  })

  var uniqueId = 1
  $('.spree_add_fields').click(function () {
    var target = $(this).data('target')
    var newTableRow = $(target + ' tr:visible:last').clone()
    var newId = new Date().getTime() + (uniqueId++)
    newTableRow.find('input, select').each(function () {
      var el = $(this)
      el.val('')
      el.prop('id', el.prop('id').replace(/\d+/, newId))
      el.prop('name', el.prop('name').replace(/\d+/, newId))
    })
    // When cloning a new row, set the href of all icons to be an empty "#"
    // This is so that clicking on them does not perform the actions for the
    // duplicated row
    newTableRow.find('a').each(function () {
      var el = $(this)
      el.prop('href', '#')
    })
    $(target).prepend(newTableRow)
  })

  $('body').on('click', '.delete-resource', function () {
    var el = $(this)
    if (confirm(el.data('confirm'))) {
      $.ajax({
        type: 'POST',
        url: $(this).prop('href'),
        data: {
          _method: 'delete',
          authenticity_token: AUTH_TOKEN
        },
        dataType: 'script'
      }).done(function () {
        var $flash_element = $('.alert-success')
        if ($flash_element.length) {
          el.parents('tr').fadeOut('hide', function () {
            $(this).remove()
          })
        }
      }).fail(function (response) {
        show_flash('error', response.responseText)
      })
    }
    return false
  })

  $('body').on('click', 'a.spree_remove_fields', function () {
    el = $(this)
    el.prev('input[type=hidden]').val('1')
    el.closest('.fields').hide()
    if (el.prop('href').substr(-1) === '#') {
      el.parents('tr').fadeOut('hide')
    } else if (el.prop('href')) {
      $.ajax({
        type: 'POST',
        url: el.prop('href'),
        data: {
          _method: 'delete',
          authenticity_token: AUTH_TOKEN
        }
      }).done(function () {
        el.parents('tr').fadeOut('hide', function () {
          $(this).remove()
        })
      }).fail(function (response) {
        show_flash('error', response.responseText)
      })
    }
    return false
  })

  $('body').on('click', '.select_properties_from_prototype', function() {
    $('#busy_indicator').show()
    var clicked_link = $(this)
    $.ajax({
      dataType: 'script',
      url: clicked_link.prop('href'),
      type: 'GET'
    }).done(function () {
      clicked_link.parent('td').parent('tr').hide()
      $('#busy_indicator').hide()
    })
    return false
  })

  // Sortable List Up-Down
  var element = document.getElementById('sortVert')
  if (element !== null && element !== '') {
    Sortable.create(element, {
      handle: '.move-handle',
      animation: 550,
      ghostClass: 'bg-light',
      dragClass: "sortable-drag-v",
      easing: 'cubic-bezier(1, 0, 0, 1)',
      swapThreshold: 0.9,
      forceFallback: true,
      onEnd: function (evt) {
        var itemEl = evt.item
        var positions = { authenticity_token: AUTH_TOKEN }
        $.each($('tr', element), function(position, obj) {
          reg = /spree_(\w+_?)+_(\d+)/
          parts = reg.exec($(obj).prop('id'))
          if (parts) {
            positions['positions[' + parts[2] + ']'] = position + 1
          }
        })
        $.ajax({
          type: 'POST',
          dataType: 'json',
          url: $(itemEl).closest('table.sortable').data('sortable-link'),
          data: positions
        })
      }
    })
  }

  // Close notifications
  $('a.dismiss').click(function () {
    $(this).parent().fadeOut()
  })

  // Utility
  window.Spree.advanceOrder = function() {
    $.ajax({
      type: 'PUT',
      async: false,
      data: {
        token: Spree.api_key
      },
      url: Spree.url(Spree.routes.checkouts_api + '/' + order_number + '/advance')
    }).done(function() {
      window.location.reload()
    })
  }
})
<commit_msg>Update CC issues with trailing spaces.<commit_after>/**
This is a collection of javascript functions and whatnot
under the spree namespace that do stuff we find helpful.
Hopefully, this will evolve into a propper class.
**/

/* global AUTH_TOKEN, order_number, Sortable */

jQuery(function ($) {
  // Add some tips
  $('.with-tip').tooltip()

  $('.js-show-index-filters').click(function () {
    $('.filter-well').slideToggle()
    $(this).parents('.filter-wrap').toggleClass('collapsed')
  })

  // Off Canvas Sidebar Functionality
  var sidebarOpen    = $('#sidebar-open')
  var sidebarClose   = $('#sidebar-close')
  var body            = $('body')
  var activeItem     = $('#main-sidebar').find('.selected')
  var modalBackdrop  = $('#multi-backdrop')

  function closeAllMenus() {
    $(body).removeClass()
    body.addClass('admin')
    modalBackdrop.removeClass('show')
  }
  modalBackdrop.click(closeAllMenus)

  activeItem.closest('.nav-sidebar').addClass('active-option')
  activeItem.closest('.nav-pills').addClass('in show')

  function openMenu() {
    body.addClass('sidebar-open modal-open')
    modalBackdrop.addClass('show')
  }

  function closeMenu() {
    body.removeClass('sidebar-open modal-open')
    modalBackdrop.removeClass('show')
  }

  sidebarOpen.click(openMenu)
  sidebarClose.click(closeMenu)

  // Contextual Sidebar Menu Functionality
  var contextualSidebarMenuToggle    = $('#contextual-menu-open')

  function openContextualToggle() {
    if (document.body.classList.contains('contextualSideMenu-open')) {
      body.removeClass('contextualSideMenu-open modal-open')
      modalBackdrop.removeClass('show')
    } else {
      body.addClass('contextualSideMenu-open modal-open')
      modalBackdrop.addClass('show')
    }
  }

  contextualSidebarMenuToggle.click(openContextualToggle)

  // TODO: remove this js temp behaviour and fix this decent
  // Temp quick search
  // When there was a search term, copy it
  $('.js-quick-search').val($('.js-quick-search-target').val())
  // Catch the quick search form submit and submit the real form
  $('#quick-search').submit(function () {
    $('.js-quick-search-target').val($('.js-quick-search').val())
    $('#table-filter form').submit()
    return false
  })

  // Replace ▼ and ▲ in sort_link with nicer icons
  $('.sort_link').each(function () {
    // Remove the &nbsp in the text
    var sortLinkText = $(this).text().replace('\xA0', '')

    if (sortLinkText.indexOf('▼') >= 0) {
      $(this).text(sortLinkText.replace('▼', ''))
      $(this).append('')
    } else if (sortLinkText.indexOf('▲') >= 0) {
      $(this).text(sortLinkText.replace('▲', ''))
      $(this).append('')
    }
  })

  // Clickable ransack filters
  $('.js-add-filter').click(function () {
    var ransackField = $(this).data('ransack-field')
    var ransackValue = $(this).data('ransack-value')

    $('#' + ransackField).val(ransackValue)
    $('#table-filter form').submit()
  })

  $(document).on('click', '.js-delete-filter', function () {
    var ransackField = $(this).parents('.js-filter').data('ransack-field')

    $('#' + ransackField).val('')
    $('#table-filter form').submit()
  })

  function ransackField (value) {
    switch (value) {
      case 'Date Range':
        return 'Start'
      case '':
        return 'Stop'
      default:
        return value.trim()
    }
  }

  $('.js-filterable').each(function () {
    var $this = $(this)

    if ($this.val()) {
      var ransackValue, filter
      var ransackFieldId = $this.attr('id')
      var label = $('label[for="' + ransackFieldId + '"]')

      if ($this.is('select')) {
        ransackValue = $this.find('option:selected').text()
      } else {
        ransackValue = $this.val()
      }

      label = ransackField(label.text()) + ': ' + ransackValue

      filter = '' + label + ''
      $(".js-filters").append(filter).show()
    }
  })

  // per page dropdown
  // preserves all selected filters / queries supplied by user
  // changes only per_page value
  $('.js-per-page-select').change(function () {
    var form = $(this).closest('.js-per-page-form')
    var url = form.attr('action')
    var value = $(this).val().toString()
    if (url.match(/\?/)) {
      url += '&per_page=' + value
    } else {
      url += '?per_page=' + value
    }
    window.location = url
  })

  // injects per_page settings to all available search forms
  // so when user changes some filters / queries per_page is preserved
  $(document).ready(function () {
    var perPageDropdown = $('.js-per-page-select:first')
    if (perPageDropdown.length) {
      var perPageValue = perPageDropdown.val().toString()
      var perPageInput = '<input type="hidden" name="per_page" value=' + perPageValue + ' />'
      $('#table-filter form').append(perPageInput)
    }
  })

  // Make flash messages disappear
  setTimeout(function () { $('.alert-auto-disappear').slideUp() }, 5000)
})

$.fn.visible = function (cond) { this[ cond ? 'show' : 'hide' ]() }
// eslint-disable-next-line camelcase
function show_flash (type, message) {
  var flashDiv = $('.alert-' + type)
  if (flashDiv.length === 0) {
    flashDiv = $('
')
    $('#content').prepend(flashDiv)
  }
  flashDiv.html(message).show().delay(10000).slideUp()
}

// Apply to individual radio button that makes another element visible when checked
$.fn.radioControlsVisibilityOfElement = function (dependentElementSelector) {
  if (!this.get(0)) { return }
  var showValue = this.get(0).value
  var radioGroup = $("input[name='" + this.get(0).name + "']")
  radioGroup.each(function () {
    $(this).click(function () {
      // eslint-disable-next-line eqeqeq
      $(dependentElementSelector).visible(this.checked && this.value == showValue)
    })
    if (this.checked) { this.click() }
  })
}
// eslint-disable-next-line camelcase
function handle_date_picker_fields () {
  $('.datepicker').datepicker({
    dateFormat: Spree.translations.date_picker,
    dayNames: Spree.translations.abbr_day_names,
    dayNamesMin: Spree.translations.abbr_day_names,
    firstDay: Spree.translations.first_day,
    monthNames: Spree.translations.month_names,
    prevText: Spree.translations.previous,
    nextText: Spree.translations.next,
    showOn: 'focus',
    showAnim: ''
  })

  // Correctly display range dates
  $('.date-range-filter .datepicker-from').datepicker('option', 'onSelect', function (selectedDate) {
    $('.date-range-filter .datepicker-to').datepicker('option', 'minDate', selectedDate)
  })
  $('.date-range-filter .datepicker-to').datepicker('option', 'onSelect', function (selectedDate) {
    $('.date-range-filter .datepicker-from').datepicker('option', 'maxDate', selectedDate)
  })
}

$(document).ready(function() {
  handle_date_picker_fields()
  $('.observe_field').on('change', function() {
    target = $(this).data('update')
    $(target).hide()
    $.ajax({
      dataType: 'html',
      url: $(this).data('base-url') + encodeURIComponent($(this).val()),
      type: 'GET'
    }).done(function (data) {
      $(target).html(data)
      $(target).show()
    })
  })

  var uniqueId = 1
  $('.spree_add_fields').click(function () {
    var target = $(this).data('target')
    var newTableRow = $(target + ' tr:visible:last').clone()
    var newId = new Date().getTime() + (uniqueId++)
    newTableRow.find('input, select').each(function () {
      var el = $(this)
      el.val('')
      el.prop('id', el.prop('id').replace(/\d+/, newId))
      el.prop('name', el.prop('name').replace(/\d+/, newId))
    })
    // When cloning a new row, set the href of all icons to be an empty "#"
    // This is so that clicking on them does not perform the actions for the
    // duplicated row
    newTableRow.find('a').each(function () {
      var el = $(this)
      el.prop('href', '#')
    })
    $(target).prepend(newTableRow)
  })

  $('body').on('click', '.delete-resource', function () {
    var el = $(this)
    if (confirm(el.data('confirm'))) {
      $.ajax({
        type: 'POST',
        url: $(this).prop('href'),
        data: {
          _method: 'delete',
          authenticity_token: AUTH_TOKEN
        },
        dataType: 'script'
      }).done(function () {
        var $flash_element = $('.alert-success')
        if ($flash_element.length) {
          el.parents('tr').fadeOut('hide', function () {
            $(this).remove()
          })
        }
      }).fail(function (response) {
        show_flash('error', response.responseText)
      })
    }
    return false
  })

  $('body').on('click', 'a.spree_remove_fields', function () {
    el = $(this)
    el.prev('input[type=hidden]').val('1')
    el.closest('.fields').hide()
    if (el.prop('href').substr(-1) === '#') {
      el.parents('tr').fadeOut('hide')
    } else if (el.prop('href')) {
      $.ajax({
        type: 'POST',
        url: el.prop('href'),
        data: {
          _method: 'delete',
          authenticity_token: AUTH_TOKEN
        }
      }).done(function () {
        el.parents('tr').fadeOut('hide', function () {
          $(this).remove()
        })
      }).fail(function (response) {
        show_flash('error', response.responseText)
      })
    }
    return false
  })

  $('body').on('click', '.select_properties_from_prototype', function() {
    $('#busy_indicator').show()
    var clicked_link = $(this)
    $.ajax({
      dataType: 'script',
      url: clicked_link.prop('href'),
      type: 'GET'
    }).done(function () {
      clicked_link.parent('td').parent('tr').hide()
      $('#busy_indicator').hide()
    })
    return false
  })

  // Sortable List Up-Down
  var element = document.getElementById('sortVert')
  if (element !== null && element !== '') {
    Sortable.create(element, {
      handle: '.move-handle',
      animation: 550,
      ghostClass: 'bg-light',
      dragClass: "sortable-drag-v",
      easing: 'cubic-bezier(1, 0, 0, 1)',
      swapThreshold: 0.9,
      forceFallback: true,
      onEnd: function (evt) {
        var itemEl = evt.item
        var positions = { authenticity_token: AUTH_TOKEN }
        $.each($('tr', element), function(position, obj) {
          reg = /spree_(\w+_?)+_(\d+)/
          parts = reg.exec($(obj).prop('id'))
          if (parts) {
            positions['positions[' + parts[2] + ']'] = position + 1
          }
        })
        $.ajax({
          type: 'POST',
          dataType: 'json',
          url: $(itemEl).closest('table.sortable').data('sortable-link'),
          data: positions
        })
      }
    })
  }

  // Close notifications
  $('a.dismiss').click(function () {
    $(this).parent().fadeOut()
  })

  // Utility
  window.Spree.advanceOrder = function() {
    $.ajax({
      type: 'PUT',
      async: false,
      data: {
        token: Spree.api_key
      },
      url: Spree.url(Spree.routes.checkouts_api + '/' + order_number + '/advance')
    }).done(function() {
      window.location.reload()
    })
  }
})
<|endoftext|>


<commit_before>/*
 * This file is part of the RedKiteCmsBunde Application and it is distributed
 * under the GPL LICENSE Version 2.0. To use this application you must leave
 * intact this copyright notice.
 *
 * Copyright (c) RedKite Labs <webmaster@redkite-labs.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * For extra documentation and help please visit http://www.redkite-labs.com
 *
 * @license    GPL LICENSE Version 2.0
 *
 */

;(function($){
    var settings;

    var methods = {
        start: function()
        {
            var $this = $(this);
            initList($this);

            $('body').data('al-active-inline-list', $this);

            return this;
        },
        stop: function()
        {
            $('.al-add-item-list').unbind().remove();
            $('.al-delete-item-list').unbind().remove();
            $('.inline-list-commands-container').remove();
            $('body').data('al-active-inline-list', null);

            return this;
        }
    };

    function initList(element)
    {
        var buttonAddMarkup = '<button class="btn btn-xs btn-primary"></button>';
        var buttonDeleteMarkup = '<button class="btn btn-xs btn-danger"></button>';
        if (bootstrapVersion == "2.x") {
            buttonAddMarkup = '';
            buttonDeleteMarkup = '';
        }

        var addButton = document.createElement("div");
        $(addButton)
            .addClass("al-add-item-list")
            .attr('data-item', '-1')
            .append(buttonAddMarkup)
            .position({
                my: "left top",
                at: "left top",
                of: element,
                collision: 'fit fit'
            })
            .appendTo('body')
            .show()
        ;

        element
            .find(settings.target)
            .each(function(){
                var $this = $(this);
                if ($this.hasClass('al-empty')) {
                    return;
                }

                if ( ! $this.is(':visible')) {
                    return;
                }

                var containerDiv = $(document.createElement("div"));
                var addButton = document.createElement("div");
                $(addButton)
                    .addClass("al-add-item-list")
                    .attr('data-item', $this.attr('data-item'))
                    .append(buttonAddMarkup)
                    .appendTo(containerDiv)
                    .css('left', '0')
                    .show()
                ;

                var removeButton = document.createElement("div");
                $(removeButton)
                    .addClass("al-delete-item-list")
                    .attr('data-item', $this.attr('data-item'))
                    .attr('data-slot-name', $this.attr('data-slot-name'))
                    .append(buttonDeleteMarkup)
                    .appendTo(containerDiv)
                    .css('left', '26px')
                    .show()
                ;

                containerDiv.position({
                    my: "center top",
                    at: settings.position,
                    of: $this,
                    collision: 'fit fit'
                })
                .addClass('inline-list-commands-container')
                .css('position', 'absolute')
                .appendTo('body') ;
            })
        ;

        $('.al-add-item-list').show();
        if (settings.addValue == null) {
            // Adds a custom value
            $('.al-add-item-list')
                .click(function(event){
                    event.stopPropagation();
                    $(document).data('data-item', $(this).attr('data-item'));
                })
                .blocksMenu('add', {'filter' : settings.filterAdders})
            ;
        }
        else {

            // Adds an included block
            $('.al-add-item-list').click(function(event) {
                event.stopPropagation();
                var value = settings.addValue;
                if ($.parseJSON(value) != null) {
                    value = value.substring(0, value.length-1) + ', "item": "' + $(this).attr('data-item') + '"}';
                }

                var addItemCallback = settings.addItemCallback;

                $('body').EditBlock("Content", value, null, function()
                {
                    Holder.run();
                    addItemCallback();
                    $('.inline-list').addClass('collapsed-list');
                });
            });
        }

        $('.al-delete-item-list').click(function(event){
            event.stopPropagation();
            if (confirm(translate('Are you sure to remove the active item'))) {
                var $this = $(this);
                var deleteItemCallback = settings.deleteItemCallback;
                $('body').EditBlock("Content", '{"operation": "remove", "item": "' + $this.attr('data-item') + '", "slotName": "' + $this.attr('data-slot-name') + '"}', null, function()
                {
                    Holder.run();
                    deleteItemCallback();
                    $('.inline-list').addClass('collapsed-list');
                });
            }
        });
    }

    $.fn.inlinelist = function( method, options ) {

        settings = $.extend( {
          target                : '> li',
          addValue              : null,
          position              : 'left bottom',
          filterAdders          : 'none',
          addItemCallback       : function(){},
          deleteItemCallback    : function(){}
        }, options);

        if ( methods[method] ) {
            return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof method === 'object' || ! method ) {
            return methods.init.apply( this, arguments );
        } else {
            $.error( 'Method ' +  method + ' does not exist on jQuery.inlinelist' );
        }
    };
})($);<commit_msg>added a callback called when the list is started end another one when the list is stopped<commit_after>/*
 * This file is part of the RedKiteCmsBunde Application and it is distributed
 * under the GPL LICENSE Version 2.0. To use this application you must leave
 * intact this copyright notice.
 *
 * Copyright (c) RedKite Labs <webmaster@redkite-labs.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * For extra documentation and help please visit http://www.redkite-labs.com
 *
 * @license    GPL LICENSE Version 2.0
 *
 */

;(function($){
    var settings;

    var methods = {
        start: function()
        {
            var $this = $(this);
            initList($this);

            $('body').data('al-active-inline-list', $this);

            settings.startListCallback();

            return this;
        },
        stop: function()
        {
            $('.al-add-item-list').unbind().remove();
            $('.al-delete-item-list').unbind().remove();
            $('.inline-list-commands-container').remove();
            $('body').data('al-active-inline-list', null);

            settings.stopListCallback();

            return this;
        }
    };

    function initList(element)
    {
        var buttonAddMarkup = '<button class="btn btn-xs btn-primary"></button>';
        var buttonDeleteMarkup = '<button class="btn btn-xs btn-danger"></button>';
        if (bootstrapVersion == "2.x") {
            buttonAddMarkup = '';
            buttonDeleteMarkup = '';
        }

        var addButton = document.createElement("div");
        $(addButton)
            .addClass("al-add-item-list")
            .attr('data-item', '-1')
            .append(buttonAddMarkup)
            .position({
                my: "left top",
                at: "left top",
                of: element,
                collision: 'fit fit'
            })
            .appendTo('body')
            .show()
        ;

        element
            .find(settings.target)
            .each(function(){
                var $this = $(this);
                if ($this.hasClass('al-empty')) {
                    return;
                }

                if ( ! $this.is(':visible')) {
                    return;
                }

                var containerDiv = $(document.createElement("div"));
                var addButton = document.createElement("div");
                $(addButton)
                    .addClass("al-add-item-list")
                    .attr('data-item', $this.attr('data-item'))
                    .append(buttonAddMarkup)
                    .appendTo(containerDiv)
                    .css('left', '0')
                    .show()
                ;

                var removeButton = document.createElement("div");
                $(removeButton)
                    .addClass("al-delete-item-list")
                    .attr('data-item', $this.attr('data-item'))
                    .attr('data-slot-name', $this.attr('data-slot-name'))
                    .append(buttonDeleteMarkup)
                    .appendTo(containerDiv)
                    .css('left', '26px')
                    .show()
                ;

                containerDiv.position({
                    my: "center top",
                    at: settings.position,
                    of: $this,
                    collision: 'fit fit'
                })
                .addClass('inline-list-commands-container')
                .css('position', 'absolute')
                .appendTo('body') ;
            })
        ;

        $('.al-add-item-list').show();
        if (settings.addValue == null) {
            // Adds a custom value
            $('.al-add-item-list')
                .click(function(event){
                    event.stopPropagation();
                    $(document).data('data-item', $(this).attr('data-item'));
                })
                .blocksMenu('add', {'filter' : settings.filterAdders})
            ;
        }
        else {

            // Adds an included block
            $('.al-add-item-list').click(function(event) {
                event.stopPropagation();
                var value = settings.addValue;
                if ($.parseJSON(value) != null) {
                    value = value.substring(0, value.length-1) + ', "item": "' + $(this).attr('data-item') + '"}';
                }

                var addItemCallback = settings.addItemCallback;

                $('body').EditBlock("Content", value, null, function()
                {
                    Holder.run();
                    addItemCallback();
                    $('.inline-list').addClass('collapsed-list');
                });
            });
        }

        $('.al-delete-item-list').click(function(event){
            event.stopPropagation();
            if (confirm(translate('Are you sure to remove the active item'))) {
                var $this = $(this);
                var deleteItemCallback = settings.deleteItemCallback;
                $('body').EditBlock("Content", '{"operation": "remove", "item": "' + $this.attr('data-item') + '", "slotName": "' + $this.attr('data-slot-name') + '"}', null, function()
                {
                    Holder.run();
                    deleteItemCallback();
                    $('.inline-list').addClass('collapsed-list');
                });
            }
        });
    }

    $.fn.inlinelist = function( method, options ) {

        settings = $.extend( {
          target                : '> li',
          addValue              : null,
          position              : 'left bottom',
          filterAdders          : 'none',
          startListCallback     : function(){},
          stopListCallback      : function(){},
          addItemCallback       : function(){},
          deleteItemCallback    : function(){}
        }, options);

        if ( methods[method] ) {
            return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof method === 'object' || ! method ) {
            return methods.init.apply( this, arguments );
        } else {
            $.error( 'Method ' +  method + ' does not exist on jQuery.inlinelist' );
        }
    };
})($);<|endoftext|>


<commit_before>'use strict';

angular.module('impactApp')
  .controller('MdphInputCtrl', function($state) {

    this.zipcode = '';

    this.isOk =  () => {
      const zipcodeRegex = /^([0-8][0-9]|9[0-5]|2A|2a|2B|2b|97[1-4]|976)$/;
      return zipcodeRegex.test(this.zipcode);
    };

    this.go = () => {
      $state.go('departement', {codeDepartement: this.zipcode});
    };

  });
<commit_msg>Add codeDepartement uppercase<commit_after>'use strict';

angular.module('impactApp')
  .controller('MdphInputCtrl', function($state) {

    this.zipcode = '';

    this.isOk =  () => {
      const zipcodeRegex = /^([0-8][0-9]|9[0-5]|2A|2a|2B|2b|97[1-4]|976)$/;
      return zipcodeRegex.test(this.zipcode);
    };

    this.go = () => {
      const codeDepartement = this.zipcode.toUpperCase();
      $state.go('departement', {codeDepartement});
    };

  });
<|endoftext|>


<commit_before>'use strict';

angular.module('impactApp')
  .component('prestation', {
    templateUrl: 'components/prestations/prestation.html',
    bindings: {
      prestation: '=',
      id: '@',
      titre: '@',
      link: '@'
    },
    controllerAs: 'prestationctrl',
    controller: function() {
      console.log('this.prestation, this.id, this.label, this.url', this.prestation, this.id, this.label, this.url, this);
    }
  });
<commit_msg>remove unwanted log<commit_after>'use strict';

angular.module('impactApp')
  .component('prestation', {
    templateUrl: 'components/prestations/prestation.html',
    bindings: {
      prestation: '=',
      id: '@',
      titre: '@',
      link: '@'
    },
    controllerAs: 'prestationctrl',
    controller: function() {
    }
  });
<|endoftext|>


<commit_before>/*
* Copyright 2014 Space Dynamics Laboratory - Utah State University Research Foundation.
*
* 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.
*/
'use strict';

angular.module('openstorefrontApp')
.directive('modal', function () {
  return {
    restrict: 'AE',
    scope: {},
    controller: '@',
    name: 'controllerName',
    template: '

 <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

 </div
',
    link: function postLink(scope, element, attrs) {
      var parent = scope.$parent;

      parent.$on('updateBody', function(event) { /* jshint unused: false */
        scope.nav = parent.nav;
        scope.body = null;
        scope.body = 'views/modalDefaults/body.html';
        if (parent.classes !== undefined && parent.classes !== null) {
          scope.classes = parent.classes;
        }
      });

      scope.header = 'views/modalDefaults/header.html';

      scope.footer = 'views/modalDefaults/footer.html';

      scope.body = 'views/modalDefaults/body.html';

      scope.id = attrs.modalid;

      if (attrs.header !== null && attrs.header !== undefined) {
        scope.header = attrs.header;
      }
      if (attrs.footer !== null && attrs.footer !== undefined) {
        scope.footer = attrs.footer;
      }
      if (attrs.body !== null && attrs.body !== undefined) {
        scope.body = attrs.body;
      }

      if (attrs.modalclasses !== null && attrs.modalclasses !== undefined) {
        scope.classes = attrs.modalclasses;
      }

      scope.$watch('body', function() {
        console.log('Body Changed');
        console.log('Body', scope.body);

      });

    }
  };
});
<commit_msg>Fixed a bug that I introduced when I built in the body refresh.<commit_after>/*
* Copyright 2014 Space Dynamics Laboratory - Utah State University Research Foundation.
*
* 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.
*/
'use strict';

angular.module('openstorefrontApp')
.directive('modal', function () {
  return {
    restrict: 'AE',
    scope: {},
    controller: '@',
    name: 'controllerName',
    template: '

 <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

 </div
',
    link: function postLink(scope, element, attrs) {
      var parent = scope.$parent;

      parent.$on('updateBody', function(event) { /* jshint unused: false */
        if (parent.nav !== undefined && parent.nav !== null) {
          scope.nav = parent.nav;
        }
        scope.body = null;
        scope.body = 'views/modalDefaults/body.html';
        if (parent.classes !== undefined && parent.classes !== null) {
          scope.classes = parent.classes;
        }
      });

      scope.header = 'views/modalDefaults/header.html';

      scope.footer = 'views/modalDefaults/footer.html';

      scope.body = 'views/modalDefaults/body.html';

      scope.id = attrs.modalid;

      if (attrs.header !== null && attrs.header !== undefined) {
        scope.header = attrs.header;
      }
      if (attrs.footer !== null && attrs.footer !== undefined) {
        scope.footer = attrs.footer;
      }
      if (attrs.body !== null && attrs.body !== undefined) {
        scope.body = attrs.body;
      }

      if (attrs.modalclasses !== null && attrs.modalclasses !== undefined) {
        scope.classes = attrs.modalclasses;
      }

      scope.$watch('body', function() {
        console.log('Body Changed');
        console.log('Body', scope.body);

      });

    }
  };
});
<|endoftext|>


<commit_before>import React, { createElement as h } from "react";
import input from "components/input";
import spinner from "components/spinner";
import paper from "components/Paper";
import formGroup from "components/FormGroup";

import { observer } from "mobx-react";

export default context => {
  const { tr } = context;
  const FormGroup = formGroup(context);
  const Paper = paper(context);
  const ButtonLoading = require("mdlean/lib/button").default(context);
  const UsernameInput = input(context);
  const EmailInput = input(context);
  const BioInput = input(context);

  function ProfileForm({ store }) {
    const { errors } = store;
    if (store.opGet.loading) {
      return h(spinner(context));
    }
    return (
      <Paper>
        <form onSubmit={e => e.preventDefault()}>

{tr.t("My Profile")}

          { store.picture && }
          <FormGroup>
            <UsernameInput
              id="username"
              label={tr.t("Username")}
              value={store.username}
              disabled
            />
          </FormGroup>
          <FormGroup>
            <EmailInput
              id="email"
              value={store.email}
              disabled
              label={tr.t("Email")}
            />
          </FormGroup>

          <FormGroup>

{tr.t("About Me")}

            <BioInput
              className="biography-input"
              value={store.profile.biography || ""}
              error={errors.biography && errors.biography[0]}
              label={tr.t("Enter Biography")}
              rows={1}
              onChange={e => {
                store.profile.biography = e.target.value;
              }}
            />
          </FormGroup>
          {/*<FormGroup>

{tr.t("Picture")}

            <input
              type="file"
              accept="image/*"
              onChange={event => store.uploadPicture(event)}
            />

          </FormGroup>*/}
          <FormGroup>
            <ButtonLoading
              className="btn-update-profile"
              raised
              css={{ width: 256 }}
              onClick={() => store.update()}
              label={tr.t("Update Profile")}
            />
          </FormGroup>
        </form>
      </Paper>
    );
  }
  return observer(ProfileForm);
};
<commit_msg>fix button update profile<commit_after>/** @jsx jsx */
import { jsx, css } from "@emotion/core";
import { createElement as h } from "react";
import input from "components/input";
import spinner from "components/spinner";
import paper from "components/Paper";
import formGroup from "components/FormGroup";

import { observer } from "mobx-react";

export default context => {
  const { tr } = context;
  const FormGroup = formGroup(context);
  const Paper = paper(context);
  const ButtonLoading = require("mdlean/lib/button").default(context, { cssOverride: css`width: 256px;` });
  const UsernameInput = input(context);
  const EmailInput = input(context);
  const BioInput = input(context);

  function ProfileForm({ store }) {
    const { errors } = store;
    if (store.opGet.loading) {
      return h(spinner(context));
    }
    return (
      <Paper>
        <form onSubmit={e => e.preventDefault()}>

{tr.t("My Profile")}

          {store.picture && }
          <FormGroup>
            <UsernameInput
              id="username"
              label={tr.t("Username")}
              value={store.username}
              disabled
            />
          </FormGroup>
          <FormGroup>
            <EmailInput
              id="email"
              value={store.email}
              disabled
              label={tr.t("Email")}
            />
          </FormGroup>

          <FormGroup>

{tr.t("About Me")}

            <BioInput
              className="biography-input"
              value={store.profile.biography || ""}
              error={errors.biography && errors.biography[0]}
              label={tr.t("Enter Biography")}
              rows={1}
              onChange={e => {
                store.profile.biography = e.target.value;
              }}
            />
          </FormGroup>
          {/*<FormGroup>

{tr.t("Picture")}

            <input
              type="file"
              accept="image/*"
              onChange={event => store.uploadPicture(event)}
            />

          </FormGroup>*/}
          <FormGroup>
            <ButtonLoading
              className="btn-update-profile"
              raised
              onClick={() => store.update()}
              label={tr.t("Update Profile")}
            />
          </FormGroup>
        </form>
      </Paper>
    );
  }
  return observer(ProfileForm);
};
<|endoftext|>


<commit_before>import '../page-chooser';
import '../draftail';
import './telepath';
import './widgets';

import $ from 'jquery';
window.$ = $;

describe('telepath: wagtail.widgets.Widget', () => {
  let boundWidget;

  beforeEach(() => {
    // Create a placeholder to render the widget
    document.body.innerHTML = '

';

    // Unpack and render a simple text block widget
    const widgetDef = window.telepath.unpack({
      _type: 'wagtail.widgets.Widget',
      _args: [
        '<input type="text" name="__NAME__" maxlength="255" id="__ID__">',
        '__ID__'
      ]
    });
    boundWidget = widgetDef.render($('#placeholder'), 'the-name', 'the-id', 'The Value');
  });

  test('it renders correctly', () => {
    expect(document.body.innerHTML).toBe('<input type="text" name="the-name" maxlength="255" id="the-id">');
    expect(document.querySelector('input').value).toBe('The Value');
  });

  test('getValue() returns the current value', () => {
    expect(boundWidget.getValue()).toBe('The Value');
  });

  test('getState() returns the current state', () => {
    expect(boundWidget.getState()).toBe('The Value');
  });

  test('setState() changes the current state', () => {
    boundWidget.setState('The new Value');
    expect(document.querySelector('input').value).toBe('The new Value');
  });

  test('focus() focuses the text input', () => {
    boundWidget.focus();
    expect(document.activeElement).toBe(document.querySelector('input'));
  });
});

describe('telepath: wagtail.widgets.RadioSelect', () => {
  let boundWidget;

  beforeEach(() => {
    // Create a placeholder to render the widget
    document.body.innerHTML = '

';

    // Unpack and render a radio select widget
    const widgetDef = window.telepath.unpack({
      _type: 'wagtail.widgets.RadioSelect',
      _args: [
        `

            <input type="radio" name="__NAME__" value="tea" id="__ID___0"> Tea

            <input type="radio" name="__NAME__" value="coffee" id="__ID___1"> Coffee

`,
        '__ID___0'
      ]
    });
    boundWidget = widgetDef.render($('#placeholder'), 'the-name', 'the-id', 'tea');
  });

  test('it renders correctly', () => {
    expect(document.body.innerHTML).toMatchSnapshot();
    expect(document.querySelector('input[value="tea"]').checked).toBe(true);
    expect(document.querySelector('input[value="coffee"]').checked).toBe(false);
  });

  test('getValue() returns the current value', () => {
    expect(boundWidget.getValue()).toBe('tea');
  });

  test('getState() returns the current state', () => {
    expect(boundWidget.getState()).toBe('tea');
  });

  test('setState() changes the current state', () => {
    boundWidget.setState('coffee');
    expect(document.querySelector('input[value="tea"]').checked).toBe(false);
    expect(document.querySelector('input[value="coffee"]').checked).toBe(true);
  });

  test('focus() focuses the text input', () => {
    boundWidget.focus();

    // Note: This widget always focuses the last element
    expect(document.activeElement).toBe(document.querySelector('input[value="coffee"]'));
  });
});

describe('telepath: wagtail.widgets.PageChooser', () => {
  let boundWidget;

  beforeEach(() => {
    // Create a placeholder to render the widget
    document.body.innerHTML = '

';

    // Unpack and render a radio select widget
    const widgetDef = window.telepath.unpack({
      _type: 'wagtail.widgets.PageChooser',
      _args: [
        `

                <button type="button" class="button action-choose button-small button-secondary">
                  Choose another page
                </button>

                  Edit this page

            <button type="button" class="button action-choose button-small button-secondary">
              Choose a page
            </button>

        <input type="hidden" name="__NAME__" id="__ID__">`,
        '__ID__',
        {
          model_names: ['wagtailcore.page'],
          can_choose_root: false,
          user_perms: null
        }
      ]
    });
    boundWidget = widgetDef.render($('#placeholder'), 'the-name', 'the-id', {
      id: 60,
      parentId: 1,
      adminTitle: 'Welcome to the Wagtail Bakery!',
      editUrl: '/admin/pages/60/edit/'
    });
  });

  test('it renders correctly', () => {
    expect(document.body.innerHTML).toMatchSnapshot();
    expect(document.querySelector('input').value).toBe('60');
  });

  test('getValue() returns the current value', () => {
    expect(boundWidget.getValue()).toBe(60);
  });

  test('getState() returns the current state', () => {
    expect(boundWidget.getState()).toEqual({
      id: 60,
      parentId: 1,
      adminTitle: 'Welcome to the Wagtail Bakery!',
      editUrl: '/admin/pages/60/edit/'
    });
  });

  test('setState() changes the current page', () => {
    boundWidget.setState({
      id: 34,
      parentId: 3,
      adminTitle: 'Anadama',
      editUrl: '/admin/pages/34/edit/'
    });
    expect(document.body.innerHTML).toMatchSnapshot();
    expect(document.querySelector('input').value).toBe('34');
  });

  test('setState() to null clears the fields', () => {
    boundWidget.setState(null);
    expect(document.body.innerHTML).toMatchSnapshot();
    expect(document.querySelector('input').value).toBe('');
  });

  test('focus() focuses the input', () => {
    boundWidget.focus();

    // Note: This widget always focuses the unchosen button, even if it has a value
    expect(document.activeElement).toBe(document.querySelector('.unchosen button'));
  });
});

describe('telepath: wagtail.widgets.AdminAutoHeightTextInput', () => {
  let boundWidget;

  beforeEach(() => {
    window.autosize = jest.fn();

    // Create a placeholder to render the widget
    document.body.innerHTML = '

';

    // Unpack and render a textarea using the AdminAutoHeightTextInput widget
    const widgetDef = window.telepath.unpack({
      _type: 'wagtail.widgets.AdminAutoHeightTextInput',
      _args: [
        '<textarea name="__NAME__" cols="40" rows="1" id="__ID__"></textarea>',
        '__ID__'
      ]
    });
    boundWidget = widgetDef.render($('#placeholder'), 'the-name', 'the-id', 'The Value');
  });

  test('it renders correctly', () => {
    expect(document.body.innerHTML).toBe('<textarea name="the-name" cols="40" rows="1" id="the-id"></textarea>');
    expect(document.querySelector('textarea').value).toBe('The Value');
  });

  test('window.autosize was called', () => {
    expect(window.autosize.mock.calls.length).toBe(1);
    expect(window.autosize.mock.calls[0][0].get(0)).toBe(document.querySelector('textarea'));
  });

  test('getValue() returns the current value', () => {
    expect(boundWidget.getValue()).toBe('The Value');
  });

  test('getState() returns the current state', () => {
    expect(boundWidget.getState()).toBe('The Value');
  });

  test('setState() changes the current state', () => {
    boundWidget.setState('The new Value');
    expect(document.querySelector('textarea').value).toBe('The new Value');
  });

  test('focus() focuses the text input', () => {
    boundWidget.focus();
    expect(document.activeElement).toBe(document.querySelector('textarea'));
  });
});

describe('telepath: wagtail.widgets.DraftailRichTextArea', () => {
  let boundWidget;

  const TEST_VALUE = JSON.stringify({
    blocks: [{
      key: 't30wm',
      type: 'unstyled',
      depth: 0,
      text: 'Test Bold Italic',
      inlineStyleRanges: [{
        offset: 5,
        length: 4,
        style: 'BOLD'
      }, {
        offset: 10,
        length: 6,
        style: 'ITALIC'
      }],
      entityRanges: []
    }],
    entityMap: {}
  });

  beforeEach(() => {
    // Create a placeholder to render the widget
    document.body.innerHTML = '

';

    // Unpack and render a Draftail input
    const widgetDef = window.telepath.unpack({
      _type: 'wagtail.widgets.DraftailRichTextArea',
      _args: [{
        entityTypes: [{
          _dict: {
            type: 'LINK',
            icon: 'link',
            description: 'Link',
            attributes: ['url', 'id', 'parentId'],
            whitelist: {
              href: '^(http:|https:|undefined$)'
            }
          },
        }, {
          _dict: {
            type: 'IMAGE',
            icon: 'image',
            description: 'Image',
            attributes: ['id', 'src', 'alt', 'format'],
            whitelist: {
              id: true
            }
          },
        }],
        enableHorizontalRule: true,
        inlineStyles: [{
          _dict: {
            type: 'BOLD',
            icon: 'bold',
            description: 'Bold'
          },
        }, {
          _dict: {
            type: 'ITALIC',
            icon: 'italic',
            description: 'Italic'
          },
        }],
        blockTypes: [{
          _dict: {
            label: 'H2',
            type: 'header-two',
            description: 'Heading 2'
          },
        }]
      }]
    });
    boundWidget = widgetDef.render(document.getElementById('placeholder'), 'the-name', 'the-id', TEST_VALUE);
  });

  test('it renders correctly', () => {
    expect(document.querySelector('.Draftail-Editor__wrapper')).toBeTruthy();
    expect(document.querySelector('input').value).toBe(TEST_VALUE);
  });

  test('getValue() returns the current value', () => {
    expect(boundWidget.getValue()).toBe(TEST_VALUE);
  });

  test('getState() returns the current state', () => {
    expect(boundWidget.getState()).toBe(TEST_VALUE);
  });

  test('setState() changes the current state', () => {
    const NEW_VALUE = JSON.stringify({
      blocks: [{
        key: 't30wm',
        type: 'unstyled',
        depth: 0,
        text: 'New value',
        inlineStyleRanges: [],
        entityRanges: []
      }],
      entityMap: {}
    });

    expect(() => {
      boundWidget.setState(NEW_VALUE);
    }).toThrowError('DraftailRichTextArea.setState is not implemented');
  });

  test('focus() focuses the text input', () => {
    boundWidget.focus();
    expect(document.activeElement).toBe(document.querySelector('.public-DraftEditor-content'));
  });
});
<commit_msg>Unit tests for date/time widgets<commit_after>import '../page-chooser';
import '../draftail';
import './telepath';
import './widgets';

import $ from 'jquery';
window.$ = $;

describe('telepath: wagtail.widgets.Widget', () => {
  let boundWidget;

  beforeEach(() => {
    // Create a placeholder to render the widget
    document.body.innerHTML = '

';

    // Unpack and render a simple text block widget
    const widgetDef = window.telepath.unpack({
      _type: 'wagtail.widgets.Widget',
      _args: [
        '<input type="text" name="__NAME__" maxlength="255" id="__ID__">',
        '__ID__'
      ]
    });
    boundWidget = widgetDef.render($('#placeholder'), 'the-name', 'the-id', 'The Value');
  });

  test('it renders correctly', () => {
    expect(document.body.innerHTML).toBe('<input type="text" name="the-name" maxlength="255" id="the-id">');
    expect(document.querySelector('input').value).toBe('The Value');
  });

  test('getValue() returns the current value', () => {
    expect(boundWidget.getValue()).toBe('The Value');
  });

  test('getState() returns the current state', () => {
    expect(boundWidget.getState()).toBe('The Value');
  });

  test('setState() changes the current state', () => {
    boundWidget.setState('The new Value');
    expect(document.querySelector('input').value).toBe('The new Value');
  });

  test('focus() focuses the text input', () => {
    boundWidget.focus();
    expect(document.activeElement).toBe(document.querySelector('input'));
  });
});

describe('telepath: wagtail.widgets.RadioSelect', () => {
  let boundWidget;

  beforeEach(() => {
    // Create a placeholder to render the widget
    document.body.innerHTML = '

';

    // Unpack and render a radio select widget
    const widgetDef = window.telepath.unpack({
      _type: 'wagtail.widgets.RadioSelect',
      _args: [
        `

            <input type="radio" name="__NAME__" value="tea" id="__ID___0"> Tea

            <input type="radio" name="__NAME__" value="coffee" id="__ID___1"> Coffee

`,
        '__ID___0'
      ]
    });
    boundWidget = widgetDef.render($('#placeholder'), 'the-name', 'the-id', 'tea');
  });

  test('it renders correctly', () => {
    expect(document.body.innerHTML).toMatchSnapshot();
    expect(document.querySelector('input[value="tea"]').checked).toBe(true);
    expect(document.querySelector('input[value="coffee"]').checked).toBe(false);
  });

  test('getValue() returns the current value', () => {
    expect(boundWidget.getValue()).toBe('tea');
  });

  test('getState() returns the current state', () => {
    expect(boundWidget.getState()).toBe('tea');
  });

  test('setState() changes the current state', () => {
    boundWidget.setState('coffee');
    expect(document.querySelector('input[value="tea"]').checked).toBe(false);
    expect(document.querySelector('input[value="coffee"]').checked).toBe(true);
  });

  test('focus() focuses the text input', () => {
    boundWidget.focus();

    // Note: This widget always focuses the last element
    expect(document.activeElement).toBe(document.querySelector('input[value="coffee"]'));
  });
});

describe('telepath: wagtail.widgets.PageChooser', () => {
  let boundWidget;

  beforeEach(() => {
    // Create a placeholder to render the widget
    document.body.innerHTML = '

';

    // Unpack and render a radio select widget
    const widgetDef = window.telepath.unpack({
      _type: 'wagtail.widgets.PageChooser',
      _args: [
        `

                <button type="button" class="button action-choose button-small button-secondary">
                  Choose another page
                </button>

                  Edit this page

            <button type="button" class="button action-choose button-small button-secondary">
              Choose a page
            </button>

        <input type="hidden" name="__NAME__" id="__ID__">`,
        '__ID__',
        {
          model_names: ['wagtailcore.page'],
          can_choose_root: false,
          user_perms: null
        }
      ]
    });
    boundWidget = widgetDef.render($('#placeholder'), 'the-name', 'the-id', {
      id: 60,
      parentId: 1,
      adminTitle: 'Welcome to the Wagtail Bakery!',
      editUrl: '/admin/pages/60/edit/'
    });
  });

  test('it renders correctly', () => {
    expect(document.body.innerHTML).toMatchSnapshot();
    expect(document.querySelector('input').value).toBe('60');
  });

  test('getValue() returns the current value', () => {
    expect(boundWidget.getValue()).toBe(60);
  });

  test('getState() returns the current state', () => {
    expect(boundWidget.getState()).toEqual({
      id: 60,
      parentId: 1,
      adminTitle: 'Welcome to the Wagtail Bakery!',
      editUrl: '/admin/pages/60/edit/'
    });
  });

  test('setState() changes the current page', () => {
    boundWidget.setState({
      id: 34,
      parentId: 3,
      adminTitle: 'Anadama',
      editUrl: '/admin/pages/34/edit/'
    });
    expect(document.body.innerHTML).toMatchSnapshot();
    expect(document.querySelector('input').value).toBe('34');
  });

  test('setState() to null clears the fields', () => {
    boundWidget.setState(null);
    expect(document.body.innerHTML).toMatchSnapshot();
    expect(document.querySelector('input').value).toBe('');
  });

  test('focus() focuses the input', () => {
    boundWidget.focus();

    // Note: This widget always focuses the unchosen button, even if it has a value
    expect(document.activeElement).toBe(document.querySelector('.unchosen button'));
  });
});

describe('telepath: wagtail.widgets.AdminAutoHeightTextInput', () => {
  let boundWidget;

  beforeEach(() => {
    window.autosize = jest.fn();

    // Create a placeholder to render the widget
    document.body.innerHTML = '

';

    // Unpack and render a textarea using the AdminAutoHeightTextInput widget
    const widgetDef = window.telepath.unpack({
      _type: 'wagtail.widgets.AdminAutoHeightTextInput',
      _args: [
        '<textarea name="__NAME__" cols="40" rows="1" id="__ID__"></textarea>',
        '__ID__'
      ]
    });
    boundWidget = widgetDef.render($('#placeholder'), 'the-name', 'the-id', 'The Value');
  });

  test('it renders correctly', () => {
    expect(document.body.innerHTML).toBe('<textarea name="the-name" cols="40" rows="1" id="the-id"></textarea>');
    expect(document.querySelector('textarea').value).toBe('The Value');
  });

  test('window.autosize was called', () => {
    expect(window.autosize.mock.calls.length).toBe(1);
    expect(window.autosize.mock.calls[0][0].get(0)).toBe(document.querySelector('textarea'));
  });

  test('getValue() returns the current value', () => {
    expect(boundWidget.getValue()).toBe('The Value');
  });

  test('getState() returns the current state', () => {
    expect(boundWidget.getState()).toBe('The Value');
  });

  test('setState() changes the current state', () => {
    boundWidget.setState('The new Value');
    expect(document.querySelector('textarea').value).toBe('The new Value');
  });

  test('focus() focuses the text input', () => {
    boundWidget.focus();
    expect(document.activeElement).toBe(document.querySelector('textarea'));
  });
});

describe('telepath: wagtail.widgets.DraftailRichTextArea', () => {
  let boundWidget;

  const TEST_VALUE = JSON.stringify({
    blocks: [{
      key: 't30wm',
      type: 'unstyled',
      depth: 0,
      text: 'Test Bold Italic',
      inlineStyleRanges: [{
        offset: 5,
        length: 4,
        style: 'BOLD'
      }, {
        offset: 10,
        length: 6,
        style: 'ITALIC'
      }],
      entityRanges: []
    }],
    entityMap: {}
  });

  beforeEach(() => {
    // Create a placeholder to render the widget
    document.body.innerHTML = '

';

    // Unpack and render a Draftail input
    const widgetDef = window.telepath.unpack({
      _type: 'wagtail.widgets.DraftailRichTextArea',
      _args: [{
        entityTypes: [{
          _dict: {
            type: 'LINK',
            icon: 'link',
            description: 'Link',
            attributes: ['url', 'id', 'parentId'],
            whitelist: {
              href: '^(http:|https:|undefined$)'
            }
          },
        }, {
          _dict: {
            type: 'IMAGE',
            icon: 'image',
            description: 'Image',
            attributes: ['id', 'src', 'alt', 'format'],
            whitelist: {
              id: true
            }
          },
        }],
        enableHorizontalRule: true,
        inlineStyles: [{
          _dict: {
            type: 'BOLD',
            icon: 'bold',
            description: 'Bold'
          },
        }, {
          _dict: {
            type: 'ITALIC',
            icon: 'italic',
            description: 'Italic'
          },
        }],
        blockTypes: [{
          _dict: {
            label: 'H2',
            type: 'header-two',
            description: 'Heading 2'
          },
        }]
      }]
    });
    boundWidget = widgetDef.render(document.getElementById('placeholder'), 'the-name', 'the-id', TEST_VALUE);
  });

  test('it renders correctly', () => {
    expect(document.querySelector('.Draftail-Editor__wrapper')).toBeTruthy();
    expect(document.querySelector('input').value).toBe(TEST_VALUE);
  });

  test('getValue() returns the current value', () => {
    expect(boundWidget.getValue()).toBe(TEST_VALUE);
  });

  test('getState() returns the current state', () => {
    expect(boundWidget.getState()).toBe(TEST_VALUE);
  });

  test('setState() changes the current state', () => {
    const NEW_VALUE = JSON.stringify({
      blocks: [{
        key: 't30wm',
        type: 'unstyled',
        depth: 0,
        text: 'New value',
        inlineStyleRanges: [],
        entityRanges: []
      }],
      entityMap: {}
    });

    expect(() => {
      boundWidget.setState(NEW_VALUE);
    }).toThrowError('DraftailRichTextArea.setState is not implemented');
  });

  test('focus() focuses the text input', () => {
    boundWidget.focus();
    expect(document.activeElement).toBe(document.querySelector('.public-DraftEditor-content'));
  });
});

describe('telepath: wagtail.widgets.DateInput', () => {
  let boundWidget;

  beforeEach(() => {
    window.initDateChooser = jest.fn();

    // Create a placeholder to render the widget
    document.body.innerHTML = '

';

    // Render
    const widgetDef = window.telepath.unpack({
      _type: 'wagtail.widgets.AdminDateInput',
      _args: [{
        dayOfWeekStart: 0,
        format: 'Y-m-d'
      }]
    });
    boundWidget = widgetDef.render($('#placeholder'), 'the-name', 'the-id', '2021-01-19');
  });

  test('it renders correctly', () => {
    expect(document.body.innerHTML).toBe('<input type="text" name="the-name" id="the-id">');
    expect(document.querySelector('input').value).toBe('2021-01-19');
  });

  test('window.initDateChooser was called', () => {
    expect(window.initDateChooser.mock.calls.length).toBe(1);
    expect(window.initDateChooser.mock.calls[0][0]).toBe('the-id');
    expect(window.initDateChooser.mock.calls[0][1]).toEqual({
      dayOfWeekStart: 0,
      format: 'Y-m-d'
    });
  });

  test('getValue() returns the current value', () => {
    expect(boundWidget.getValue()).toBe('2021-01-19');
  });

  test('getState() returns the current state', () => {
    expect(boundWidget.getState()).toBe('2021-01-19');
  });

  test('setState() changes the current state', () => {
    boundWidget.setState('2021-01-20');
    expect(document.querySelector('input').value).toBe('2021-01-20');
  });

  test('focus() focuses the input', () => {
    boundWidget.focus();
    expect(document.activeElement).toBe(document.querySelector('input'));
  });
});

describe('telepath: wagtail.widgets.TimeInput', () => {
  let boundWidget;

  beforeEach(() => {
    window.initTimeChooser = jest.fn();

    // Create a placeholder to render the widget
    document.body.innerHTML = '

';

    // Render
    const widgetDef = window.telepath.unpack({
      _type: 'wagtail.widgets.AdminTimeInput',
      _args: [{
        format: 'H:i',
        formatTime: 'H:i'
      }]
    });
    boundWidget = widgetDef.render($('#placeholder'), 'the-name', 'the-id', '11:59');
  });

  test('it renders correctly', () => {
    expect(document.body.innerHTML).toBe('<input type="text" name="the-name" id="the-id">');
    expect(document.querySelector('input').value).toBe('11:59');
  });

  test('window.initTimeChooser was called', () => {
    expect(window.initTimeChooser.mock.calls.length).toBe(1);
    expect(window.initTimeChooser.mock.calls[0][0]).toBe('the-id');
    expect(window.initTimeChooser.mock.calls[0][1]).toEqual({
      format: 'H:i',
      formatTime: 'H:i'
    });
  });

  test('getValue() returns the current value', () => {
    expect(boundWidget.getValue()).toBe('11:59');
  });

  test('getState() returns the current state', () => {
    expect(boundWidget.getState()).toBe('11:59');
  });

  test('setState() changes the current state', () => {
    boundWidget.setState('12:34');
    expect(document.querySelector('input').value).toBe('12:34');
  });

  test('focus() focuses the input', () => {
    boundWidget.focus();
    expect(document.activeElement).toBe(document.querySelector('input'));
  });
});

describe('telepath: wagtail.widgets.DateTimeInput', () => {
  let boundWidget;

  beforeEach(() => {
    window.initDateTimeChooser = jest.fn();

    // Create a placeholder to render the widget
    document.body.innerHTML = '

';

    // Render
    const widgetDef = window.telepath.unpack({
      _type: 'wagtail.widgets.AdminDateTimeInput',
      _args: [{
        dayOfWeekStart: 0,
        format: 'Y-m-d H:i',
        formatTime: 'H:i'
      }]
    });
    boundWidget = widgetDef.render($('#placeholder'), 'the-name', 'the-id', '2021-01-19 11:59');
  });

  test('it renders correctly', () => {
    expect(document.body.innerHTML).toBe('<input type="text" name="the-name" id="the-id">');
    expect(document.querySelector('input').value).toBe('2021-01-19 11:59');
  });

  test('window.initDateTimeChooser was called', () => {
    expect(window.initDateTimeChooser.mock.calls.length).toBe(1);
    expect(window.initDateTimeChooser.mock.calls[0][0]).toBe('the-id');
    expect(window.initDateTimeChooser.mock.calls[0][1]).toEqual({
      dayOfWeekStart: 0,
      format: 'Y-m-d H:i',
      formatTime: 'H:i'
    });
  });

  test('getValue() returns the current value', () => {
    expect(boundWidget.getValue()).toBe('2021-01-19 11:59');
  });

  test('getState() returns the current state', () => {
    expect(boundWidget.getState()).toBe('2021-01-19 11:59');
  });

  test('setState() changes the current state', () => {
    boundWidget.setState('2021-01-20 12:34');
    expect(document.querySelector('input').value).toBe('2021-01-20 12:34');
  });

  test('focus() focuses the input', () => {
    boundWidget.focus();
    expect(document.activeElement).toBe(document.querySelector('input'));
  });
});
<|endoftext|>


<commit_before>/**
 *
 * Validates and sends an imaging request for the selected instance.
 *
 */
Atmo.Views.RequestImagingForm = Backbone.View.extend({
	'tagName': 'div',
	'className' : 'imaging_form module',
	template: _.template(Atmo.Templates.request_imaging_form),
    events: {
        'submit .request_imaging_form' : 'send_request',
		'click #licensed_software' : 'certify_image'
    },
	initialize: function() {
        this.tagger = null;
	},
	render: function() {
		this.$el.html(this.template(this.model.toJSON()));
        var self = this;
        this.tagger = new Atmo.Views.Tagger({
            change: function(tags) {
                self.$el.find('.tag_input').val(tags.join(','));
            }
        });
        this.tagger.render().$el.prependTo(this.$el.find('.tagger_container'));

		// Populate cloud for deployment only with user's available providers

		// Populate the top menu with a provider switcher
		for (var i = 0; i < Atmo.identities.length; i++) {

			var identity = Atmo.identities.models[i];
			var name = Atmo.identities.models[i].get('provider').get('location');
            // Skip eucalyptus
            if (name.match(/eucalyptus/i))
                continue
			if (identity.get('selected'))
				this.$el.find('select[name="provider"]').prepend('<option value="' + identity.get('provider_id') + '">' + name + '</option>');
			else
				this.$el.find('select[name="provider"]').append('<option value="' + identity.get('provider_id') + '">' + name + '</option>');
		}

		return this;
	},
	certify_image: function(e) {

		if (this.$el.find('#licensed_software:checked').length == 1) {
			this.$el.find('#licensed_software').closest('.control-group').removeClass('error');
			this.$el.find('#licensed_software').closest('.controls').removeClass('alert-error').removeClass('alert');
		}
		else {
			this.$el.find('#licensed_software').closest('.control-group').addClass('error');
			this.$el.find('#licensed_software').closest('.controls').addClass('alert-error').addClass('alert');
		}

	},
    send_request: function(e) {
        var self = this;
        e.preventDefault();

	if (this.$el.find('#licensed_software:checked').length == 0) {
		// You shall not pass!
		this.$el.find('#licensed_software').closest('.control-group').addClass('error');
		this.$el.find('#licensed_software').closest('.controls').addClass('alert-error').addClass('alert');
		return false;
	}

        var form = this.$el.find('.request_imaging_form');
        var formData = form.serializeArray();

	var result = {};
        for(var i = 0; i < formData.length; i++){
		var data = formData[i];
		result[data.name] = data.value;
        }

        $.ajax({
            type: 'POST',
            url: Atmo.API_ROOT + '/provider/'+Atmo.profile.get('selected_identity').get('provider_id') + '/identity/' + Atmo.profile.get('selected_identity').id + '/request_image',
            data: JSON.stringify(result),
            dataType: 'json',
            contentType: 'application/json',
            success: function() {
                self.$el.find('.request_image_submit').val("Request Submitted!").attr("disabled", "disabled").click(function() { return false; });
            },
			error: function() {
				Atmo.Utils.notify("Could not submit request", 'If the problem persists, please email your request to support@iplantcollaborative.org', { no_timeout: true });
			},
            dataType: 'json'
        });

        return false;

    }
});
<commit_msg>Airport change to machine request error dialog<commit_after>/**
 *
 * Validates and sends an imaging request for the selected instance.
 *
 */
Atmo.Views.RequestImagingForm = Backbone.View.extend({
	'tagName': 'div',
	'className' : 'imaging_form module',
	template: _.template(Atmo.Templates.request_imaging_form),
    events: {
        'submit .request_imaging_form' : 'send_request',
		'click #licensed_software' : 'certify_image'
    },
	initialize: function() {
        this.tagger = null;
	},
	render: function() {
		this.$el.html(this.template(this.model.toJSON()));
        var self = this;
        this.tagger = new Atmo.Views.Tagger({
            change: function(tags) {
                self.$el.find('.tag_input').val(tags.join(','));
            }
        });
        this.tagger.render().$el.prependTo(this.$el.find('.tagger_container'));

		// Populate cloud for deployment only with user's available providers

		// Populate the top menu with a provider switcher
		for (var i = 0; i < Atmo.identities.length; i++) {

			var identity = Atmo.identities.models[i];
			var name = Atmo.identities.models[i].get('provider').get('location');
            // Skip eucalyptus
            if (name.match(/eucalyptus/i))
                continue
			if (identity.get('selected'))
				this.$el.find('select[name="provider"]').prepend('<option value="' + identity.get('provider_id') + '">' + name + '</option>');
			else
				this.$el.find('select[name="provider"]').append('<option value="' + identity.get('provider_id') + '">' + name + '</option>');
		}

		return this;
	},
	certify_image: function(e) {

		if (this.$el.find('#licensed_software:checked').length == 1) {
			this.$el.find('#licensed_software').closest('.control-group').removeClass('error');
			this.$el.find('#licensed_software').closest('.controls').removeClass('alert-error').removeClass('alert');
		}
		else {
			this.$el.find('#licensed_software').closest('.control-group').addClass('error');
			this.$el.find('#licensed_software').closest('.controls').addClass('alert-error').addClass('alert');
		}

	},
    send_request: function(e) {
        var self = this;
        e.preventDefault();

	if (this.$el.find('#licensed_software:checked').length == 0) {
		// You shall not pass!
		this.$el.find('#licensed_software').closest('.control-group').addClass('error');
		this.$el.find('#licensed_software').closest('.controls').addClass('alert-error').addClass('alert');
		return false;
	}

        var form = this.$el.find('.request_imaging_form');
        var formData = form.serializeArray();

	var result = {};
        for(var i = 0; i < formData.length; i++){
		var data = formData[i];
		result[data.name] = data.value;
        }

        $.ajax({
            type: 'POST',
            url: Atmo.API_ROOT + '/provider/'+Atmo.profile.get('selected_identity').get('provider_id') + '/identity/' + Atmo.profile.get('selected_identity').id + '/request_image',
            data: JSON.stringify(result),
            dataType: 'json',
            contentType: 'application/json',
            success: function() {
                self.$el.find('.request_image_submit').val("Request Submitted!").attr("disabled", "disabled").click(function() { return false; });
            },
			error: function(request, model, error) {
                Atmo.Utils.notifyErrors(request, 'Could not submit imaging request for the following reason(s):');
			},
            dataType: 'json'
        });

        return false;

    }
});
<|endoftext|>


<commit_before>import ConnectionDefinitionGenerator from './ConnectionDefinitionGenerator';
import StyleGenerator from './StyleGenerator'

function create(connections) {
  const defaultStyle = [
    {
      name: 'DefaultStyle',
    }
  ];

  const styleGenerator = new StyleGenerator(defaultStyle)
  const generator = new ConnectionDefinitionGenerator(connections, styleGenerator)
  return generator;
}

describe('createLabel', () => {

  test('with a shape without connections', () => {
    const generator = create({});

    expect(generator.getLabels('TestConnection')).toEqual([])
  })

  test('with empty connetions', () => {
    const generator = create({connections: []});

    expect(generator.getLabels('TestConnection')).toEqual([])
  })

  test('with one full defined connection and one placing', () => {
    const shapeJSON = {
      connections: [
        {
          "name": "TestConnection",
          "placings": [
            {
              "positionDistance": 1,
              "positionOffset": 1.0,
              "shape": {
                "textBody": "ExampleText",
                "id": 1234,
                "type": "text",
              }
            }
          ]
        }
      ]
    }

    const generator = create(shapeJSON);

    expect(generator.getLabels('TestConnection')).toEqual(
        [
          {
            position: 1.0,
            attrs: {
                rect: {fill: 'transparent'},
                text: {
                y: 1,
                text: "ExampleText"
                }
            },
            id: 1234
        }
      ]
    )
  })

});

describe('createPlacing', () => {

  test('with a shape without connections', () => {
    const generator = create({});

    expect(generator.getPlacings('TestConnection')).toEqual([])
  })

  test('with empty connetions', () => {
    const generator = create({connections: []});

    expect(generator.getPlacings('TestConnection')).toEqual([])
  })

  test('with a Line as Shape with a Style', () => {
    const shapeJSON = {
      connections: [
        {
          "name": "TestConnection",
          placings: [
            {
              "positionOffset": 0.5,
              "shape": {
                "endPoint": {
                  "x": 0,
                  "y": 0,
                },
                "startPoint": {
                  "x": 0,
                  "y": 0,
                },
                "style": "DefaultStyle",
                "type": "line",
              }
            }
          ]
        }
      ]
    }

    const generator = create(shapeJSON);

    expect(generator.getPlacings('TestConnection')).toEqual(
      [
        {
          position: 0.5,
          markup: '<line />',
          attrs: {
              x1: 0,
              y1: 0,
              x2: 0,
              y2: 0,
              "fill-opacity": 1,
              "stroke": "#000000",
              "stroke-dasharray": "0",
              "stroke-width": 0
          }
        }
    ])
  })
});

describe('getConnectionStyle', () => {

  test('with a shape without connections', () => {
    const generator = create({});

    expect(generator.getConnectionStyle('TestConnection')).toEqual({})
  })

  test('with empty connetions', () => {
    const generator = create({connections: []})

    expect(generator.getConnectionStyle('TestConnection')).toEqual({})
  })

  test('with an example Placing (Line)', () => {
    const shapeJSON = {
      connections: [
        {
          "name": "TestConnection",
          "placings": [
            {
              "positionOffset": 0.0,
              "shape": {
                "endPoint": {
                  "x": 1,
                  "y": 1,
                },
                "startPoint": {
                  "x": 0,
                  "y": 0,
                },
                "type": "line",
              }
            }
          ]
        }
      ]
    }

    const generator = create(shapeJSON);
    expect(generator.getConnectionStyle('TestConnection')).toEqual(
      {
        ".connection": {"stroke": "black"},
        ".marker-source": {
          "d": "M 0 0 L 1 1",
          "transform": "scale(1,1)"
        },
        ".marker-target": {"d": "M 0 0"}
      }
    )
  })

  test('a Connection without a Style', () => {
    const shapeJSON = {
      connections:  [
        {
          "name": "TestConnection"
        }
      ]
    }

    const generator = create(shapeJSON);
    expect(generator.getConnectionStyle('TestConnection')).toEqual({
      '.connection':{stroke: 'black'},
      '.marker-target': {"d": "M 0 0"}
    })
  })

  test('a Connection with a default Style', () => {
    const shapeJSON = {
      connections: [
        {
          "name": "TestConnection",
          "style": "DefaultStyle"
        }
      ]
    }

    const generator = create(shapeJSON);

    expect(generator.getConnectionStyle('TestConnection')).toEqual(
      {
        ".connection, .marker-target, .marker-source": {
          "fill-opacity": 1,
          "stroke": "#000000",
          "stroke-dasharray": "0",
          "stroke-width": 0,
          "dominant-baseline": "text-before-edge",
          "fill": "#000000",
          "font-family": "DefaultStyle",
          "font-size": "11",
          "font-weight": "normal"
        },
        ".marker-target": {"d": "M 0 0"},
        "fill-opacity": 1,
        "stroke": "#000000",
        "stroke-dasharray": "0",
        "stroke-width": 0,
        "text": {
          "dominant-baseline": "text-before-edge",
          "fill": "#000000",
          "font-family": "sans-serif",
          "font-size": "11",
          "font-weight": "normal"
        }
      }

    )
  })

  test('a Connection with a default Style and an example mirrored Placing (Line)', () => {

    const shapeJSON = {
      connections: [
        {
          "name": "TestConnection",
          "placings": [
            {
              "positionOffset": 1.0,
              "shape": {
                "endPoint": {
                  "x": 1,
                  "y": 1,
                },
                "startPoint": {
                  "x": 0,
                  "y": 0,
                },
                "type": "line",
                "style": "DefaultStyle"
              }
            }
          ]
        }
      ]
    }

    const generator = create(shapeJSON);

    expect(generator.getConnectionStyle('TestConnection')).toEqual(
      {
        ".connection": {"stroke": "black"},
        ".marker-target": {
          "d": "M 0 0 L 1 1",
          "fill-opacity": 1,
          "stroke": "#000000",
          "stroke-dasharray": "0",
          "stroke-width": 0,
          "text": {
            "dominant-baseline": "text-before-edge",
            "fill": "#000000",
            "font-family":"DefaultStyle",
            "font-size": "11",
            "font-weight":"normal"
          },
          "transform": "scale(1,1)"}
      }
    )
  })

  test('a Connection with a default Style and an example Placing (Line)', () => {

    const shapeJSON = {
        connections: [
        {
          "name": "TestConnection",
          "placings": [
            {
              "positionOffset": 0.0,
              "shape": {
                "endPoint": {
                  "x": 1,
                  "y": 1,
                },
                "startPoint": {
                  "x": 0,
                  "y": 0,
                },
                "type": "line",
                "style": "DefaultStyle"
              }
            }
          ]
        }
      ]
    }

    const generator = create(shapeJSON);

    expect(generator.getConnectionStyle('TestConnection')).toEqual(
      {
        ".connection": {"stroke": "black"},
        ".marker-source": {
          "d": "M 0 0 L 1 1",
          "fill-opacity": 1,
          "stroke": "#000000",
          "stroke-dasharray": "0",
          "stroke-width": 0,
          "text": {
            "dominant-baseline": "text-before-edge",
            "fill": "#000000",
            "font-family":"DefaultStyle",
            "font-size": "11",
            "font-weight":"normal"
          },
          "transform": "scale(1,1)"},
          ".marker-target": {"d": "M 0 0"}
      }
    )
  })
});<commit_msg>fix wrong tests<commit_after>import ConnectionDefinitionGenerator from './ConnectionDefinitionGenerator';
import StyleGenerator from './StyleGenerator'

function create(connections) {
  const defaultStyle = [
    {
      name: 'DefaultStyle',
    }
  ];

  const styleGenerator = new StyleGenerator(defaultStyle)
  const generator = new ConnectionDefinitionGenerator(connections, styleGenerator)
  return generator;
}

describe('createLabel', () => {

  test('with a shape without connections', () => {
    const generator = create({});

    expect(generator.getLabels('TestConnection')).toEqual([])
  })

  test('with empty connetions', () => {
    const generator = create({connections: []});

    expect(generator.getLabels('TestConnection')).toEqual([])
  })

  test('with one full defined connection and one placing', () => {
    const shapeJSON = {
      connections: [
        {
          "name": "TestConnection",
          "placings": [
            {
              "positionDistance": 1,
              "positionOffset": 1.0,
              "shape": {
                "textBody": "ExampleText",
                "id": 1234,
                "type": "text",
              }
            }
          ]
        }
      ]
    }

    const generator = create(shapeJSON);

    expect(generator.getLabels('TestConnection')).toEqual(
        [
          {
            position: 1.0,
            attrs: {
                rect: {fill: 'transparent'},
                text: {
                y: 1,
                text: "ExampleText"
                }
            },
            id: 1234
        }
      ]
    )
  })

});

describe('createPlacing', () => {

  test('with a shape without connections', () => {
    const generator = create({});

    expect(generator.getPlacings('TestConnection')).toEqual([])
  })

  test('with empty connetions', () => {
    const generator = create({connections: []});

    expect(generator.getPlacings('TestConnection')).toEqual([])
  })

  test('with a Line as Shape with a Style', () => {
    const shapeJSON = {
      connections: [
        {
          "name": "TestConnection",
          placings: [
            {
              "positionOffset": 0.5,
              "shape": {
                "endPoint": {
                  "x": 0,
                  "y": 0,
                },
                "startPoint": {
                  "x": 0,
                  "y": 0,
                },
                "style": "DefaultStyle",
                "type": "line",
              }
            }
          ]
        }
      ]
    }

    const generator = create(shapeJSON);

    expect(generator.getPlacings('TestConnection')).toEqual(
      [
        {
          position: 0.5,
          markup: '<line />',
          attrs: {
              x1: 0,
              y1: 0,
              x2: 0,
              y2: 0,
              "fill-opacity": 1,
              "stroke": "#000000",
              "stroke-dasharray": "0",
              "stroke-width": 0
          }
        }
    ])
  })
});

describe('getConnectionStyle', () => {

  test('with a shape without connections', () => {
    const generator = create({});

    expect(generator.getConnectionStyle('TestConnection')).toEqual({})
  })

  test('with empty connetions', () => {
    const generator = create({connections: []})

    expect(generator.getConnectionStyle('TestConnection')).toEqual({})
  })

  test('with an example Placing (Line)', () => {
    const shapeJSON = {
      connections: [
        {
          "name": "TestConnection",
          "placings": [
            {
              "positionOffset": 0.0,
              "shape": {
                "endPoint": {
                  "x": 1,
                  "y": 1,
                },
                "startPoint": {
                  "x": 0,
                  "y": 0,
                },
                "type": "line",
              }
            }
          ]
        }
      ]
    }

    const generator = create(shapeJSON);
    expect(generator.getConnectionStyle('TestConnection')).toEqual(
      {
        ".connection": {"stroke": "black"},
        ".marker-source": {
          "d": "M 0 0 L 1 1",
          "transform": "scale(1,1)"
        },
        ".marker-target": {"d": "M 0 0"}
      }
    )
  })

  test('a Connection without a Style', () => {
    const shapeJSON = {
      connections:  [
        {
          "name": "TestConnection"
        }
      ]
    }

    const generator = create(shapeJSON);
    expect(generator.getConnectionStyle('TestConnection')).toEqual({
      '.connection':{stroke: 'black'},
      '.marker-target': {"d": "M 0 0"}
    })
  })

  test('a Connection with a default Style', () => {
    const shapeJSON = {
      connections: [
        {
          "name": "TestConnection",
          "style": "DefaultStyle"
        }
      ]
    }

    const generator = create(shapeJSON);

    expect(generator.getConnectionStyle('TestConnection')).toEqual(
      {
        ".connection, .marker-target, .marker-source": {
          "fill-opacity": 1,
          "stroke": "#000000",
          "stroke-dasharray": "0",
          "stroke-width": 0,
          "dominant-baseline": "text-before-edge",
          "fill": "#000000",
          "font-family": "sans-serif",
          "font-size": "11",
          "font-weight": "normal"
        },
        ".marker-target": {"d": "M 0 0"},
        "fill-opacity": 1,
        "stroke": "#000000",
        "stroke-dasharray": "0",
        "stroke-width": 0,
        "text": {
          "dominant-baseline": "text-before-edge",
          "fill": "#000000",
          "font-family": "sans-serif",
          "font-size": "11",
          "font-weight": "normal"
        }
      }

    )
  })

  test('a Connection with a default Style and an example mirrored Placing (Line)', () => {

    const shapeJSON = {
      connections: [
        {
          "name": "TestConnection",
          "placings": [
            {
              "positionOffset": 1.0,
              "shape": {
                "endPoint": {
                  "x": 1,
                  "y": 1,
                },
                "startPoint": {
                  "x": 0,
                  "y": 0,
                },
                "type": "line",
                "style": "DefaultStyle"
              }
            }
          ]
        }
      ]
    }

    const generator = create(shapeJSON);

    expect(generator.getConnectionStyle('TestConnection')).toEqual(
      {
        ".connection": {"stroke": "black"},
        ".marker-target": {
          "d": "M 0 0 L 1 1",
          "fill-opacity": 1,
          "stroke": "#000000",
          "stroke-dasharray": "0",
          "stroke-width": 0,
          "text": {
            "dominant-baseline": "text-before-edge",
            "fill": "#000000",
            "font-family":"sans-serif",
            "font-size": "11",
            "font-weight":"normal"
          },
          "transform": "scale(1,1)"}
      }
    )
  })

  test('a Connection with a default Style and an example Placing (Line)', () => {

    const shapeJSON = {
        connections: [
        {
          "name": "TestConnection",
          "placings": [
            {
              "positionOffset": 0.0,
              "shape": {
                "endPoint": {
                  "x": 1,
                  "y": 1,
                },
                "startPoint": {
                  "x": 0,
                  "y": 0,
                },
                "type": "line",
                "style": "DefaultStyle"
              }
            }
          ]
        }
      ]
    }

    const generator = create(shapeJSON);

    expect(generator.getConnectionStyle('TestConnection')).toEqual(
      {
        ".connection": {"stroke": "black"},
        ".marker-source": {
          "d": "M 0 0 L 1 1",
          "fill-opacity": 1,
          "stroke": "#000000",
          "stroke-dasharray": "0",
          "stroke-width": 0,
          "text": {
            "dominant-baseline": "text-before-edge",
            "fill": "#000000",
            "font-family":"sans-serif",
            "font-size": "11",
            "font-weight":"normal"
          },
          "transform": "scale(1,1)"},
          ".marker-target": {"d": "M 0 0"}
      }
    )
  })
});<|endoftext|>