<commit_before>'use strict';

/*  user map direcitve */

angular.module('ten20Angular').
  directive('userConsole', ['$window', function($window) {
    return {
			templateUrl: '/templates/userConsole.html',
			restrict: 'A',
			replace: true,
      link: function(scope, element, attrs) {
        // enable toolbox to off canvas in small screens;
        scope.toggleTB = function(action) {
          if (action === 'on') {
            element.children('#map').addClass('off-canvas');
          } else if (action === 'off') {
            element.children('#map').removeClass('off-canvas');
          } else {
            element.children('#map').toggleClass('off-canvas');
          }
          //scope.$broadcast('ResizeMap');
        };
        // bind tracker accordion click to update tracker data
        element.delegate('.panel-heading a', 'click', function(e) {
          var panelScope = $(e.target).parents('.panel').scope();

          if (panelScope.isopen) {
            scope.refreshTracker(panelScope.tracker);
          }
        });

        // bind tracker tab click to update tracker recent or trip
        element.delegate('.nav-tabs a', 'click', function(e) {
          var tracker = $(e.target).parents('.panel').scope().tracker;
          var infoTab = $(e.currentTarget).parent().hasClass('info-tab');

          if (infoTab) {
            tracker.tripActive = false;
            scope.recentMsg(tracker);
          } else {
            tracker.tripActive = true;
            scope.loadTrips(tracker, true);
          }
        });

        // make tool box draggable
        var toolbox = element.find('.tool-box')[0];
        var handle = element.find('.tool-box .time-weather')[0];
        // enable drag on big screens
        if ($window.innerWidth > 767) {
          draggable(toolbox, handle);
        }
      }
    };
  }]).
  directive('userMap', function($timeout) {
    return {
			restrict: 'A',
      scope: true,
      controller: ['$scope', '$element', '$attrs', function($scope, $element, $attrs) {
        // init trackers
        function _initTrackers() {
          var bounds = [];
          // check whether user has trackers
          if ($scope.trackers.length === 0) {
            return;
          }

          for (var i = 0; i < $scope.trackers.length; i++) {
            if ($scope.trackers[i].lastMessage &&
                $scope.trackers[i].lastMessage.location) {
              bounds.push([
                $scope.trackers[i].lastMessage.location.latitude,
                $scope.trackers[i].lastMessage.location.longitude
              ]);
              $scope.userMap.updateTracker($scope.trackers[i], true);
            }
          };

          $scope.userMap.map.fitBounds(bounds, {
            paddingTopLeft: L.point(100, 100),
            paddingBottomRight: L.point(350, 350)
          });
        }

        // init map
        function _initMap() {
          var params;

          // fallback to hard-code location
          params = {
            "lat": 0,
            "lng": 0,
            "zoomLevel": 6,
            "zoomControl":true,
            "layers":[
              {
                "label":"Map",
                "tileLayer":"alexbirkett.map-bugector"
              },
              {
                "label":"Satellite",
                "tileLayer":"alexbirkett.map-t0fodlre"
              }
            ]
          };

          $scope.userMap = new ten20.UserMap($attrs.id, params);

          // bind map zoom event
          $scope.userMap.map.on('zoomend', function() {
            if ($scope.activeTracker) {
              $scope.userMap.updatePath($scope.activeTracker, false);
            }
          });
        }

        _initMap();
        $scope.$on('InitTrackers', _initTrackers);
        $scope.$on('TrackerUpdate', _updateTracker);
        $scope.$on('FocusTracker', _focusTracker);
        $scope.$on('PathUpdate', _updatePath);
        $scope.$on('ResizeMap', function() {
          $scope.userMap.map.invalidateSize();
        });

        // center map to tracker location
        function _focusTracker(e, t) {
          $scope.userMap.updateTracker(t, true);
        }

        function _updateTracker(e, t) {
          $scope.userMap.updateTracker(t);
        }

        // show recent or trip msg as path on map for a tracker
        function _updatePath(e, t, quiet) {
          if (t.path && t.path.length !== 0) {
            $scope.userMap.updatePath(t, quiet);
          }
        }

      }],
      link: function(scope, elem, attrs) {
        // bind accordion click, set active tracker
      }
    };
  });
<commit_msg>guard against invalid location messages<commit_after>'use strict';

/*  user map direcitve */

angular.module('ten20Angular').
  directive('userConsole', ['$window', function($window) {
    return {
			templateUrl: '/templates/userConsole.html',
			restrict: 'A',
			replace: true,
      link: function(scope, element, attrs) {
        // enable toolbox to off canvas in small screens;
        scope.toggleTB = function(action) {
          if (action === 'on') {
            element.children('#map').addClass('off-canvas');
          } else if (action === 'off') {
            element.children('#map').removeClass('off-canvas');
          } else {
            element.children('#map').toggleClass('off-canvas');
          }
          //scope.$broadcast('ResizeMap');
        };
        // bind tracker accordion click to update tracker data
        element.delegate('.panel-heading a', 'click', function(e) {
          var panelScope = $(e.target).parents('.panel').scope();

          if (panelScope.isopen) {
            scope.refreshTracker(panelScope.tracker);
          }
        });

        // bind tracker tab click to update tracker recent or trip
        element.delegate('.nav-tabs a', 'click', function(e) {
          var tracker = $(e.target).parents('.panel').scope().tracker;
          var infoTab = $(e.currentTarget).parent().hasClass('info-tab');

          if (infoTab) {
            tracker.tripActive = false;
            scope.recentMsg(tracker);
          } else {
            tracker.tripActive = true;
            scope.loadTrips(tracker, true);
          }
        });

        // make tool box draggable
        var toolbox = element.find('.tool-box')[0];
        var handle = element.find('.tool-box .time-weather')[0];
        // enable drag on big screens
        if ($window.innerWidth > 767) {
          draggable(toolbox, handle);
        }
      }
    };
  }]).
  directive('userMap', function($timeout) {
    return {
			restrict: 'A',
      scope: true,
      controller: ['$scope', '$element', '$attrs', function($scope, $element, $attrs) {
        // init trackers
        function _initTrackers() {
          var bounds = [];
          // check whether user has trackers
          if ($scope.trackers.length === 0) {
            return;
          }

          for (var i = 0; i < $scope.trackers.length; i++) {
            if ($scope.trackers[i].lastMessage &&
                $scope.trackers[i].lastMessage.location &&
                $scope.trackers[i].lastMessage.location.latitude) {
              bounds.push([
                $scope.trackers[i].lastMessage.location.latitude,
                $scope.trackers[i].lastMessage.location.longitude
              ]);
              $scope.userMap.updateTracker($scope.trackers[i], true);
            }
          };

          $scope.userMap.map.fitBounds(bounds, {
            paddingTopLeft: L.point(100, 100),
            paddingBottomRight: L.point(350, 350)
          });
        }

        // init map
        function _initMap() {
          var params;

          // fallback to hard-code location
          params = {
            "lat": 0,
            "lng": 0,
            "zoomLevel": 6,
            "zoomControl":true,
            "layers":[
              {
                "label":"Map",
                "tileLayer":"alexbirkett.map-bugector"
              },
              {
                "label":"Satellite",
                "tileLayer":"alexbirkett.map-t0fodlre"
              }
            ]
          };

          $scope.userMap = new ten20.UserMap($attrs.id, params);

          // bind map zoom event
          $scope.userMap.map.on('zoomend', function() {
            if ($scope.activeTracker) {
              $scope.userMap.updatePath($scope.activeTracker, false);
            }
          });
        }

        _initMap();
        $scope.$on('InitTrackers', _initTrackers);
        $scope.$on('TrackerUpdate', _updateTracker);
        $scope.$on('FocusTracker', _focusTracker);
        $scope.$on('PathUpdate', _updatePath);
        $scope.$on('ResizeMap', function() {
          $scope.userMap.map.invalidateSize();
        });

        // center map to tracker location
        function _focusTracker(e, t) {
          if (t.lastMessage && t.lastMessage.location &&
              t.lastMessage.location.latitude) {
                $scope.userMap.updateTracker(t, true);
          }
        }

        function _updateTracker(e, t) {
          if (t.lastMessage && t.lastMessage.location &&
              t.lastMessage.location.latitude) {
                $scope.userMap.updateTracker(t);
          }
        }

        // show recent or trip msg as path on map for a tracker
        function _updatePath(e, t, quiet) {
          if (t.path && t.path.length !== 0) {
            $scope.userMap.updatePath(t, quiet);
          }
        }

      }],
      link: function(scope, elem, attrs) {
        // bind accordion click, set active tracker
      }
    };
  });
<|endoftext|>


<commit_before>// Category View
// =============

// Includes file dependencies
define([
	"jquery",
	"backbone",
], function( $, Backbone ) {

    // Extends Backbone.View
    var View = Backbone.View.extend({

        // The View Constructor
        initialize: function (options) {
            _.bindAll(this, "remove", "update_value", "save_clicked");

            this.redirectRemove = options.redirectRemove || "#characters?all";
            this.redirectRemove = _.template(this.redirectRemove);
            this.redirectSave = options.redirectSave || "#character?<%= self.model.id %>";
            this.redirectSave = _.template(this.redirectSave);
        },

        events: {
            "click .cancel": "cancel",
            "change": "update_value",
            "click .save": "save_clicked"
        },

        cancel: function(a, b, c) {
            var self = this;
            $.mobile.loading("show");
            window.location.hash = self.redirectRemove({"self": self});

            return false;
        },

        update_value: function(a, b, c) {
            var self = this;
            var v = this.$(a.target).val();
            this.model.set("name", v);
        },

        save_clicked: function(a, b, c) {
            var self = this;
            var v = self.$el.find('input[name="characterName"]').val();
            self.model.save({name: v, owner: Parse.User.current(), change_count: 0}).then(function() {
                window.location.hash = self.redirectSave({"self": self});
            }, function(error) {
                console.log("Failed to save a character", error);
            })
            return false;
        },

        // Renders all of the Category models on the UI
        render: function() {

            // Sets the view's template property
            this.template = _.template( $( "script#characterNewView" ).html())({ "model": this.model } );

            // Renders the view's template inside of the current listview element
            this.$el.find("div[role='main']").html(this.template);

            this.$el.enhanceWithin();

            // Maintains chainability
            return this;

        }

    } );

    // Returns the View class
    return View;

} );<commit_msg>Accept enter on character creation screen<commit_after>// Category View
// =============

// Includes file dependencies
define([
	"jquery",
	"backbone",
], function( $, Backbone ) {

    // Extends Backbone.View
    var View = Backbone.View.extend({

        // The View Constructor
        initialize: function (options) {
            _.bindAll(this, "remove", "update_value", "save_clicked");

            this.redirectRemove = options.redirectRemove || "#characters?all";
            this.redirectRemove = _.template(this.redirectRemove);
            this.redirectSave = options.redirectSave || "#character?<%= self.model.id %>";
            this.redirectSave = _.template(this.redirectSave);
        },

        events: {
            "click .cancel": "cancel",
            "change": "update_value",
            "click .save": "save_clicked",
            "submit": "save_clicked"
        },

        cancel: function(a, b, c) {
            var self = this;
            $.mobile.loading("show");
            window.location.hash = self.redirectRemove({"self": self});

            return false;
        },

        update_value: function(a, b, c) {
            var self = this;
            var v = this.$(a.target).val();
            this.model.set("name", v);
        },

        save_clicked: function(a, b, c) {
            var self = this;
            var v = self.$el.find('input[name="characterName"]').val();
            self.model.save({name: v, owner: Parse.User.current(), change_count: 0}).then(function() {
                window.location.hash = self.redirectSave({"self": self});
            }, function(error) {
                console.log("Failed to save a character", error);
            })
            return false;
        },

        // Renders all of the Category models on the UI
        render: function() {

            // Sets the view's template property
            this.template = _.template( $( "script#characterNewView" ).html())({ "model": this.model } );

            // Renders the view's template inside of the current listview element
            this.$el.find("div[role='main']").html(this.template);

            this.$el.enhanceWithin();

            // Maintains chainability
            return this;

        }

    } );

    // Returns the View class
    return View;

} );<|endoftext|>


<commit_before>/**
 * Fittable application
 *
 * This is the main javascript file for fittable app.
 * Implements callbacks using Sirius API as data source. Then initializes the fittable widget.
 *
 * @author      Marián Hlaváč
 * @version     1.0
 */

import ReactCookie from 'react-cookie'
import URL from 'url'
import R from 'ramda'

const emptyObject = (obj) => R.is(Object, obj) && R.pipe(R.keys, R.propEq('length', 0))

/**
 * Fittable widget instance
 */
var f

/**
 * Main application parameter, specifying the view
 * Choices are: person, room, course
 * @type {string}
 */
var view = 'person'

/**
 * Parameter for the selected view. Used for specifying the room or course.
 * @type {string}
 */
var parameter = ''

/**
 * Logged user's credentials
 * @type {{name: string, token: string}}
 */
var user = {
  name: ReactCookie.load('oauth_username'),
  token: ReactCookie.load('oauth_access_token'),
}

/**
 * URL of proxy for Sirius API
 * @type {string}
 */
var siriusAPIUrl = `${getBaseUri()}/_proxy/api/v1/`

/**
 * Currently selected application language setting
 * @type {string}
 */
var appLocale = 'cs'

var viewPaths = {
  course: 'courses',
  person: 'people',
  room: 'rooms',
}

// TODO: This should be removed!
var defaultLimit = 200

var STATUS_ERROR_TYPES = {
  0: 'connection',
  401: 'unauthorized',
  403: 'access',
  404: 'notfound',
  500: 'servererror'
}
function generateError (status, message = 'No message specified') {
  const error = new Error(message)
  if (status in STATUS_ERROR_TYPES) {
    error.type = STATUS_ERROR_TYPES[status]
    if (error.type === 'notfound' && view === 'person' && parameter === user.name) {
      error.type = 'own' + error.type
    }
  } else {
    error.type = 'generic'
  }
  return error
}

/**
 * @return {string} a base URI (aka relative URL root) of this site with
 * trailing slash omitted.
 */
function getBaseUri () {
  var baseUri = document.baseURI

  // IE doesn't support baseURI, workaround
  if (typeof baseURI === 'undefined') {
    var baseTag = document.getElementsByTagName("base")[0]
    baseUri = baseTag.href
  }

  return URL.parse(baseUri).pathname.replace(/\/$/, '')
}

function changeView (newView, newParam) {
  // Set new view
  view = newView
  parameter = newParam
}

/**
 * Checks the user variable, if it's valid logged user.
 * @returns {bool}
 */
function isUserLoggedIn () {
  return (user.name && user.token)
}

function makeRequest (parameters) {
  var requestUrl = siriusAPIUrl

  requestUrl += parameters

  var request = new XMLHttpRequest()
  request.open('GET', encodeURI(requestUrl), true)
  request.send(null)

  return request
}

/**
 * Data callback, requesting the events from Sirius API, depending on view type and range.
 * @param params   Object with request parameters
 * @param callback Callback to be called after successful request
 */
function dataCallback ({calendarType, dateFrom, dateTo, calendarId}, callback) {
  // FIXME: until `me` is a valid shortcut on Sirius
  if (calendarId === 'me' && calendarType === 'people') {
    calendarId = user.name
  }

  const path = `${calendarType}/${calendarId}/events` +
    `?from=${dateFrom}&to=${dateTo}&limit=${defaultLimit}` +
    `&include=courses,teachers,schedule_exceptions&deleted=true`

  // Make the request
  const request = makeRequest(path)

  request.onreadystatechange = function (callback, fittable) {
    if (request.readyState === XMLHttpRequest.DONE) {
      if (request.status === 200) {
        // Request successful
        var ajaxresult = JSON.parse(request.responseText)
        var itemCount = ajaxresult.meta.count

        var linknames = { teachers: [], courses: [], exceptions: [] }

        const responseEvents = ajaxresult.events || []
        const data = responseEvents.map(event => {
          // And add new event to array
          const newEvent = {
            id: event.id,
            name: event.name,
            course: event.links.course,
            startsAt: event.starts_at,
            endsAt: event.ends_at,
            sequenceNumber: event.sequence_number,
            type: event.event_type,
            room: event.links.room,
            flag: null,
            notification: false,
            cancelled: event.deleted,
            replacement: false,
            teachers: event.links.teachers,
            details: {
              students: event.links.students,
              capacity: event.capacity,
              parallel: event.parallel,
              appliedExceptions: event.links.applied_exceptions,
            },
          }

          // If the original data are present, insert one reverted event
          if (!emptyObject(event.original_data)) {
            // Convert times to milliseconds
            var rangeFromMs = (new Date(dateFrom)).getMilliseconds()
            var rangeToMs = (new Date(dateTo)).getMilliseconds()
            var originalFromMs = (new Date(event.original_data.starts_at)).getMilliseconds()

            // Check if the original start is between the range
            if (rangeFromMs <= originalFromMs && originalFromMs >= rangeToMs) {
              // The event is cancelled, show with original data
              newEvent.startsAt = event.original_data.starts_at
              newEvent.endsAt = event.original_data.ends_at
              newEvent.room = event.original_data.room_id
              newEvent.cancelled = true
              newEvent.replacedAt = event.starts_at
            } else {
              // The event is replacement
              newEvent.replacement = true
              newEvent.replaces = event.original_data.starts_at
            }
          }
          return newEvent
        })

        // Add teachers links full names
        if ('linked' in ajaxresult) {
          if ('teachers' in ajaxresult.linked) {
            for (let i = 0; i < ajaxresult.linked.teachers.length; i++) {
              // Add teacher link full name
              linknames.teachers.push({
                id: ajaxresult.linked.teachers[i].id,
                name: {
                  cs: ajaxresult.linked.teachers[i].full_name,
                  en: ajaxresult.linked.teachers[i].full_name,
                },
              })
            }
          }

          // Add courses links full names
          if ('courses' in ajaxresult.linked) {
            for (let i = 0; i < ajaxresult.linked.courses.length; i++) {
              // Add course link full name
              linknames.courses.push({
                id: ajaxresult.linked.courses[i].id,
                name: {
                  cs: ajaxresult.linked.courses[i].name.cs,
                  en: ajaxresult.linked.courses[i].name.en,
                },
              })
            }
          }

          // Add exceptions links full names
          if ('schedule_exceptions' in ajaxresult.linked) {
            for (let i = 0; i < ajaxresult.linked.schedule_exceptions.length; i++) {
              // Add exceptions link full name
              linknames.exceptions.push({
                id: ajaxresult.linked.schedule_exceptions[i].id,
                type: ajaxresult.linked.schedule_exceptions[i].exception_type,
                name: ajaxresult.linked.schedule_exceptions[i].name,
              })
            }
          }
        }

        // Send data to fittable
        callback(null, {events: data, linkNames: linknames})
      } else {
        // Request failed
        callback(generateError(request.status, 'dataCallback failed'))
      }
    }
  }.bind(null, callback, f)
}

/**
 * Search callback, returning search results from Sirius API.
 * @param query
 * @param callback
 */
var searchCallback = function (query, callback) {

  // Construct the request URL
  var request = makeRequest('search?q=' + query + '&limit=' + defaultLimit)

  request.onreadystatechange = function (callback, fittable) {
    if (request.readyState === XMLHttpRequest.DONE) {
      if (request.status === 200) {
        // Request successful
        var ajaxresult = JSON.parse(request.responseText)

        // Send data to fittable
        callback(ajaxresult.results)
      } else {
        // Request failed
        fittable.onError(generateError(request.status).type)
      }
    }
  }.bind(null, callback, f)
}

var dateChangeCallback = function (newdate, newsemester) {
  console.log(newdate, newsemester)
  // Display semester name in subheading
  updateTitle(null, newsemester)
}

var semesterDataCallback = function (callback) {

  // Construct the request URL
  var request = makeRequest('semesters?limit=' + defaultLimit)

  request.onreadystatechange = function (callback, fittable) {
    if (request.readyState === XMLHttpRequest.DONE) {
      if (request.status === 200) {
        // Request successful
        var ajaxresult = JSON.parse(request.responseText)
        var itemCount = ajaxresult.meta.count

        // Check if there is semesters object in result
        if (!('semesters' in ajaxresult)) {
          return false
        }

        var semesters = []

        // Create events from data
        for (var i = 0; i < itemCount; i++) {
          var semester = ajaxresult.semesters[i]

          // And add new semester to array
          semesters[ i ] = {
            id: semester.id,
            semester: semester.semester,
            faculty: semester.faculty,
            startsAt: semester.starts_at,
            endsAt: semester.ends_at,
            examsStartsAt: semester.exams_start_at,
            examsEndsAt: semester.exams_end_at,
            hourDuration: semester.hour_duration,
            breakDuration: 15,  // FIXME: replace this and that two below with semester.hourStarts
            dayStartsAtHour: 7.5,
            dayEndsAtHour: 21.25
          }
        }

        // Send semester data to fittable
        callback(semesters)
      } else {
        // Request failed
        fittable.onError(generateError(request.status).type)
      }
    }
  }.bind(null, callback, f)
}

var settingsChangeCallback = function (settings) {

  // We really don't want to save the user property
  settings.user = null

  // Save settings
  window.localStorage.setItem(user.name + '.settings', JSON.stringify(settings))

  // Update appLocale
  appLocale = settings.locale

  // Update title and subtitle for possible locale change
  updateTitle(view === 'person' && parameter === user.name ?
    viewNames[appLocale]['personal'] : viewNames[appLocale][view] + ' ' + parameter, null)
}

/**
 * --- Initialize the widget ---
 */

function viewChangeCallback (view, param) {
  console.error('viewChangeCallback fired!')
}

// If the user is not logged in, redirect him to the landing page
if (!isUserLoggedIn()) {
  window.location.href = 'landing.html'

} else {
  // Prepare the options object with default values
  var options = {
    locale: 'cs',
  }

  // Load settings from localStorage
  var save = window.localStorage.getItem(user.name + '.settings')
  if (save !== null) {
    var usersettings = JSON.parse(save)

    for (var key in usersettings) {
      options[key] = usersettings[key]
    }
  }

  // Set user and callbacks
  options.username = user.name
  options.usertoken = user.token
  options.callbacks = {
    data: dataCallback,
    search: searchCallback,

    dateChange: dateChangeCallback,
    semesterData: semesterDataCallback,
    settingsChange: settingsChangeCallback
  }

  // Get app locale
  appLocale = options.locale
}

function userCallback (cb) {
  const request = makeRequest(`people/${user.name}`)

  request.onreadystatechange = (callback, fittable) => {
    if (request.readyState === XMLHttpRequest.DONE) {
      if (request.status === 200) {
        // Request successful
        const rawData = JSON.parse(request.responseText)

        if (!rawData || !rawData.people) {
          cb(generateError('generic'))
          return
        }

        const rawUser = rawData.people

        const data = {
          publicAccessToken: rawUser['access_token'],
          id: rawUser.id,
          name: rawUser.name,
        }

        cb(null, data)
      } else {
        // Request failed
        cb(generateError(request.status).type)
      }
    }
  }
}

export {
  dataCallback as data,
  searchCallback as search,
  dateChangeCallback as dateChange,
  semesterDataCallback as semesterData,
  settingsChangeCallback as settingsChange,
  viewChangeCallback as viewChange,
  userCallback as user,
}
<commit_msg>Use proxy as Sirius API url<commit_after>/**
 * Fittable application
 *
 * This is the main javascript file for fittable app.
 * Implements callbacks using Sirius API as data source. Then initializes the fittable widget.
 *
 * @author      Marián Hlaváč
 * @version     1.0
 */

import ReactCookie from 'react-cookie'
import URL from 'url'
import R from 'ramda'

import { SIRIUS_PROXY_PATH } from '../config'

const emptyObject = (obj) => R.is(Object, obj) && R.pipe(R.keys, R.propEq('length', 0))

/**
 * Fittable widget instance
 */
var f

/**
 * Main application parameter, specifying the view
 * Choices are: person, room, course
 * @type {string}
 */
var view = 'person'

/**
 * Parameter for the selected view. Used for specifying the room or course.
 * @type {string}
 */
var parameter = ''

/**
 * Logged user's credentials
 * @type {{name: string, token: string}}
 */
var user = {
  name: ReactCookie.load('oauth_username'),
  token: ReactCookie.load('oauth_access_token'),
}

/**
 * URL of proxy for Sirius API
 * @type {string}
 */
var siriusAPIUrl = `${getBaseUri()}${SIRIUS_PROXY_PATH}/`

/**
 * Currently selected application language setting
 * @type {string}
 */
var appLocale = 'cs'

var viewPaths = {
  course: 'courses',
  person: 'people',
  room: 'rooms',
}

// TODO: This should be removed!
var defaultLimit = 200

var STATUS_ERROR_TYPES = {
  0: 'connection',
  401: 'unauthorized',
  403: 'access',
  404: 'notfound',
  500: 'servererror'
}
function generateError (status, message = 'No message specified') {
  const error = new Error(message)
  if (status in STATUS_ERROR_TYPES) {
    error.type = STATUS_ERROR_TYPES[status]
    if (error.type === 'notfound' && view === 'person' && parameter === user.name) {
      error.type = 'own' + error.type
    }
  } else {
    error.type = 'generic'
  }
  return error
}

/**
 * @return {string} a base URI (aka relative URL root) of this site with
 * trailing slash omitted.
 */
function getBaseUri () {
  var baseUri = document.baseURI

  // IE doesn't support baseURI, workaround
  if (typeof baseURI === 'undefined') {
    var baseTag = document.getElementsByTagName("base")[0]
    baseUri = baseTag.href
  }

  return URL.parse(baseUri).pathname.replace(/\/$/, '')
}

function changeView (newView, newParam) {
  // Set new view
  view = newView
  parameter = newParam
}

/**
 * Checks the user variable, if it's valid logged user.
 * @returns {bool}
 */
function isUserLoggedIn () {
  return (user.name && user.token)
}

function makeRequest (parameters) {
  var requestUrl = siriusAPIUrl

  requestUrl += parameters

  var request = new XMLHttpRequest()
  request.open('GET', encodeURI(requestUrl), true)
  request.send(null)

  return request
}

/**
 * Data callback, requesting the events from Sirius API, depending on view type and range.
 * @param params   Object with request parameters
 * @param callback Callback to be called after successful request
 */
function dataCallback ({calendarType, dateFrom, dateTo, calendarId}, callback) {
  // FIXME: until `me` is a valid shortcut on Sirius
  if (calendarId === 'me' && calendarType === 'people') {
    calendarId = user.name
  }

  const path = `${calendarType}/${calendarId}/events` +
    `?from=${dateFrom}&to=${dateTo}&limit=${defaultLimit}` +
    `&include=courses,teachers,schedule_exceptions&deleted=true`

  // Make the request
  const request = makeRequest(path)

  request.onreadystatechange = function (callback, fittable) {
    if (request.readyState === XMLHttpRequest.DONE) {
      if (request.status === 200) {
        // Request successful
        var ajaxresult = JSON.parse(request.responseText)
        var itemCount = ajaxresult.meta.count

        var linknames = { teachers: [], courses: [], exceptions: [] }

        const responseEvents = ajaxresult.events || []
        const data = responseEvents.map(event => {
          // And add new event to array
          const newEvent = {
            id: event.id,
            name: event.name,
            course: event.links.course,
            startsAt: event.starts_at,
            endsAt: event.ends_at,
            sequenceNumber: event.sequence_number,
            type: event.event_type,
            room: event.links.room,
            flag: null,
            notification: false,
            cancelled: event.deleted,
            replacement: false,
            teachers: event.links.teachers,
            details: {
              students: event.links.students,
              capacity: event.capacity,
              parallel: event.parallel,
              appliedExceptions: event.links.applied_exceptions,
            },
          }

          // If the original data are present, insert one reverted event
          if (!emptyObject(event.original_data)) {
            // Convert times to milliseconds
            var rangeFromMs = (new Date(dateFrom)).getMilliseconds()
            var rangeToMs = (new Date(dateTo)).getMilliseconds()
            var originalFromMs = (new Date(event.original_data.starts_at)).getMilliseconds()

            // Check if the original start is between the range
            if (rangeFromMs <= originalFromMs && originalFromMs >= rangeToMs) {
              // The event is cancelled, show with original data
              newEvent.startsAt = event.original_data.starts_at
              newEvent.endsAt = event.original_data.ends_at
              newEvent.room = event.original_data.room_id
              newEvent.cancelled = true
              newEvent.replacedAt = event.starts_at
            } else {
              // The event is replacement
              newEvent.replacement = true
              newEvent.replaces = event.original_data.starts_at
            }
          }
          return newEvent
        })

        // Add teachers links full names
        if ('linked' in ajaxresult) {
          if ('teachers' in ajaxresult.linked) {
            for (let i = 0; i < ajaxresult.linked.teachers.length; i++) {
              // Add teacher link full name
              linknames.teachers.push({
                id: ajaxresult.linked.teachers[i].id,
                name: {
                  cs: ajaxresult.linked.teachers[i].full_name,
                  en: ajaxresult.linked.teachers[i].full_name,
                },
              })
            }
          }

          // Add courses links full names
          if ('courses' in ajaxresult.linked) {
            for (let i = 0; i < ajaxresult.linked.courses.length; i++) {
              // Add course link full name
              linknames.courses.push({
                id: ajaxresult.linked.courses[i].id,
                name: {
                  cs: ajaxresult.linked.courses[i].name.cs,
                  en: ajaxresult.linked.courses[i].name.en,
                },
              })
            }
          }

          // Add exceptions links full names
          if ('schedule_exceptions' in ajaxresult.linked) {
            for (let i = 0; i < ajaxresult.linked.schedule_exceptions.length; i++) {
              // Add exceptions link full name
              linknames.exceptions.push({
                id: ajaxresult.linked.schedule_exceptions[i].id,
                type: ajaxresult.linked.schedule_exceptions[i].exception_type,
                name: ajaxresult.linked.schedule_exceptions[i].name,
              })
            }
          }
        }

        // Send data to fittable
        callback(null, {events: data, linkNames: linknames})
      } else {
        // Request failed
        callback(generateError(request.status, 'dataCallback failed'))
      }
    }
  }.bind(null, callback, f)
}

/**
 * Search callback, returning search results from Sirius API.
 * @param query
 * @param callback
 */
var searchCallback = function (query, callback) {

  // Construct the request URL
  var request = makeRequest('search?q=' + query + '&limit=' + defaultLimit)

  request.onreadystatechange = function (callback, fittable) {
    if (request.readyState === XMLHttpRequest.DONE) {
      if (request.status === 200) {
        // Request successful
        var ajaxresult = JSON.parse(request.responseText)

        // Send data to fittable
        callback(ajaxresult.results)
      } else {
        // Request failed
        fittable.onError(generateError(request.status).type)
      }
    }
  }.bind(null, callback, f)
}

var dateChangeCallback = function (newdate, newsemester) {
  console.log(newdate, newsemester)
  // Display semester name in subheading
  updateTitle(null, newsemester)
}

var semesterDataCallback = function (callback) {

  // Construct the request URL
  var request = makeRequest('semesters?limit=' + defaultLimit)

  request.onreadystatechange = function (callback, fittable) {
    if (request.readyState === XMLHttpRequest.DONE) {
      if (request.status === 200) {
        // Request successful
        var ajaxresult = JSON.parse(request.responseText)
        var itemCount = ajaxresult.meta.count

        // Check if there is semesters object in result
        if (!('semesters' in ajaxresult)) {
          return false
        }

        var semesters = []

        // Create events from data
        for (var i = 0; i < itemCount; i++) {
          var semester = ajaxresult.semesters[i]

          // And add new semester to array
          semesters[ i ] = {
            id: semester.id,
            semester: semester.semester,
            faculty: semester.faculty,
            startsAt: semester.starts_at,
            endsAt: semester.ends_at,
            examsStartsAt: semester.exams_start_at,
            examsEndsAt: semester.exams_end_at,
            hourDuration: semester.hour_duration,
            breakDuration: 15,  // FIXME: replace this and that two below with semester.hourStarts
            dayStartsAtHour: 7.5,
            dayEndsAtHour: 21.25
          }
        }

        // Send semester data to fittable
        callback(semesters)
      } else {
        // Request failed
        fittable.onError(generateError(request.status).type)
      }
    }
  }.bind(null, callback, f)
}

var settingsChangeCallback = function (settings) {

  // We really don't want to save the user property
  settings.user = null

  // Save settings
  window.localStorage.setItem(user.name + '.settings', JSON.stringify(settings))

  // Update appLocale
  appLocale = settings.locale

  // Update title and subtitle for possible locale change
  updateTitle(view === 'person' && parameter === user.name ?
    viewNames[appLocale]['personal'] : viewNames[appLocale][view] + ' ' + parameter, null)
}

/**
 * --- Initialize the widget ---
 */

function viewChangeCallback (view, param) {
  console.error('viewChangeCallback fired!')
}

// If the user is not logged in, redirect him to the landing page
if (!isUserLoggedIn()) {
  window.location.href = 'landing.html'

} else {
  // Prepare the options object with default values
  var options = {
    locale: 'cs',
  }

  // Load settings from localStorage
  var save = window.localStorage.getItem(user.name + '.settings')
  if (save !== null) {
    var usersettings = JSON.parse(save)

    for (var key in usersettings) {
      options[key] = usersettings[key]
    }
  }

  // Set user and callbacks
  options.username = user.name
  options.usertoken = user.token
  options.callbacks = {
    data: dataCallback,
    search: searchCallback,

    dateChange: dateChangeCallback,
    semesterData: semesterDataCallback,
    settingsChange: settingsChangeCallback
  }

  // Get app locale
  appLocale = options.locale
}

function userCallback (cb) {
  const request = makeRequest(`people/${user.name}`)

  request.onreadystatechange = (callback, fittable) => {
    if (request.readyState === XMLHttpRequest.DONE) {
      if (request.status === 200) {
        // Request successful
        const rawData = JSON.parse(request.responseText)

        if (!rawData || !rawData.people) {
          cb(generateError('generic'))
          return
        }

        const rawUser = rawData.people

        const data = {
          publicAccessToken: rawUser['access_token'],
          id: rawUser.id,
          name: rawUser.name,
        }

        cb(null, data)
      } else {
        // Request failed
        cb(generateError(request.status).type)
      }
    }
  }
}

export {
  dataCallback as data,
  searchCallback as search,
  dateChangeCallback as dateChange,
  semesterDataCallback as semesterData,
  settingsChangeCallback as settingsChange,
  viewChangeCallback as viewChange,
  userCallback as user,
}
<|endoftext|>


<commit_before>const DrawCard = require('../../drawcard');

class MaesterMurenmure extends DrawCard {
    setupCardAbilities(ability) {
        this.interrupt({
            canCancel: true,
            when: {
                onCardAbilityInitiated: event => (
                    event.ability.isTriggeredAbility() &&
                    event.source.getType() === 'location' &&
                    // Explicitly allow cancellation of your own forced abilities
                    (event.ability.isForcedAbility() || event.source.controller !== this.controller)
                )
            },
            cost: ability.costs.kneelSelf(),
            handler: context => {
                this.game.addMessage('{0} kneels {1} to cancel {2}', this.controller, this, context.event.source);
                context.event.cancel();
            }
        });
    }
}

MaesterMurenmure.code = '12010';

module.exports = MaesterMurenmure;
<commit_msg>Trigger Murenmure based on triggering player (#2420)<commit_after>const DrawCard = require('../../drawcard');

class MaesterMurenmure extends DrawCard {
    setupCardAbilities(ability) {
        this.interrupt({
            canCancel: true,
            when: {
                onCardAbilityInitiated: event => (
                    event.ability.isTriggeredAbility() &&
                    event.source.getType() === 'location' &&
                    // Explicitly allow cancellation of your own forced abilities
                    (event.ability.isForcedAbility() || event.player !== this.controller)
                )
            },
            cost: ability.costs.kneelSelf(),
            handler: context => {
                this.game.addMessage('{0} kneels {1} to cancel {2}', this.controller, this, context.event.source);
                context.event.cancel();
            }
        });
    }
}

MaesterMurenmure.code = '12010';

module.exports = MaesterMurenmure;
<|endoftext|>


<commit_before>/**
 * Created by Spadon on 19/08/2015.
 */

var should = require('should');
var fs = require('fs');
var path = require('path');
var mime = require('mime-types');

var Logics = require('../hylar/core/Logics/Logics');
var OWL2RL = require('../hylar/core/OWL2RL');
var emitter = require('../hylar/core/Emitter');

var H = require('../hylar/hylar');
var owl, ontology, Hylar = new H();

var reasoningMethod = process.env.rm;
var triples = fs.readFileSync(path.resolve(__dirname + '/ontologies/University0_14.nt')).toString();
var baseOntoTxt = fs.readFileSync(path.resolve(__dirname + '/ontologies/univ-bench-base-onto.ttl')).toString();

var univ1 = baseOntoTxt + fs.readFileSync(path.resolve(__dirname + '/ontologies/University0_0.ttl')).toString();
var univ2 = baseOntoTxt + fs.readFileSync(path.resolve(__dirname + '/ontologies/University0_5.ttl')).toString();
var univ3 = baseOntoTxt + fs.readFileSync(path.resolve(__dirname + '/ontologies/University0_14.ttl')).toString();

/*var univ1 = baseOntoTxt + fs.readFileSync(path.resolve(__dirname + '/ontologies/University20-5k.ttl')).toString();
var univ2 = baseOntoTxt + fs.readFileSync(path.resolve(__dirname + '/ontologies/University20-20k.ttl')).toString();
var univ3 = baseOntoTxt + fs.readFileSync(path.resolve(__dirname + '/ontologies/University20-50k.ttl')).toString();*/

//univ1=univ3;
//univ1 += univ2 + univ3; //20k

Hylar.setRules(OWL2RL.equality.concat(OWL2RL.transitivityInverse, OWL2RL.equivalence, OWL2RL.subsumption));
//Hylar.setRules(OWL2RL.equivalence);
//Hylar.setRules(OWL2RL.equality);
//Hylar.setRules(OWL2RL.subsumption);
//Hylar.setRules(OWL2RL.transitivityInverse);

var date = new Date().getTime();
var firedRules;

emitter.on('rule-fired', function(rulename) {
    if (!firedRules[rulename]) {
        firedRules[rulename] = 0;
    }
    firedRules[rulename]++;
});

function initFiredRules() {
    firedRules = {};
}

function displayFiredRules() {
    console.log(JSON.stringify(firedRules, null, 4));
}

Hylar.quiet();

function delay() {
    /*var delay = new Date().getTime() - date;
    fs.appendFileSync('bench.txt', delay + '\n');
    console.log(delay);
    date = new Date().getTime();*/
}

describe('CLASSIFICATION UNIV 1', function () {
    it('should parse and classify the ontology', function () {
        initFiredRules();
        return Hylar.load(univ1, 'text/turtle', false, false, reasoningMethod)
        .then(function() {
            displayFiredRules();
            delay();
        });
    });
});

describe('INSERT UNIV 1', function () {
    var query, results;
    it('insert data and derivations', function () {
        var queryText = 'INSERT DATA { ' + triples + ' }';
        return Hylar.query(queryText).then(function() {
            delay();
        });
    });
});

describe('DELETE UNIV 1', function () {
    var query, results;
    it('insert data and derivations', function () {
        var queryText = 'DELETE DATA { ' + triples + ' }';
        return Hylar.query(queryText).then(function() {
            delay();
        });
    });
});

describe('REINSERT UNIV 1', function () {
    var query, results;
    it('insert data and derivations', function () {
        var queryText = 'INSERT DATA { ' + triples + ' }';
        return Hylar.query(queryText).then(function() {
            delay();
        });
    });
});

describe('SELECT', function () {
    var queryText = 'PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX ub: <http://www.lehigh.edu/~zhp2/2004/0401/univ-bench.owl#> SELECT ?X ?Y ?Z WHERE {?X rdf:type ub:GraduateStudent . ?Y rdf:type ub:University . ?Z rdf:type ub:Department . ?X ub:memberOf ?Z . ?Z ub:subOrganizationOf ?Y . ?X ub:undergraduateDegreeFrom ?Y}';
    it('insert data and derivations', function () {
        return Hylar.query(queryText).then(function() {
            delay();
        });
    });
});

// ------------------------------------------------------------------------

describe('CLASSIFICATION UNIV 2', function () {
    it('should parse and classify the ontology', function () {
        return Hylar.load(univ2, 'text/turtle', false, false, reasoningMethod).then(function() {
            delay();
        });
    });
});

describe('INSERT UNIV 2', function () {
    var query, results;
    it('insert data and derivations', function () {
        var queryText = 'INSERT DATA { ' + triples + ' }';
        return Hylar.query(queryText).then(function() {
            delay();
        });
    });
});

describe('DELETE UNIV 2', function () {
    var query, results;
    it('insert data and derivations', function () {
        var queryText = 'DELETE DATA { ' + triples + ' }';
        return Hylar.query(queryText).then(function() {
            delay();
        });
    });
});

describe('REINSERT UNIV 2', function () {
    var query, results;
    it('insert data and derivations', function () {
        var queryText = 'INSERT DATA { ' + triples + ' }';
        return Hylar.query(queryText).then(function() {
            delay();
        });
    });
});

describe('SELECT', function () {
    var queryText = 'PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX ub: <http://www.lehigh.edu/~zhp2/2004/0401/univ-bench.owl#> SELECT ?X ?Y ?Z WHERE {?X rdf:type ub:GraduateStudent . ?Y rdf:type ub:University . ?Z rdf:type ub:Department . ?X ub:memberOf ?Z . ?Z ub:subOrganizationOf ?Y . ?X ub:undergraduateDegreeFrom ?Y}';
    it('insert data and derivations', function () {
        return Hylar.query(queryText).then(function() {
            delay();
        });
    });
});

// ------------------------------------------------------------------------

describe('CLASSIFICATION UNIV 3', function () {
    it('should parse and classify the ontology', function () {
        return Hylar.load(univ3, 'text/turtle', false, false, reasoningMethod).then(function() {
            delay();
        });
    });
});

describe('INSERT UNIV 3', function () {
    var query, results;
    it('insert data and derivations', function () {
        var queryText = 'INSERT DATA { ' + triples + ' }';
        return Hylar.query(queryText).then(function() {
            delay();
        });
    });
});

describe('DELETE UNIV 3', function () {
    var query, results;
    it('insert data and derivations', function () {
        var queryText = 'DELETE DATA { ' + triples + ' }';
        return Hylar.query(queryText).then(function() {
            delay();
        });
    });
});

describe('REINSERT UNIV 3', function () {
    var query, results;
    it('insert data and derivations', function () {
        var queryText = 'INSERT DATA { ' + triples + ' }';
        return Hylar.query(queryText).then(function() {
            delay();
        });
    });
});

describe('SELECT', function () {
    var queryText = 'PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX ub: <http://www.lehigh.edu/~zhp2/2004/0401/univ-bench.owl#> SELECT ?X ?Y ?Z WHERE {?X rdf:type ub:GraduateStudent . ?Y rdf:type ub:University . ?Z rdf:type ub:Department . ?X ub:memberOf ?Z . ?Z ub:subOrganizationOf ?Y . ?X ub:undergraduateDegreeFrom ?Y}';
    it('insert data and derivations', function () {
        return Hylar.query(queryText).then(function() {
            delay();
        });
    });
});<commit_msg>Stashing<commit_after>/**
 * Created by Spadon on 19/08/2015.
 */

var should = require('should');
var fs = require('fs');
var path = require('path');
var mime = require('mime-types');

var Logics = require('../hylar/core/Logics/Logics');
var OWL2RL = require('../hylar/core/OWL2RL');
var emitter = require('../hylar/core/Emitter');

var H = require('../hylar/hylar');
var owl, ontology, Hylar = new H();

var reasoningMethod = process.env.rm;
var triples = fs.readFileSync(path.resolve(__dirname + '/ontologies/University0_14.nt')).toString();
var baseOntoTxt = fs.readFileSync(path.resolve(__dirname + '/ontologies/univ-bench-base-onto.ttl')).toString();

var univ1 = baseOntoTxt + fs.readFileSync(path.resolve(__dirname + '/ontologies/University0_0.ttl')).toString();
var univ2 = baseOntoTxt + fs.readFileSync(path.resolve(__dirname + '/ontologies/University0_5.ttl')).toString();
var univ3 = baseOntoTxt + fs.readFileSync(path.resolve(__dirname + '/ontologies/University0_14.ttl')).toString();

/*var univ1 = baseOntoTxt + fs.readFileSync(path.resolve(__dirname + '/ontologies/University20-5k.ttl')).toString();
var univ2 = baseOntoTxt + fs.readFileSync(path.resolve(__dirname + '/ontologies/University20-20k.ttl')).toString();
var univ3 = baseOntoTxt + fs.readFileSync(path.resolve(__dirname + '/ontologies/University20-50k.ttl')).toString();*/

//univ1=univ3;
//univ1 += univ2 + univ3; //20k

Hylar.setRules(OWL2RL.equality.concat(OWL2RL.transitivityInverse, OWL2RL.equivalence, OWL2RL.subsumption));
//Hylar.setRules(OWL2RL.equivalence);
//Hylar.setRules(OWL2RL.equality);
//Hylar.setRules(OWL2RL.subsumption);
//Hylar.setRules(OWL2RL.transitivityInverse);

var date = new Date().getTime();
var firedRules;

emitter.on('rule-fired', function(rulename) {
    if (!firedRules[rulename]) {
        firedRules[rulename] = 0;
    }
    firedRules[rulename]++;
});

function initFiredRules() {
    firedRules = {};
}

function displayFiredRules() {
    console.log(JSON.stringify(firedRules, null, 4));
}

Hylar.quiet();

function delay() {
    /*var delay = new Date().getTime() - date;
    fs.appendFileSync('bench.txt', delay + '\n');
    console.log(delay);
    date = new Date().getTime();*/
}

describe('CLASSIFICATION UNIV 1', function () {
    it('should parse and classify the ontology', function () {
        initFiredRules();
        return Hylar.load(univ1, 'text/turtle', false, false, reasoningMethod)
        .then(function() {
            displayFiredRules();
            delay();
        });
    });
});

describe('INSERT UNIV 1', function () {
    var query, results;
    it('insert data and derivations', function () {
        var queryText = 'INSERT DATA { ' + triples + ' }';
        return Hylar.query(queryText).then(function() {
            delay();
        });
    });
});

describe('DELETE UNIV 1', function () {
    var query, results;
    it('insert data and derivations', function () {
        var queryText = 'DELETE DATA { ' + triples + ' }';
        return Hylar.query(queryText).then(function() {
            delay();
        });
    });
});

describe('REINSERT UNIV 1', function () {
    var query, results;
    it('insert data and derivations', function () {
        var queryText = 'INSERT DATA { ' + triples + ' }';
        return Hylar.query(queryText).then(function() {
            delay();
        });
    });
});

describe('SELECT', function () {
    var queryText = 'PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX ub: <http://www.lehigh.edu/~zhp2/2004/0401/univ-bench.owl#> SELECT ?X ?Y ?Z WHERE {?X rdf:type ub:GraduateStudent . ?Y rdf:type ub:University . ?Z rdf:type ub:Department . ?X ub:memberOf ?Z . ?Z ub:subOrganizationOf ?Y . ?X ub:undergraduateDegreeFrom ?Y}';
    it('insert data and derivations', function () {
        return Hylar.query(queryText).then(function() {
            delay();
        });
    });
});

// ------------------------------------------------------------------------

describe('CLASSIFICATION UNIV 2', function () {
    it('should parse and classify the ontology', function () {
        return Hylar.load(univ2, 'text/turtle', false, false, reasoningMethod).then(function() {
            delay();
        });
    });
});

describe('INSERT UNIV 2', function () {
    var query, results;
    it('insert data and derivations', function () {
        var queryText = 'INSERT DATA { ' + triples + ' }';
        return Hylar.query(queryText).then(function() {
            delay();
        });
    });
});

describe('DELETE UNIV 2', function () {
    var query, results;
    it('insert data and derivations', function () {
        var queryText = 'DELETE DATA { ' + triples + ' }';
        return Hylar.query(queryText).then(function() {
            delay();
        });
    });
});

describe('REINSERT UNIV 2', function () {
    var query, results;
    it('insert data and derivations', function () {
        var queryText = 'INSERT DATA { ' + triples + ' }';
        return Hylar.query(queryText).then(function() {
            delay();
        });
    });
});

describe('SELECT', function () {
    var queryText = 'PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX ub: <http://www.lehigh.edu/~zhp2/2004/0401/univ-bench.owl#> SELECT ?X ?Y ?Z WHERE {?X rdf:type ub:GraduateStudent . ?Y rdf:type ub:University . ?Z rdf:type ub:Department . ?X ub:memberOf ?Z . ?Z ub:subOrganizationOf ?Y . ?X ub:undergraduateDegreeFrom ?Y}';
    it('insert data and derivations', function () {
        return Hylar.query(queryText).then(function() {
            delay();
        });
    });
});

// ------------------------------------------------------------------------

describe('CLASSIFICATION UNIV 3', function () {
    it('should parse and classify the ontology', function () {
        return Hylar.load(univ3, 'text/turtle', false, false, reasoningMethod).then(function() {
            delay();
        });
    });
});

describe('INSERT UNIV 3', function () {
    var query, results;
    it('insert data and derivations', function () {
        var queryText = 'INSERT DATA { ' + triples + ' }';
        return Hylar.query(queryText).then(function() {
            delay();
        });
    });
});

describe('DELETE UNIV 3', function () {
    var query, results;
    it('insert data and derivations', function () {
        var queryText = 'DELETE DATA { ' + triples + ' }';
        return Hylar.query(queryText).then(function() {
            delay();
        });
    });
});

describe('REINSERT UNIV 3', function () {
    var query, results;
    it('insert data and derivations', function () {
        var queryText = 'INSERT DATA { ' + triples + ' }';
        return Hylar.query(queryText).then(function() {
            delay();
        });
    });
});

describe('SELECT', function () {
    var queryText = 'PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX ub: <http://www.lehigh.edu/~zhp2/2004/0401/univ-bench.owl#> SELECT ?X ?Y ?Z WHERE {?X rdf:type ub:GraduateStudent . ?Y rdf:type ub:University . ?Z rdf:type ub:Department . ?X ub:memberOf ?Z . ?Z ub:subOrganizationOf ?Y . ?X ub:undergraduateDegreeFrom ?Y}';
    it('insert data and derivations', function () {
        return Hylar.query(queryText).then(function() {
            delay();
        });
    });
});<|endoftext|>


<commit_before>/* global describe, it */
import {expect} from 'chai';
import Response from '../../src/core/request.js';

describe('Response', () => {
  it('should have all fields', () => {
    const request = new Response();
    expect(request.method).to.not.equal(undefined);
    expect(request.headers).to.not.equal(undefined);
    expect(request.cache).to.not.equal(undefined);
    expect(request.bodyUsed).to.not.equal(undefined);
    expect(request.context).to.not.equal(undefined);
    expect(request.mode).to.not.equal(undefined);
    expect(request.referrer).to.not.equal(undefined);
    expect(request.referrerPolicy).to.not.equal(undefined);
    expect(request.url).to.not.equal(undefined);
  });
  it('should have all body fields ', () => {
    const request = new Response();
    expect(request.json).to.not.equal(undefined);
    expect(request.blob).to.not.equal(undefined);
    expect(request.text).to.not.equal(undefined);
    expect(request.arrayBuffer).to.not.equal(undefined);
    expect(request.formData).to.not.equal(undefined);
  });
});
<commit_msg>Fixed response tests<commit_after>/* global describe, it */
import {expect} from 'chai';
import Response from '../../src/core/response.js';

describe('Response', () => {
  it('should have all fields', () => {
    const response = new Response();
    expect(response.body).to.not.equal(undefined);
    expect(response.ok).to.not.equal(undefined);
    expect(response.status).to.not.equal(undefined);
    expect(response.statusMessage).to.not.equal(undefined);
    expect(response.headers).to.not.equal(undefined);
    expect(response.type).to.not.equal(undefined);
    expect(response.url).to.not.equal(undefined);
    expect(response.useFinalUrl).to.not.equal(undefined);
  });
  it('should have all body fields ', () => {
    const response = new Response();
    expect(response.json).to.not.equal(undefined);
    expect(response.blob).to.not.equal(undefined);
    expect(response.text).to.not.equal(undefined);
    expect(response.arrayBuffer).to.not.equal(undefined);
    expect(response.formData).to.not.equal(undefined);
  });
  it('should set statusMessage when status is set', () => {
      const response = new Response();
      response.status = 201;
      expect(response.statusMessage).to.equal('Created');
  });
  it('should parse json', () => {

  });
  it('should parse text', () => {

  });
});
<|endoftext|>


<commit_before>define(function(require, exports, module) {
  "use strict";

    var TSCORE = require("tscore");
    var extDir;
    var supportedFileTypesThumbs = ['jpg','jpeg','png','gif','bmp','svg'];
    var defaultThumnailPath;

    function initUI(dir) {
        extDir = dir;
        defaultThumnailPath = extDir + "/default.png";
    }

    function load(container, template, files) {
        var data = [];
        var compiledTemplate = Handlebars.compile(template);
        files.forEach(function(fileInfo) {
            var ext = fileInfo[TSCORE.fileListFILEEXT];

            if(supportedFileTypesThumbs.indexOf(ext) !== -1) {

                var doc = {
                    name: fileInfo[TSCORE.fileListFILENAME],
                    path: fileInfo[TSCORE.fileListFILEPATH],
                    thumbnail: defaultThumnailPath,
                    title: fileInfo[TSCORE.fileListTITLE]
                }

                data.push(doc);
            }
        });

        var html = compiledTemplate({data: data});
        container.append(html);
        initPhotoSwipeFromDOM('.my-gallery');
    }

    exports.initUI = initUI;
    exports.load = load;

    var initPhotoSwipeFromDOM = function(gallerySelector) {

        // parse slide data (url, title, size ...) from DOM elements
        // (children of gallerySelector)
        var parseThumbnailElements = function(el) {
            var thumbElements = el.childNodes,
                numNodes = thumbElements.length,
                items = [],
                figureEl,
                linkEl,
                size,
                item;

            for(var i = 0; i < numNodes; i++) {

                figureEl = thumbElements[i]; // <figure> element

                // include only element nodes
                if(figureEl.nodeType !== 1) {
                    continue;
                }

                linkEl = figureEl.children[0]; // <a> element

                size = [0,0]; //linkEl.getAttribute('data-size').split('x');

                // create slide object
                item = {
                    src: linkEl.getAttribute('href'),
                    w: parseInt(size[0], 10),
                    h: parseInt(size[1], 10)
                };

                if(figureEl.children.length > 1) {
                    // <figcaption> content
                    item.title = figureEl.children[1].innerHTML;
                }

                if(linkEl.children.length > 0) {
                    // <img> thumbnail element, retrieving thumbnail url
                    item.msrc = linkEl.children[0].getAttribute('src');
                }

                item.el = figureEl; // save link to element for getThumbBoundsFn
                items.push(item);
            }

            return items;
        };

        // find nearest parent element
        var closest = function closest(el, fn) {
            return el && ( fn(el) ? el : closest(el.parentNode, fn) );
        };

        // triggers when user clicks on thumbnail
        var onThumbnailsClick = function(e) {
            e = e || window.event;
            e.preventDefault ? e.preventDefault() : e.returnValue = false;

            var eTarget = e.target || e.srcElement;

            // find root element of slide
            var clickedListItem = closest(eTarget, function(el) {
                return (el.tagName && el.tagName.toUpperCase() === 'FIGURE');
            });

            if(!clickedListItem) {
                return;
            }

            // find index of clicked item by looping through all child nodes
            // alternatively, you may define index via data- attribute
            var clickedGallery = clickedListItem.parentNode,
                childNodes = clickedListItem.parentNode.childNodes,
                numChildNodes = childNodes.length,
                nodeIndex = 0,
                index;

            for (var i = 0; i < numChildNodes; i++) {
                if(childNodes[i].nodeType !== 1) {
                    continue;
                }

                if(childNodes[i] === clickedListItem) {
                    index = nodeIndex;
                    break;
                }
                nodeIndex++;
            }

            if(index >= 0) {
                // open PhotoSwipe if valid index found
                openPhotoSwipe( index, clickedGallery );
            }
            return false;
        };

        var openPhotoSwipe = function(index, galleryElement, disableAnimation, fromURL) {
            var pswpElement = document.querySelectorAll('.pswp')[0],
                gallery,
                options,
                items;

            items = parseThumbnailElements(galleryElement);

            options = {
                // define gallery index (for URL)
                galleryUID: galleryElement.getAttribute('data-pswp-uid'),

                getThumbBoundsFn: function(index) {
                    // See Options -> getThumbBoundsFn section of documentation for more info
                    var thumbnail = items[index].el.getElementsByTagName('img')[0], // find thumbnail
                        pageYScroll = window.pageYOffset || document.documentElement.scrollTop,
                        rect = thumbnail.getBoundingClientRect();

                    return {x:rect.left, y:rect.top + pageYScroll, w:rect.width};
                }
            };

            options.index = parseInt(index, 10);

            // exit if index not found
            if( isNaN(options.index) ) {
                console.log("PhotoSwipe error: index not found");
                return;
            }

            if(disableAnimation) {
                options.showAnimationDuration = 0;
            }

             require([
                extDir + "/dist/photoswipe.js",
                extDir + "/dist/photoswipe-ui-default.js",
            ], function( PhotoSwipe, PhotoSwipeUI_Default ) {

                gallery = new PhotoSwipe( pswpElement, PhotoSwipeUI_Default, items, options);
                gallery.init();

                gallery.listen('imageLoadComplete', function(index, item) {

                    var img = new Image();
                    img.src = item.src;
                    item.w = img.width;
                    item.h = img.height;
                    gallery.updateSize(true);
                    img = undefined;
                });

            });
        };

        // loop through all gallery elements and bind events
        var galleryElements = document.querySelectorAll( gallerySelector );

        for(var i = 0, l = galleryElements.length; i < l; i++) {
            galleryElements[i].setAttribute('data-pswp-uid', i+1);
            galleryElements[i].onclick = onThumbnailsClick;
        }
    };
});<commit_msg>fixed image urls<commit_after>define(function(require, exports, module) {
  "use strict";

    var TSCORE = require("tscore");
    var extDir;
    var supportedFileTypesThumbs = ['jpg','jpeg','png','gif','bmp','svg'];
    var defaultThumnailPath;

    function initUI(dir) {
        extDir = dir;
        defaultThumnailPath = extDir + "/default.png";
    }

    function load(container, template, files) {
        var data = [];
        var compiledTemplate = Handlebars.compile(template);
        files.forEach(function(fileInfo) {
            var ext = fileInfo[TSCORE.fileListFILEEXT];

            if(supportedFileTypesThumbs.indexOf(ext) !== -1) {

                var doc = {
                    name: fileInfo[TSCORE.fileListFILENAME],
                    path: encodeURI(fileInfo[TSCORE.fileListFILEPATH]),
                    thumbnail: encodeURI(defaultThumnailPath),
                    title: fileInfo[TSCORE.fileListTITLE]
                }
                data.push(doc);
            }
        });

        var html = compiledTemplate({data: data});
        container.append(html);
        initPhotoSwipeFromDOM('.my-gallery');
    }

    exports.initUI = initUI;
    exports.load = load;

    var initPhotoSwipeFromDOM = function(gallerySelector) {

        // parse slide data (url, title, size ...) from DOM elements
        // (children of gallerySelector)
        var parseThumbnailElements = function(el) {
            var thumbElements = el.childNodes,
                numNodes = thumbElements.length,
                items = [],
                figureEl,
                linkEl,
                size,
                item;

            for(var i = 0; i < numNodes; i++) {

                figureEl = thumbElements[i]; // <figure> element

                // include only element nodes
                if(figureEl.nodeType !== 1) {
                    continue;
                }

                linkEl = figureEl.children[0]; // <a> element

                size = [0,0]; //linkEl.getAttribute('data-size').split('x');

                // create slide object
                item = {
                    src: linkEl.getAttribute('href'),
                    w: parseInt(size[0], 10),
                    h: parseInt(size[1], 10)
                };

                if(figureEl.children.length > 1) {
                    // <figcaption> content
                    item.title = figureEl.children[1].innerHTML;
                }

                if(linkEl.children.length > 0) {
                    // <img> thumbnail element, retrieving thumbnail url
                    item.msrc = linkEl.children[0].getAttribute('src');
                }

                item.el = figureEl; // save link to element for getThumbBoundsFn
                items.push(item);
            }

            return items;
        };

        // find nearest parent element
        var closest = function closest(el, fn) {
            return el && ( fn(el) ? el : closest(el.parentNode, fn) );
        };

        // triggers when user clicks on thumbnail
        var onThumbnailsClick = function(e) {
            e = e || window.event;
            e.preventDefault ? e.preventDefault() : e.returnValue = false;

            var eTarget = e.target || e.srcElement;

            // find root element of slide
            var clickedListItem = closest(eTarget, function(el) {
                return (el.tagName && el.tagName.toUpperCase() === 'FIGURE');
            });

            if(!clickedListItem) {
                return;
            }

            // find index of clicked item by looping through all child nodes
            // alternatively, you may define index via data- attribute
            var clickedGallery = clickedListItem.parentNode,
                childNodes = clickedListItem.parentNode.childNodes,
                numChildNodes = childNodes.length,
                nodeIndex = 0,
                index;

            for (var i = 0; i < numChildNodes; i++) {
                if(childNodes[i].nodeType !== 1) {
                    continue;
                }

                if(childNodes[i] === clickedListItem) {
                    index = nodeIndex;
                    break;
                }
                nodeIndex++;
            }

            if(index >= 0) {
                // open PhotoSwipe if valid index found
                openPhotoSwipe( index, clickedGallery );
            }
            return false;
        };

        var openPhotoSwipe = function(index, galleryElement, disableAnimation, fromURL) {
            var pswpElement = document.querySelectorAll('.pswp')[0],
                gallery,
                options,
                items;

            items = parseThumbnailElements(galleryElement);

            options = {
                // define gallery index (for URL)
                galleryUID: galleryElement.getAttribute('data-pswp-uid'),

                getThumbBoundsFn: function(index) {
                    // See Options -> getThumbBoundsFn section of documentation for more info
                    var thumbnail = items[index].el.getElementsByTagName('img')[0], // find thumbnail
                        pageYScroll = window.pageYOffset || document.documentElement.scrollTop,
                        rect = thumbnail.getBoundingClientRect();

                    return {x:rect.left, y:rect.top + pageYScroll, w:rect.width};
                }
            };

            options.index = parseInt(index, 10);

            // exit if index not found
            if( isNaN(options.index) ) {
                console.log("PhotoSwipe error: index not found");
                return;
            }

            if(disableAnimation) {
                options.showAnimationDuration = 0;
            }

             require([
                extDir + "/dist/photoswipe.js",
                extDir + "/dist/photoswipe-ui-default.js",
            ], function( PhotoSwipe, PhotoSwipeUI_Default ) {

                gallery = new PhotoSwipe( pswpElement, PhotoSwipeUI_Default, items, options);
                gallery.init();

                gallery.listen('imageLoadComplete', function(index, item) {

                    var img = new Image();
                    img.src = item.src;
                    item.w = img.width;
                    item.h = img.height;
                    gallery.updateSize(true);
                    img = undefined;
                });

            });
        };

        // loop through all gallery elements and bind events
        var galleryElements = document.querySelectorAll( gallerySelector );

        for(var i = 0, l = galleryElements.length; i < l; i++) {
            galleryElements[i].setAttribute('data-pswp-uid', i+1);
            galleryElements[i].onclick = onThumbnailsClick;
        }
    };
});<|endoftext|>


<commit_before>const DrawCard = require('../../../drawcard.js');

class GreatKraken extends DrawCard {
    constructor(owner, cardData) {
        super(owner, cardData);

        this.registerEvents(['onUnopposedWin', 'onBeginRound', 'onCardPlayed']);
    }

    onBeginRound() {
        this.abilityUsed = 0;
    }

    onUnopposedWin(event, challenge) {
        var winner = challenge.winner;
        if(!this.inPlay || this.isBlank() || this.controller !== winner && this.abilityUsed < 2) {
            return;
        }

        this.game.promptWithMenu(winner, this, {
            activePrompt: {
                menuTitle: 'Trigger ' + this.name + '?',
                buttons: [
                    { text: 'Draw 1 card', command: 'menuButton', method: 'drawCard' },
                    { test: 'Gain 1 power', command: 'menuButton', method: 'gainPower' },
                    { text: 'No', command: 'menuButton', method: 'cancel' }
                ]
            },
            waitingPromptTitle: 'Waiting for opponent to perform reactions'
        });
    }

    onCardPlayed(event, player, cardId) {
        if(!this.inPlay || this.controller !== player) {
            return;
        }

        var card = player.findCardInPlayByUuid(cardId);
        if(!card) {
            return;
        }

        if(card.name === 'Balon Greyjoy') {
            card.addKeyword('stealth');
        }
    }

    gainPower(player) {
        if(!this.inPlay || this.isBlank() || this.controller !== player) {
            return false;
        }

        this.game.addPower(player, 1);

        this.game.addMessage('{0} uses {1} to 1 power for their faction', player, this);

        this.abilityUsed++;

        return true;
    }

    drawCard(player) {
        if(!this.inPlay || this.isBlank() || this.controller !== player) {
            return false;
        }

        player.drawCardsToHand(1);

        this.game.addMessage('{0} uses {1} to draw 1 card', player, this);

        this.abilityUsed++;

        return true;
    }

    cancel(player) {
        if(!this.inPlay || this.isBlank() || this.controller !== player) {
            return false;
        }

        this.game.addMessage('{0} declines to trigger {1}', player, this);
        return true;
    }

    leavesPlay() {
        var balonGreyjoy = this.controller.findCardByName(this.controller.cardsInPlay, 'Balon Greyjoy');

        if(balonGreyjoy) {
            balonGreyjoy.removeKeyword('stealth');
        }
    }
}

GreatKraken.code = '01078';

module.exports = GreatKraken;
<commit_msg>fix typo<commit_after>const DrawCard = require('../../../drawcard.js');

class GreatKraken extends DrawCard {
    constructor(owner, cardData) {
        super(owner, cardData);

        this.registerEvents(['onUnopposedWin', 'onBeginRound', 'onCardPlayed']);
    }

    onBeginRound() {
        this.abilityUsed = 0;
    }

    onUnopposedWin(event, challenge) {
        var winner = challenge.winner;
        if(!this.inPlay || this.isBlank() || this.controller !== winner && this.abilityUsed < 2) {
            return;
        }

        this.game.promptWithMenu(winner, this, {
            activePrompt: {
                menuTitle: 'Trigger ' + this.name + '?',
                buttons: [
                    { text: 'Draw 1 card', command: 'menuButton', method: 'drawCard' },
                    { text: 'Gain 1 power', command: 'menuButton', method: 'gainPower' },
                    { text: 'No', command: 'menuButton', method: 'cancel' }
                ]
            },
            waitingPromptTitle: 'Waiting for opponent to perform reactions'
        });
    }

    onCardPlayed(event, player, cardId) {
        if(!this.inPlay || this.controller !== player) {
            return;
        }

        var card = player.findCardInPlayByUuid(cardId);
        if(!card) {
            return;
        }

        if(card.name === 'Balon Greyjoy') {
            card.addKeyword('stealth');
        }
    }

    gainPower(player) {
        if(!this.inPlay || this.isBlank() || this.controller !== player) {
            return false;
        }

        this.game.addPower(player, 1);

        this.game.addMessage('{0} uses {1} to 1 power for their faction', player, this);

        this.abilityUsed++;

        return true;
    }

    drawCard(player) {
        if(!this.inPlay || this.isBlank() || this.controller !== player) {
            return false;
        }

        player.drawCardsToHand(1);

        this.game.addMessage('{0} uses {1} to draw 1 card', player, this);

        this.abilityUsed++;

        return true;
    }

    cancel(player) {
        if(!this.inPlay || this.isBlank() || this.controller !== player) {
            return false;
        }

        this.game.addMessage('{0} declines to trigger {1}', player, this);
        return true;
    }

    leavesPlay() {
        var balonGreyjoy = this.controller.findCardByName(this.controller.cardsInPlay, 'Balon Greyjoy');

        if(balonGreyjoy) {
            balonGreyjoy.removeKeyword('stealth');
        }
    }
}

GreatKraken.code = '01078';

module.exports = GreatKraken;
<|endoftext|>


<commit_before>"use strict";

var test = require("tap").test;
var breakable = require("../");

test("normal-return", function(t) {
    t.equal(breakable(function(brk) {
        return 1;
    }), 1);
    t.end();
});

test("break-return", function(t) {
    t.equal(breakable(function(brk) {
        brk(2);
        return 1;
    }), 2);
    t.end();
});

test("recurse", function(t) {
    t.equal(breakable(function(brk) {
        function traverse(n) {
            if (n < 100) {
                traverse(n + 1);
            }
            brk(n);
        }
        traverse(0);
    }), 100);
    t.end();
});

test("simple-throws", function(t) {
    t.throws(breakable.fn(function(brk) {
        throw 1;
    }));
    t.doesNotThrow(breakable.fn(function(brk) {
        brk(1);
        throw 2;
    }));
    t.end();
});

test("prop-recurse-break", function(t) {
    var tstObj = {a: 1, b: {c: 2, d: {e: 3, f: "gold", g: null}}, h: {i: 6}};

    var found = breakable(function(brk) {
        function traverse(obj) {
            var props = Object.keys(obj);
            props.forEach(function(prop) {
                var val = obj[prop];
                if (val === "gold") {
                    brk(prop);
                } else if (val === null) {
                    throw new Error("break did not work");
                } else if (val && typeof val === "object") {
                    traverse(val);
                }
            });
        }
        traverse(tstObj);
    });
    t.equal(found, "f");
    t.end();
});

test("forEach-break", function(t) {
    var cnt = 0;
    breakable(function(brk) {
        [1,2,3].forEach(function(v) {
            ++cnt;
            if (v === 2) {
                brk();
            }
        });
    });
    t.equal(cnt, 2);
    t.end();
});

test("nested-forEach-break", function(t) {
    var cnt = 0;
    breakable(function(brk) {
        [1,2,3].forEach(function(v) {
            [4,5,6].forEach(function(v1) {
                ++cnt;
                if (v === 2 && v1 === 5) {
                    brk();
                }
            });
        });
    });
    t.equal(cnt, 5);
    t.end();
});
<commit_msg>add failing test for nested breakables, don't use breakable.fn<commit_after>"use strict";

var test = require("tap").test;
var breakable = require("../");

test("normal-return", function(t) {
    t.equal(breakable(function(brk) {
        return 1;
    }), 1);
    t.end();
});

test("break-return", function(t) {
    t.equal(breakable(function(brk) {
        brk(2);
        return 1;
    }), 2);
    t.end();
});

test("recurse", function(t) {
    t.equal(breakable(function(brk) {
        function traverse(n) {
            if (n < 100) {
                traverse(n + 1);
            }
            brk(n);
        }
        traverse(0);
    }), 100);
    t.end();
});

test("simple-throws", function(t) {
    t.throws(breakable.bind(null, function(brk) {
        throw 1;
    }));
    t.doesNotThrow(breakable.bind(null, function(brk) {
        brk(1);
        throw 2;
    }));
    t.end();
});

test("prop-recurse-break", function(t) {
    var tstObj = {a: 1, b: {c: 2, d: {e: 3, f: "gold", g: null}}, h: {i: 6}};

    var found = breakable(function(brk) {
        function traverse(obj) {
            var props = Object.keys(obj);
            props.forEach(function(prop) {
                var val = obj[prop];
                if (val === "gold") {
                    brk(prop);
                } else if (val === null) {
                    throw new Error("break did not work");
                } else if (val && typeof val === "object") {
                    traverse(val);
                }
            });
        }
        traverse(tstObj);
    });
    t.equal(found, "f");
    t.end();
});

test("forEach-break", function(t) {
    var cnt = 0;
    breakable(function(brk) {
        [1,2,3].forEach(function(v) {
            ++cnt;
            if (v === 2) {
                brk();
            }
        });
    });
    t.equal(cnt, 2);
    t.end();
});

test("nested-forEach-break", function(t) {
    var cnt = 0;
    breakable(function(brk) {
        [1,2,3].forEach(function(v) {
            [4,5,6].forEach(function(v1) {
                ++cnt;
                if (v === 2 && v1 === 5) {
                    brk();
                }
            });
        });
    });
    t.equal(cnt, 5);
    t.end();
});

test("nested-breakables-1", function(t) {
    var res = breakable(function(brk1) {
        breakable(function(brk2) {
            brk1(13);
        });
    });
    t.equal(res, 13);
    t.end();
});

test("nested-breakables-2", function(t) {
    t.plan(2);
    var res1 = breakable(function(brk1) {
        var res2 = breakable(function(brk2) {
            brk2(13);
        });
        t.equal(res2, 13);
    });
    t.equal(res1, undefined);
    t.end();
});
<|endoftext|>


<commit_before>module.exports = { // we shoudl probably keep this session object empty so we can easily assing all of the user info instead of interating throught each field of a record in db
    //userId :"000",
    //name : "",
    //email : "",
    //zipcode : "",
    //face_id : "",
    //stock : "",
    //homeAddress :"",
    //workAddress : ""
};<commit_msg>removing this as we don't need it.<commit_after><|endoftext|>


<commit_before>import "./setup";

import {expect} from "chai";
import {insertHTML} from "./utils";
import BtrzField from "../src/btrz-field";
import BtrzInput from "../src/btrz-input";

describe("BtrzField", () => {
  it("Should render a form-group.", () => {
    insertHTML(`

                  <btrz-field name="testName" type="text" value="testValue"></btrz-field>

`);

    const app = new Vue({
        el: "#app",
        components: {BtrzField}
      }),
    formGroup = $(".form-group");
    expect(formGroup.length).to.equal(1);
  });

  it("Should render correct label.", () => {
    insertHTML(`

                  <btrz-field name="testName" type="text" value="testValue" label="testLabel"></btrz-field>

`);

    const app = new Vue({
        el: "#app",
        components: {BtrzField}
      }),
    label = $(".form-group label");
    expect(label.text()).to.equal("testLabel:");
  });

  it("Should render an empty label if label field is empty.", () => {
    insertHTML(`

                  <btrz-field name="testName" type="testType" value="testValue" label=""></btrz-field>

`);

    const app = new Vue({
        el: "#app",
        components: {BtrzField}
      }),
    label = $(".form-group label");
    expect(label.html().trim()).to.equal(' ');
  });

  it("Should render correct for attribute in the label.", () => {
    insertHTML(`

                  <btrz-field id="123456" name="testName" type="testType" value="testValue" label="true"></btrz-field>

`);

    const app = new Vue({
        el: "#app",
        components: {BtrzField}
      }),
    label = $(".form-group label");
    expect(label.attr("for")).to.equal('123456');
  });

  it("Should have class .input--filled if the input is contains text.", () => {
    insertHTML(`

                  <btrz-field name="testName" type="testType" value="testValue" label="true"></btrz-field>

`);

    const app = new Vue({
        el: "#app",
        components: {BtrzField}
      }),
    formGroup = $(".form-group");
    expect(formGroup.hasClass('input--filled')).to.equal(true);
  });

  it("Should have class .input--empty if the input is empty.", () => {
    insertHTML(`

                  <btrz-field name="testName" type="text" value="" label="label text"></btrz-field>

`);

    const app = new Vue({
        el: "#app",
        components: {BtrzField}
      }),
    formGroup = $(".form-group");
    expect(formGroup.hasClass('input--empty')).to.equal(true);
  });

  it("Should display errors if there's any.", () => {
    insertHTML(`

                  <btrz-field name="testName" type="text" value="" label="label text" :errors="[{'type': 0, 'message': 'Error message goes here'}]"></btrz-field>

`);

    const app = new Vue({
        el: "#app",
        components: {BtrzField}
      }),
    errors = $(".form-group .errors");
    expect(errors.length).to.not.equal(0);
  });

  it("should not display any errors if there's none.", () => {
    insertHTML(`

                  <btrz-field name="testName" type="text" value="" label="label text" :errors="[{'type': 0, 'message': 'Error message goes here'}]"></btrz-field>

`);

    const app = new Vue({
        el: "#app",
        components: {BtrzField}
      }),
    errors = $(".form-group .errors");
    expect(errors.length).to.equal(1);
  });

  it("Should render btrz-toggle specified in content attribute.", () => {
    insertHTML(`

                  <btrz-field name="testName" type="text" content="BtrzToggle" value="" label="label text" :errors="[{'type': 0, 'message': 'Error message goes here'}]"></btrz-field>

`);

    const app = new Vue({
        el: "#app",
        components: {BtrzField}
      }),
    toggle = $(".form-group .btrz-switcher");
    expect(toggle.length).to.equal(1);
  });

  it("Should render btrz-input specified in content attribute.", () => {
    insertHTML(`

                  <btrz-field name="testName" type="text" content="BtrzInput" value="" label="label text" :errors="[{'type': 0, 'message': 'Error message goes here'}]"></btrz-field>

`);

    const app = new Vue({
        el: "#app",
        components: {BtrzField}
      }),
    btrzInput = $(".form-group input");
    expect(btrzInput.length).to.equal(1);
  });
});
<commit_msg>removed unused component<commit_after>import "./setup";

import {expect} from "chai";
import {insertHTML} from "./utils";
import BtrzField from "../src/btrz-field";

describe("BtrzField", () => {
  it("Should render a form-group.", () => {
    insertHTML(`

                  <btrz-field name="testName" type="text" value="testValue"></btrz-field>

`);

    const app = new Vue({
        el: "#app",
        components: {BtrzField}
      }),
    formGroup = $(".form-group");
    expect(formGroup.length).to.equal(1);
  });

  it("Should render correct label.", () => {
    insertHTML(`

                  <btrz-field name="testName" type="text" value="testValue" label="testLabel"></btrz-field>

`);

    const app = new Vue({
        el: "#app",
        components: {BtrzField}
      }),
    label = $(".form-group label");
    expect(label.text()).to.equal("testLabel:");
  });

  it("Should render an empty label if label field is empty.", () => {
    insertHTML(`

                  <btrz-field name="testName" type="testType" value="testValue" label=""></btrz-field>

`);

    const app = new Vue({
        el: "#app",
        components: {BtrzField}
      }),
    label = $(".form-group label");
    expect(label.html().trim()).to.equal(' ');
  });

  it("Should render correct for attribute in the label.", () => {
    insertHTML(`

                  <btrz-field id="123456" name="testName" type="testType" value="testValue" label="true"></btrz-field>

`);

    const app = new Vue({
        el: "#app",
        components: {BtrzField}
      }),
    label = $(".form-group label");
    expect(label.attr("for")).to.equal('123456');
  });

  it("Should have class .input--filled if the input is contains text.", () => {
    insertHTML(`

                  <btrz-field name="testName" type="testType" value="testValue" label="true"></btrz-field>

`);

    const app = new Vue({
        el: "#app",
        components: {BtrzField}
      }),
    formGroup = $(".form-group");
    expect(formGroup.hasClass('input--filled')).to.equal(true);
  });

  it("Should have class .input--empty if the input is empty.", () => {
    insertHTML(`

                  <btrz-field name="testName" type="text" value="" label="label text"></btrz-field>

`);

    const app = new Vue({
        el: "#app",
        components: {BtrzField}
      }),
    formGroup = $(".form-group");
    expect(formGroup.hasClass('input--empty')).to.equal(true);
  });

  it("Should display errors if there's any.", () => {
    insertHTML(`

                  <btrz-field name="testName" type="text" value="" label="label text" :errors="[{'type': 0, 'message': 'Error message goes here'}]"></btrz-field>

`);

    const app = new Vue({
        el: "#app",
        components: {BtrzField}
      }),
    errors = $(".form-group .errors");
    expect(errors.length).to.not.equal(0);
  });

  it("should not display any errors if there's none.", () => {
    insertHTML(`

                  <btrz-field name="testName" type="text" value="" label="label text" :errors="[{'type': 0, 'message': 'Error message goes here'}]"></btrz-field>

`);

    const app = new Vue({
        el: "#app",
        components: {BtrzField}
      }),
    errors = $(".form-group .errors");
    expect(errors.length).to.equal(1);
  });

  it("Should render btrz-toggle specified in content attribute.", () => {
    insertHTML(`

                  <btrz-field name="testName" type="text" content="BtrzToggle" value="" label="label text" :errors="[{'type': 0, 'message': 'Error message goes here'}]"></btrz-field>

`);

    const app = new Vue({
        el: "#app",
        components: {BtrzField}
      }),
    toggle = $(".form-group .btrz-switcher");
    expect(toggle.length).to.equal(1);
  });

  it("Should render btrz-input specified in content attribute.", () => {
    insertHTML(`

                  <btrz-field name="testName" type="text" content="BtrzInput" value="" label="label text" :errors="[{'type': 0, 'message': 'Error message goes here'}]"></btrz-field>

`);

    const app = new Vue({
        el: "#app",
        components: {BtrzField}
      }),
    btrzInput = $(".form-group input");
    expect(btrzInput.length).to.equal(1);
  });
});
<|endoftext|>


<commit_before>/*=esdown=*/'use strict'; var __M; (function(a) { var list = Array(a.length / 2); __M = function require(i) { var m = list[i], f, e; if (typeof m !== 'function') return m.exports; f = m; m = i || !module ? { exports: {} } : module; f(list[i] = m, e = m.exports); if (m.exports !== e && !('default' in m.exports)) m.exports['default'] = m.exports; return m.exports; }; for (var i = 0; i < a.length; i += 2) { var j = Math.abs(a[i]); list[j] = a[i + 1]; if (a[i] >= 0) __M(j); } })([
1, function(m) { m.exports = require("fs") },
2, function(module, exports) {

// pkg2/main.js

},
-5, function(module, exports) {

// b.js
module.exports = { b: "b" };

},
-3, function(module, exports) {

// a.js (legacy)
console.log("before b");
var b = __M(5);
exports.a = "a";
console.log(b.b);

},
-4, function(module, exports) {

// pkg1/index.js

},
0, function(module, exports) {

// root.js
var FS = __M(1);
var pkg2 = __M(2);

console.log("before a");
var a = __M(3);
console.log(a.a);

require("fs");
__M(4);

}]);
<commit_msg>Fix failing bundle test.<commit_after>/*=esdown=*/'use strict'; var __M; (function(a) { var list = Array(a.length / 2); __M = function(i) { var m = list[i], f, e, ee; if (typeof m !== 'function') return m.exports; f = m; m = { exports: i ? {} : exports }; f(list[i] = m, e = m.exports); ee = m.exports; if (ee && ee !== e && !('default' in ee)) ee['default'] = ee; return ee; }; for (var i = 0; i < a.length; i += 2) { var j = Math.abs(a[i]); list[j] = a[i + 1]; if (a[i] >= 0) __M(j); } })([
1, function(m) { m.exports = require("fs") },
2, function(module, exports) {

// pkg2/main.js

},
-5, function(module, exports) {

// b.js
module.exports = { b: "b" };

},
-3, function(module, exports) {

// a.js (legacy)
console.log("before b");
var b = __M(5);
exports.a = "a";
console.log(b.b);

},
-4, function(module, exports) {

// pkg1/index.js

},
0, function(module, exports) {

// root.js
var FS = __M(1);
var pkg2 = __M(2);

console.log("before a");
var a = __M(3);
console.log(a.a);

require("fs");
__M(4);

}]);
<|endoftext|>