code stringlengths 2 1.05M | repo_name stringlengths 5 114 | path stringlengths 4 991 | language stringclasses 1 value | license stringclasses 15 values | size int32 2 1.05M |
|---|---|---|---|---|---|
var dragger = dnd.drag;
var sc = ShiftCaptain || {};
var typing = null;
var typeData = "";
var doneTyping = function () {
if (typeData != "") {
var duration = $("#ShiftDuration");
var exists = duration.find("[value='" + typeData + "']");
if (exists.length) {
duration.val(typeData);
} else {
var isDecimal = true;
try{
parseFloat(typeData).toFixed(1);
} catch (ex) {
isDecimal = false;
console.log("Duration must be a decimal or integer - " + typeData);
}
if (isDecimal) {
var custom = duration.find(".custom");
if (!custom.length) {
custom = $("<option class='custom' value='" + typeData + "'>" + typeData + " hours</option>");
duration.append(custom);
} else {
custom.val(typeData);
custom.text(typeData + " hours");
}
duration.val(typeData);
}
}
typeData = "";
}
};
$(document.body).on('keypress', function (key) {
if (!key.ctrlKey && !key.shiftKey && ((key.charCode >= 48 && key.charCode <= 57) || key.charCode == 46)) {
if (key.charCode == 46) {
typeData += ".";
} else {
typeData += (key.charCode - 48);
}
if (typing != null) {
clearTimeout(typing);
}
typing = setTimeout(function () {
doneTyping();
}, 500);
} else if (typing) {
clearTimeout(typing);
typing = null;
}
});
var openTD = function (s, classname, extra) {
return "<td class='open " + (classname || "") + "' s='" + s + "' " + (extra || "") + "> </td>";
}
var displayError = function (response) {
var errorHolder = $("#Errors");
errorHolder.empty();
var li = $("<li>");
var text = response;
try{
var json = JSON.parse(response);
if (json.error) {
if ($.isArray(json.error)) {
var ul = $("<ul>");
$.each(json.error, function (index, item) {
var ili = $("<li>");
ili.text(this.message || this);
ul.append(ili);
});
errorHolder.append(ul);
return;
} else {
text = json.error;
}
}
} catch (ex) {
debugger;
}
li.text(text);
errorHolder.append($("<ul>").html(li));
sc.app.resizeHeader();
};
var FilterShifts = function (shifts, dayId) {
var filtered = [];
for (var idx = 0; idx < shifts.length; idx++) {
if (shifts[idx].Day == dayId) {
shifts[idx].s = shifts[idx].StartTime.Hours + shifts[idx].StartTime.Minutes / 60;
filtered.push(shifts[idx]);
}
};
return filtered;
};
var getShiftAtTime = function (startTime, data) {
for (var idx = 0; idx < data.length; idx++) {
if (data[idx].s == startTime) {
return data.splice(idx, 1)[0];
}
}
};
var outputTime = function (time) {
return time.Hours + ":" + time.Minutes;
};
var createShiftElement = function (shift, s) {
var cols = shift.Duration * 2;
return addDraggerFunctions('shift', $("<td class='taken draggable' s='" + s + "' colSpan='" + cols + "' shiftid='" + shift.ShiftId + "' starttime='" + outputTime(shift.StartTime) + "' duration='" + shift.Duration + "' userid='" + shift.UserId + "'>" + shift.NickName + "</td>").tooltip('shift', shift));
};
var currentRoomHours = [];
var dayName = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
var makeRow = function (rC, tbody, dayData, s, e, shifts, start, maxEnd, createShiftElement, options) {
options = options || {};
var emptyRow = true;
var tr = $("<tr class='" + dayName[dayData.Day] + "' day='" + dayData.Day + "'><td>" + (rC == 0 ? dayName[dayData.Day] : " ") + "</td></tr>");
for (var notOpen = start; notOpen < s; notOpen += .5) {
tr.append("<td class='closed'> </td>");
}
for (var t = s; t < e; t += .5) {
var shift = getShiftAtTime(t % 24, shifts);
if (shift) {
emptyRow = false;
tr.append(createShiftElement(shift, t % 24));
t += shift.Duration - .5;
} else {
tr.append(openTD(t % 24));
}
}
for (var notOpen = e; notOpen < maxEnd; notOpen += .5) {
tr.append("<td class='closed' s='" + (notOpen % 24) + "'> </td>");
}
tbody.append(tr);
if (rC == 0) {
tr.addClass('first-row');
}
if (shifts.length > 0) {
//recursive call
if (emptyRow) {
console.log("Unable to schedule the rest of the shifts");
console.log(shifts);
} else {
makeRow(++rC, tbody, dayData, s, e, shifts, start, maxEnd, createShiftElement, options);
}
} else if (!emptyRow) {
if (options.empty_row != false) {
makeRow(++rC, tbody, dayData, s, e, shifts, start, maxEnd, createShiftElement, options);
}
} else {
tr.addClass('empty-row');
}
};
$("#shiftHolder table").on("table-ready page-ready", function (event) {
this["-" + event.type] = true;
if (this["-table-ready"] && this["-page-ready"] && !this["-dragger-init"]) {
this["-dragger-init"] = true;
dragger.init();
}
});
var createShiftTable = function (roomHours, shifts, createShiftElement, options) {
options = options || {};
var sh = $("#shiftHolder table");
sh.empty();
var minStart = null;
var maxEnd = null;
$.each(roomHours, function (index) {
if (minStart == null || (this.StartTime.Hours < minStart.Hours && (this.StartTime.Hours + this.StartTime.Minutes / 60 < minStart.Hours + minStart.Minutes / 60))) {
minStart = this.StartTime;
}
var end = this.StartTime.Hours + (this.StartTime.Minutes / 60) + this.Duration;
if (maxEnd == null || end > maxEnd) {
maxEnd = end;
}
});
var start = minStart.Hours + minStart.Minutes / 60;
if (start == null || maxEnd == null || start > maxEnd) {
return;
}
var topRow = $("<tr><th> </th></tr>");
for (var idx = start; idx < maxEnd; idx += .5) {
topRow.append($("<th class='" + (idx >= 13 && idx < 24 ? "PM" : "AM") + "'>" + ((idx >= 13 ? (idx >= 24 ? idx - 24 : idx - 12) : idx) | 0) + ":" + (idx % 1 == 0.5 ? "30" : "00") + "</th>"));
}
var thead = $("<thead></thead>").append(topRow);
//var theadFixed = thead.clone();
var theadBottom = thead.clone();
sh.append(thead);
//sh.append(thead.css("visibility", "hidden"));
//sh.append(theadFixed.css("position", "fixed"));
var tbody = $("<tbody></tbody>");
var borderRow = null;
for (var idx = 0; idx < roomHours.length; idx++) {
var dayroomHours = roomHours[idx];
var dayShifts = FilterShifts(shifts, dayroomHours.Day);
if (dayShifts.length > 0) {
window.a = dayShifts;
}
dayroomHours.s = dayroomHours.StartTime.Hours + dayroomHours.StartTime.Minutes / 60;
dayroomHours.e = dayroomHours.s + dayroomHours.Duration;
dayroomHours.MinStart = start;
dayroomHours.MaxEnd = maxEnd;
makeRow(0, tbody, dayroomHours, dayroomHours.s, dayroomHours.e, dayShifts, start, maxEnd, createShiftElement, options);
if (idx < roomHours.length - 1) {
//add border row
if (options.border_row != false && !borderRow) {
borderRow = $("<tr class='row-border'><td> </td></tr>");
for (var notOpen = start; notOpen < maxEnd; notOpen += .5) {
borderRow.append("<td t='" + notOpen + "'> </td>");
}
}
if (borderRow) {
tbody.append(borderRow.clone(true));
}
}
}
sh.append(tbody);
//theadFixed.css('top', thead.offset().top);
//theadFixed.find("th:first").width(tbody.find("tr:first-child td:first-child").width()).css('display', 'block');
sh.append(theadBottom);
if (sh.width() > $("#shiftHolder").width()) {
$("#shiftHolder").width(sh.width() + 30);
}
sh.trigger("table-ready");
};
var replaceWithOpen = function ($element, temp) {
var s = parseFloat($element.attr("s"));
var replacement = "" + openTD(s, temp?"temp": "");
var span = $element.attr('colSpan');
for (var idx = 0; idx < span - 1 ; idx++) {
s += .5;
replacement += openTD(s, temp ? "temp" : "");
}
var $replacement = $(replacement);
var next = $element.nextSibling;
$element.replaceWith($replacement, true);
console.log($replacement);
return $replacement;
};
var replaceDropElementWithNewShift = function ($newShift, $dropElement) {
var span = $newShift.attr('colSpan');
var next = $dropElement;
for (var idx = 0; idx < span ; idx++) {
var prev = next;
next = next.next();
if (idx != 0) {
prev.remove();
}
}
$dropElement.replaceWith($newShift);
dragger.reinit($newShift);
return $newShift;
};
var updateTemp = function () {
$(".temp").each(function (index) {
var $elem = $(this);
$elem.removeClass("temp");
});
};
sc.app = sc.app || {};
$.extend(sc.app, {
createShiftTable: createShiftTable,
displayError: displayError,
makeRow: makeRow,
replaceWithOpen: replaceWithOpen,
replaceDropElementWithNewShift: replaceDropElementWithNewShift,
setCurrentHours: function (roomHours) {
currentRoomHours = roomHours;
},
updateTemp: updateTemp
});
| adabadyitzaboy/ShiftCaptain | ShiftCaptain/obj/Release/Package/PackageTmp/Scripts/CommonShift.js | JavaScript | mit | 9,831 |
'use strict';
var EC = protractor.ExpectedConditions;
var lib = require('./lib');
describe('data management', function() {
it('should preserve schema and document across route changes', function() {
browser.get('#/version/draft-04/markup/json');
var randomSchema = Math.random().toString(36).replace(/[^a-z]+/g, '');
var randomDocument = Math.random().toString(36).replace(/[^a-z]+/g, '');
// Reset
element(by.buttonText('Reset')).click();
// Type something RANDOM in schema and document
var schemaElement = element(by.css('validator[identifier=schema] textarea'));
schemaElement.clear();
schemaElement.sendKeys(randomSchema);
expect(schemaElement.evaluate('$ctrl.myDoc')).toEqual(randomSchema);
var documentElement = element(by.css('validator[identifier=document] textarea'));
documentElement.clear();
documentElement.sendKeys(randomDocument);
expect(documentElement.evaluate('$ctrl.myDoc')).toEqual(randomDocument);
// Select a different version (use the button!)
// Open the spec version menu
element(by.css('#specVersionDropdown')).click();
// SUSPICION - the samples menu displays outside angular's digest cycle. So protractor doesn't really know if it's there
browser.wait(EC.visibilityOf(element(by.css('ul[aria-labelledby=specVersionDropdown]'))), 250);
// Select a different version
element(by.linkText('draft-03')).click();
browser.wait(lib.isDoneWorking, 2500);
// Check the RANDOM stuff is still there
expect(schemaElement.evaluate('$ctrl.myDoc')).toEqual(randomSchema);
expect(documentElement.evaluate('$ctrl.myDoc')).toEqual(randomDocument);
});
it('should preserve schema and document across page reloads', function() {
browser.get('#/version/draft-04/markup/json');
var randomSchema = Math.random().toString(36).replace(/[^a-z]+/g, '');
var randomDocument = Math.random().toString(36).replace(/[^a-z]+/g, '');
// Reset
element(by.buttonText('Reset')).click();
// Type something RANDOM in schema and document
var schemaElement = element(by.css('validator[identifier=schema] textarea'));
schemaElement.clear();
schemaElement.sendKeys(randomSchema);
expect(schemaElement.evaluate('$ctrl.myDoc')).toEqual(randomSchema);
var documentElement = element(by.css('validator[identifier=document] textarea'));
documentElement.clear();
documentElement.sendKeys(randomDocument);
expect(documentElement.evaluate('$ctrl.myDoc')).toEqual(randomDocument);
// Reload it
browser.refresh();
browser.wait(lib.isDoneWorking, 2500);
// Check the RANDOM stuff is still there
schemaElement = element(by.css('validator[identifier=schema] textarea'));
documentElement = element(by.css('validator[identifier=document] textarea'));
expect(schemaElement.evaluate('$ctrl.myDoc')).toEqual(randomSchema);
expect(documentElement.evaluate('$ctrl.myDoc')).toEqual(randomDocument);
});
}); | HotelDon/jsonschemalint | e2e-tests/data.spec.js | JavaScript | mit | 2,981 |
/*
* Copyright 2017 Hewlett Packard Enterprise Development Company, L.P.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
*/
define([
'underscore',
'backbone',
'i18n!find/nls/bundle',
'find/idol/app/page/search/results/idol-questions-view',
'find/idol/app/model/answer-bank/idol-answered-questions-collection'
], function(_, Backbone, i18n, IdolQuestionsView, IdolAnsweredQuestionsCollection) {
'use strict';
describe('Idol Questions View', function() {
beforeEach(function() {
this.view = new IdolQuestionsView({
queryModel: new Backbone.Model({
queryText: 'This is some query text'
}),
loadingTracker: {
questionsFinished: true
},
clearLoadingSpinner: _.noop
});
this.collection = IdolAnsweredQuestionsCollection.instances[0];
});
afterEach(function() {
IdolAnsweredQuestionsCollection.reset();
});
it('should initialize a document collection', function() {
expect(IdolAnsweredQuestionsCollection.instances.length).toBeGreaterThan(0);
expect(this.collection.fetch).not.toHaveBeenCalled();
});
describe('and when prompted to fetch', function() {
beforeEach(function() {
this.view.fetchData();
});
it('should call fetch on the answered questions collection', function() {
expect(this.collection.fetch).toHaveBeenCalled();
expect(this.collection.fetch.calls.mostRecent().args[0].data).toEqual(
{
maxResults: 1,
text: 'This is some query text'
}
)
});
describe('and the fetch returns successfully', function() {
beforeEach(function() {
this.collection.add(new Backbone.Model({
question: 'Is this the question?',
answer: 'Yes it is',
systemName: 'answerbank0'
}));
this.collection.fetch.calls.mostRecent().args[0].success();
});
it('should have displayed the answered question', function() {
expect(this.view.$('.result-header').text().trim())
.toEqual(i18n['search.answeredQuestion.question'] + 'Is this the question?');
expect(this.view.$('.summary-text').text().trim())
.toEqual(i18n['search.answeredQuestion.answer'] + 'Yes it is');
});
it('the title attribute should contain the system name', function() {
expect(this.view.$('.answered-question').attr('data-original-title'))
.toEqual(i18n['search.answeredQuestion.systemName']('answerbank0'));
});
});
});
});
});
| hpe-idol/find | webapp/idol/src/test/js/spec/app/page/search/results/idol-questions-view.js | JavaScript | mit | 3,117 |
'use strict'
let crypto = require('crypto')
let bodyParser = require('body-parser')
module.exports = bodyParser.json({
verify: (req, res, buf, encoding) => {
// sha1 content
var hash = crypto.createHash('sha1')
hash.update(buf)
req.hasha = hash.digest('hex')
console.log('hash', req.hasha)
// get rawBody
req.rawBody = buf.toString()
console.log('rawBody', req.rawBody)
}
})
| andyfleming/mc-core | src/api/middleware/raw-body.js | JavaScript | mit | 416 |
var users = {
searchByZipcode: function(zipcode) {
// search legistalors by zipcode (default to Boulder, 80301)
// ref: https://sunlightlabs.github.io/congress/legislators.html
var zipcode = zipcode || '80301'
$.get("https://congress.api.sunlightfoundation.com/legislators/locate?zip=" + zipcode, apikey, function(data) {
console.log('got ' + data)
if (data.results){
$.get("/twitter/users/list.jade", function(template) {
var html = jade.render(template, {
data: data
})
console.log(html)
$("#list").html(html)
})
}
})
},
searchByName: function(name) {
// search legistalors by name
// ref: https://sunlightlabs.github.io/congress/legislators.html
$.get("https://congress.api.sunlightfoundation.com/legislators?query=" + name, apikey, function(data) {
$.get("/twitter/users/list.jade", function(template) {
var html = jade.render(template, {
data: data
})
$("#list").html(html)
})
})
},
searchByChamber: function(chamber) {
// search legistalors by chamber
// ref: https://sunlightlabs.github.io/congress/legislators.html
$.get("https://congress.api.sunlightfoundation.com/legislators?chamber=" + chamber, apikey, function(data) {
$.get("/twitter/users/list.jade", function(template) {
var html = jade.render(template, {
data: data
})
$("#list").html(html)
})
})
},
load: function() {
$.get("/twitter/users/ui.jade", function(template) {
var html = jade.render(template)
$("#ui").html(html)
})
// default search results
legislators.searchByChamber('senate')
}
} | mazdeh/social-trends | build/users/index.js | JavaScript | mit | 2,042 |
angular.module('displayOptionsDirectives', [])
/*displays text for display options obect
examples :
<display-options text="main.displayOptions.options.tcpa_optin_text" show="main.displayOptions.options.offer_tcpa_optin"></display-options>
or
<display-options text="main.displayOptions.options.tcpa_optin_text"></display-options><br />
<div display-options show="main.displayOptions.options.show_bundled_price" text="main.displayOptions.options.show_bundled_price"></div><br />
or
<display-options show="main.displayOptions.options.show_air_car_hotel_bookings" text="main.displayOptions.options.show_air_car_hotel_bookings"></display-options>
if the show attribute is present and false it will hide the element.
if the show attribute is not present or true it will display the element.
*/
.directive('displayOptions', function () {
return {
restrict: 'EA',
template: "{{text}}",
scope: {
text: "=text",
show: "=show",
},
link: function (scope, element, attrs) {
if (attrs.text || scope.text) {
return true;
} else {
element.addClass('hide');
return;
}
if (!scope.show || !attrs.show || (attrs.show && scope.show == 'true' || scope.show == true)) {
return true;
}
else {
element.addClass('hide');
return;
}
}
};
}); | tazmanrising/IntiotgAngular | Companies/ICE/AirEngine/Ovs.Hotel.Ui/apps/travel/hotel/displayOptions-directives.js | JavaScript | mit | 1,576 |
(function () {
WinJS.Namespace.define("Converters", {
boolToVisibilityConverter: WinJS.Binding.converter(function (answered) {
return answered ? "" : "none";
}),
inverseBoolToVisibilityConverter: WinJS.Binding.converter(function (answered) {
return !answered ? "" : "none";
}),
showingQuestionToVisibilityConverter: WinJS.Binding.converter(function (state) {
return state === "showingQuestion" ? "" : "none";
}),
showingAnswerToVisibilityConverter: WinJS.Binding.converter(function (state) {
return state === "showingAnswer" ? "" : "none";
}),
loadingToVisibilityConverter: WinJS.Binding.converter(function (state) {
return state === "loading" ? "" : "none";
}),
});
}()); | Microsoft-Web/WebCampTrainingKit | Presentation/05-HTTP-Services/GeekQuiz-Web-API-Universal-Windows/source/end/GeekQuiz/js/converters.js | JavaScript | mit | 841 |
/*
Copyright (c) 2004-2012, The Dojo Foundation All Rights Reserved.
Available via Academic Free License >= 2.1 OR the modified BSD license.
see: http://dojotoolkit.org/license for details
*/
if(!dojo._hasResource['GeoMOOSE.UI.Toolbar']){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource['GeoMOOSE.UI.Toolbar'] = true;
/*
Copyright (c) 2009-2012, Dan "Ducky" Little & GeoMOOSE.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/*
* Class: GeoMOOSE.UI.Toolbar
* Create a handy toolbar.
*/
dojo.provide('GeoMOOSE.UI.Toolbar');
dojo.require('dijit.Toolbar');
dojo.require('dijit.TooltipDialog');
dojo.require('GeoMOOSE.Tool');
dojo.declare('GeoMOOSE.UI.Toolbar', [dijit.Toolbar], {
activeLayer: null,
untoggleOthers: function() {
for(var tool_name in this.parent.tools) {
var tool = this.parent.tools[tool_name];
if(tool != this) {
tool.set('checked', false);
}
}
},
_deactivateTools: function() {
for(var tool_name in Tools) {
Tools[tool_name].deactivate();
}
},
_internalToolAction: function() {
if(GeoMOOSE.isDefined(Tools[this.action])) {
if(this.selectable) {
this._deactivateTools();
}
Tools[this.action].activate();
} else {
GeoMOOSE.warning('The tool "'+this.action+'" is undefined!');
}
},
_serviceToolAction: function() {
GeoMOOSE.startService(this.service_name);
},
_javascriptToolAction: function() {
eval(this.stuff_to_do);
},
_layerToolAction: function() {
GeoMOOSE.activateLayerTool(this.action);
},
_addTool: function(parent, tool_xml, asMenuItem) {
var tool_type = tool_xml.getAttribute('type');
var name = tool_xml.getAttribute('name');
var selectable = parseBoolean(tool_xml.getAttribute('selectable'), true);
var tool = null;
if(asMenuItem === true) {
if(selectable) {
tool = new GeoMOOSE.ToolMenu({'tool_xml': tool_xml, 'parent' : this});
dojo.connect(tool, 'onClick', this.untoggleOthers);
} else {
tool = new GeoMOOSE.UnselectableToolMenu({'tool_xml' : tool_xml, 'parent' : this});
}
} else {
if(selectable) {
tool = new GeoMOOSE.Tool({'tool_xml': tool_xml, 'parent' : this});
dojo.connect(tool, 'onClick', this.untoggleOthers);
} else {
tool = new GeoMOOSE.UnselectableTool({'tool_xml' : tool_xml, 'parent' : this});
}
}
if(tool != null) {
/*
* TODO : The way tool types are defined is very enumerated. This needs
* to be migrated to being more modular in 3.0 ... of course ... that will
* fundamentally break mapbook definitions for many tools.
*/
if(tool_type == 'internal') {
tool.action = tool_xml.getAttribute('action');
dojo.connect(tool, 'onClick', this._internalToolAction);
} else if(tool_type == 'service') {
tool.service_name = tool_xml.getAttribute('service');
dojo.connect(tool, 'onClick', this._serviceToolAction);
} else if(tool_type == 'javascript') {
tool.stuff_to_do = OpenLayers.Util.getXmlNodeValue(tool_xml);
dojo.connect(tool, 'onClick', this._javascriptToolAction);
} else if(tool_type == 'layer') {
tool.action = tool_xml.getAttribute('action');
dojo.connect(tool, 'onClick', this._layerToolAction);
}
tool._deactivateTools = this._deactivateTools;
this.parent = this;
this.tools[name] = tool;
parent.addChild(tool);
}
},
onMapbookLoaded: function(mapbook) {
var toolbar_xml = mapbook.getElementsByTagName('toolbar')[0];
this.tools = {};
for(var i = 0, len = toolbar_xml.childNodes.length; i < len; i++) {
var node = toolbar_xml.childNodes[i];
if(node.tagName && node.tagName == 'tool') {
this._addTool(this, node);
} else if(node.tagName && node.tagName == 'drawer') {
var drawer_class = node.getAttribute('icon-class');
if(!GeoMOOSE.isDefined(drawer_class)) {
drawer_class = 'spite-control sprite-control-down';
}
var label = '';
var show_label = parseBoolean(node.getAttribute('show-label'), CONFIGURATION.toolbar.show_labels);
if(show_label) {
label = node.getAttribute('title');
}
var drawer_menu = new dijit.Menu();
var drawer = new dijit.form.DropDownButton({
'label' : label,
'iconClass' : drawer_class,
'dropDown' : drawer_menu
});
this.addChild(drawer);
/* I really don't feel like writing recursion. */
var tools = node.getElementsByTagName('tool');
for(var t = 0, tt = tools.length; t < tt; t++) {
this._addTool(drawer_menu, tools[t], true);
}
}
}
this.layout.resize();
},
activeMapSource: null,
onActivateMapSource: function(map_source_name) {
this.activeMapSource = map_source_name;
}
});
}
| henry-gobiernoabierto/geomoose | htdocs/libs/dojo/release/geomoose2.6/gm/GeoMOOSE/UI/Toolbar.js | JavaScript | mit | 5,654 |
var zrUtil = require('zrender/lib/core/util');
module.exports = function (ecModel) {
var processedMapType = {};
ecModel.eachSeriesByType('map', function (mapSeries) {
var mapType = mapSeries.get('map');
if (processedMapType[mapType]) {
return;
}
var mapSymbolOffsets = {};
zrUtil.each(mapSeries.seriesGroup, function (subMapSeries) {
var geo = subMapSeries.coordinateSystem;
var data = subMapSeries.originalData;
if (subMapSeries.get('showLegendSymbol') && ecModel.getComponent('legend')) {
data.each('value', function (value, idx) {
var name = data.getName(idx);
var region = geo.getRegion(name);
// If input series.data is [11, 22, '-'/null/undefined, 44],
// it will be filled with NaN: [11, 22, NaN, 44] and NaN will
// not be drawn. So here must validate if value is NaN.
if (!region || isNaN(value)) {
return;
}
var offset = mapSymbolOffsets[name] || 0;
var point = geo.dataToPoint(region.center);
mapSymbolOffsets[name] = offset + 1;
data.setItemLayout(idx, {
point: point,
offset: offset
});
});
}
});
// Show label of those region not has legendSymbol(which is offset 0)
var data = mapSeries.getData();
data.each(function (idx) {
var name = data.getName(idx);
var layout = data.getItemLayout(idx) || {};
layout.showLabel = !mapSymbolOffsets[name];
data.setItemLayout(idx, layout);
});
processedMapType[mapType] = true;
});
};
| ytbryan/chart | node_modules/echarts/lib/chart/map/mapSymbolLayout.js | JavaScript | mit | 2,073 |
'use strict';
var util = require('util'),
common = require('./common'),
Session = require('./session');
var ClientSession = function(options) {
Session.call(this, options);
};
util.inherits(ClientSession, Session);
ClientSession.validParams = function(params) {
if (!common.validParams(params)) return false;
if (params.hasOwnProperty('client_max_window_bits')) {
if (common.VALID_WINDOW_BITS.indexOf(params.client_max_window_bits) < 0)
return false;
}
return true;
};
ClientSession.prototype.generateOffer = function() {
var offer = {};
if (this._acceptNoContextTakeover)
offer.client_no_context_takeover = true;
if (this._acceptMaxWindowBits !== undefined) {
if (common.VALID_WINDOW_BITS.indexOf(this._acceptMaxWindowBits) < 0) {
throw new Error('Invalid value for maxWindowBits');
}
offer.client_max_window_bits = this._acceptMaxWindowBits;
} else {
offer.client_max_window_bits = true;
}
if (this._requestNoContextTakeover)
offer.server_no_context_takeover = true;
if (this._requestMaxWindowBits !== undefined) {
if (common.VALID_WINDOW_BITS.indexOf(this._requestMaxWindowBits) < 0) {
throw new Error('Invalid value for requestMaxWindowBits');
}
offer.server_max_window_bits = this._requestMaxWindowBits;
}
return offer;
};
ClientSession.prototype.activate = function(params) {
if (!ClientSession.validParams(params)) return false;
if (this._acceptMaxWindowBits && params.client_max_window_bits) {
if (params.client_max_window_bits > this._acceptMaxWindowBits) return false;
}
if (this._requestNoContextTakeover && !params.server_no_context_takeover)
return false;
if (this._requestMaxWindowBits) {
if (!params.server_max_window_bits) return false;
if (params.server_max_window_bits > this._requestMaxWindowBits) return false;
}
this._ownContextTakeover = !(this._acceptNoContextTakeover || params.client_no_context_takeover);
this._ownWindowBits = Math.min(
this._acceptMaxWindowBits || common.MAX_WINDOW_BITS,
params.client_max_window_bits || common.MAX_WINDOW_BITS
);
this._peerContextTakeover = !params.server_no_context_takeover;
this._peerWindowBits = params.server_max_window_bits || common.MAX_WINDOW_BITS;
return true;
};
module.exports = ClientSession;
| ocadni/citychrone | .build/bundle/programs/server/npm/node_modules/meteor/socket-stream-client/node_modules/permessage-deflate/lib/client_session.js | JavaScript | mit | 2,331 |
version https://git-lfs.github.com/spec/v1
oid sha256:5eb0378c922c1a985716bab50303f10c4720ce203efa15a57b54d143fcd547aa
size 24474
| yogeshsaroya/new-cdnjs | ajax/libs/yui/3.17.1/autocomplete-list/autocomplete-list.js | JavaScript | mit | 130 |
#!/usr/bin/env node
/* jshint globalstrict: true */
/* global require */
/* global module */
/* global __dirname */
/* global process */
"use strict";
var fs = require("fs");
var config = require("../lib/config");
var pathutils = require("../lib/pathutils");
var Handlebars = require("handlebars");
var config_files = [
pathutils.join([__dirname, "..", "config", "default.yml"])
];
var args = require("../lib/cli/args")({
});
function help() {
var template_path = fs.realpathSync(pathutils.join([
__dirname,
"..",
"resources",
"server-help.txt"
]));
var source = fs.readFileSync(template_path).toString("utf-8");
var template = Handlebars.compile(source);
return template(info);
}
if (args.dev) {
config_files.push(pathutils.join([
__dirname,
"..",
"config",
"development.yml"
]));
config_files.push(pathutils.join([
__dirname,
"..",
"config",
"development_alias.yml"
]));
}
if (args['config-dir']) {
fs.readdirSync(args['config-dir']).filter(function(f){
return /\.(json|yml)$/.test(f);
}).forEach(function(f){
config_files.push(pathutils.join([args['config-dir'], f]));
});
}
if (args.config) {
config_files = config_files.concat(args.config);
}
config.load(config_files);
var get_info = require("../lib/info");
var info = get_info();
if (args.help) {
process.stdout.write(help());
process.exit();
}
require("../lib/server");
| neffets/converjon | bin/converjon.js | JavaScript | mit | 1,504 |
require('../spec_helper');
import {SimpleAltTabs, SimpleTabs, Tab, BaseTabs, LeftTabs} from '../../../src/pivotal-ui-react/tabs/tabs';
import EventEmitter from 'node-event-emitter';
import {itPropagatesAttributes} from '../support/shared_examples';
describe('Tabs', function() {
afterEach(function() {
React.unmountComponentAtNode(root);
});
describe('BaseTabs', function() {
// We are using tab-simple here because there are only two options for tabType. However,
// nothing about SimpleTabs is being used, and any string would work, were it valid.
const tabType = 'tab-simple';
let emitter;
describe('props', function() {
let onSelectSpy;
beforeEach(function() {
onSelectSpy = jasmine.createSpy('onSelectSpy');
React.render(
<BaseTabs defaultActiveKey={2} tabType={tabType} className="test-class" id="test-id" style={{opacity: 0.5}}
responsiveBreakpoint="md" smallScreenClassName="small-class" largeScreenClassName="large-class"
onSelect={onSelectSpy}>
<Tab eventKey={1} title="Tab1">Content1</Tab>
<Tab eventKey={2} title="Tab2">Content2</Tab>
</BaseTabs>,
root);
});
itPropagatesAttributes('#root > div', {className: 'test-class', id: 'test-id', style: {opacity: '0.5'}});
it('sets the responsive breakpoint', function() {
expect(`.${tabType}`).toHaveClass('hidden-md');
expect('.panel-group').toHaveClass('visible-md-block');
});
it('passes screen-size specific classes', function() {
expect(`.${tabType}`).toHaveClass('large-class');
expect('.panel-group').toHaveClass('small-class');
});
it('uses the supplied onSelect method when clicking on large-screen tabs', function() {
$(`.${tabType} li a:eq(0)`).simulate('click');
expect(onSelectSpy).toHaveBeenCalled();
});
it('uses the supplied onSelect method when clicking on small-screen tabs', function() {
$(`.panel-group .panel-title a:eq(0)`).simulate('click');
expect(onSelectSpy).toHaveBeenCalled();
});
it('sets up the correct aria-controls relationship', function() {
let pane1 = $(root).find(`.${tabType} .tab-pane:first`);
expect(pane1.length).toEqual(1);
expect(pane1.attr('id')).toBeTruthy();
expect(`.${tabType} nav ul.nav.nav-tabs li:first a`).toHaveAttr('aria-controls', pane1.attr('id'));
});
});
describe('default behavior', function() {
beforeEach(function() {
emitter = new EventEmitter();
const TestComponent = React.createClass({
getInitialState() {
return {defaultActiveKey: 2};
},
componentDidMount() {
emitter.on('changeActiveKey', (key) => this.setState({defaultActiveKey: key}));
},
render() {
return (
<BaseTabs defaultActiveKey={this.state.defaultActiveKey} tabType={tabType}>
<Tab eventKey={1} title="Tab1">Content1</Tab>
<Tab eventKey={2} title="Tab2">Content2</Tab>
</BaseTabs>
);
}
});
React.render(<TestComponent />, root);
});
it('creates tabs in the correct container', function() {
expect(`.${tabType} nav ul.nav.nav-tabs li.active`).toContainText('Tab2');
expect(`.${tabType} .tab-content .tab-pane.fade.active.in`).toContainText('Content2');
});
describe('for screens greater than the responsiveBreakpoint', function() {
it('displays tabs in a simple tab container', function() {
expect(`.hidden-xs.${tabType} nav li.active`).toContainText('Tab2');
expect(`.hidden-xs.${tabType} .tab-content`).toContainText('Content2');
});
});
describe('for screens smaller than the responsiveBreakpoint', function() {
it('renders an accordion', function() {
expect('.visible-xs-block.panel-group').toExist();
});
it('renders headers for each tab', function() {
expect('.visible-xs-block.panel-group .panel-title:eq(0)').toContainText('Tab1');
expect('.visible-xs-block.panel-group .panel-title:eq(1)').toContainText('Tab2');
expect('.visible-xs-block.panel-group .panel-title a:eq(1)').toHaveAttr('aria-expanded', 'true');
});
it('renders content for each tab', function() {
expect('.visible-xs-block.panel-group .panel-collapse:eq(0)').toContainText('Content1');
expect('.visible-xs-block.panel-group .panel-collapse:eq(1)').toContainText('Content2');
expect('.visible-xs-block.panel-group .panel-collapse:eq(1)').toHaveClass('in');
});
});
describe('when switching tabs', function() {
it('switches tabs in both small-screen and large-screen tabs', function() {
$('.hidden-xs li:eq(0) a').simulate('click');
expect('.hidden-xs li.active').toContainText('Tab1');
expect('.visible-xs-block .panel-title a[aria-expanded=true]').toContainText('Tab1');
$('.visible-xs-block .panel-title:eq(1) a').simulate('click');
expect('.hidden-xs li.active').toContainText('Tab2');
expect('.visible-xs-block .panel-title a[aria-expanded=true]').toContainText('Tab2');
});
});
describe('changing the defaultActiveKey props', function() {
beforeEach(function() {
emitter.emit('changeActiveKey', 1);
});
it('updates the current open tab', function() {
expect('.hidden-xs li.active').toContainText('Tab1');
expect('.visible-xs-block .panel-title a[aria-expanded=true]').toContainText('Tab1');
});
});
it('sets up the correct aria-controls relationship', function() {
let pane1 = $(root).find(`.${tabType} .tab-pane:first`);
expect(pane1.length).toEqual(1);
expect(pane1.attr('id')).toBeTruthy();
expect(`.${tabType} nav ul.nav.nav-tabs li:first a`).toHaveAttr('aria-controls', pane1.attr('id'));
});
});
describe('positioning', function() {
function renderTabs(props = {}) {
React.render(
<LeftTabs defaultActiveKey={1} {...props}>
<Tab eventKey={1} title="Tab1">Content1</Tab>
<Tab eventKey={2} title="Tab2">Content2</Tab>
</LeftTabs>,
root);
}
it('should render tabs stacked on the left', function() {
renderTabs({position: 'left', tabWidth: 2, paneWidth: 7});
expect('.hidden-xs nav ul').toHaveClass('nav-stacked');
});
});
});
describe('SimpleTabs', function() {
it('renders without blowing up', function() {
React.render(
<SimpleTabs defaultActiveKey={1}>
<Tab eventKey={1} title="Tab1">Content1</Tab>
<Tab eventKey={2} title="Tab2">Content2</Tab>
</SimpleTabs>, root);
expect('.tab-simple').toExist();
});
it('renders the BaseTabs component with tabType="tab-simple"', function() {
const result = shallowRender(
<SimpleTabs>
I am children
</SimpleTabs>
);
expect(result.type).toEqual(BaseTabs);
expect(result.props.tabType).toEqual('tab-simple');
expect(result.props.children).toEqual('I am children');
});
it('passes all properties', function() {
const onSelect = jasmine.createSpy();
const result = shallowRender(
<SimpleTabs defaultActiveKey={1}
responsiveBreakpoint="sm"
largeScreenClassName="lgclass"
smallScreenClassName="smclass"
onSelect={onSelect}>
</SimpleTabs>
);
expect(result.props.defaultActiveKey).toEqual(1);
expect(result.props.responsiveBreakpoint).toEqual('sm');
expect(result.props.smallScreenClassName).toEqual('smclass');
expect(result.props.largeScreenClassName).toEqual('lgclass');
expect(result.props.onSelect).toEqual(onSelect);
});
});
describe('SimpleAltTabs', function() {
it('should add the class tab-simple to large screen tabs', function() {
React.render(
<SimpleAltTabs defaultActiveKey={1}>
<Tab eventKey={1} title="Tab1">Content1</Tab>
<Tab eventKey={2} title="Tab2">Content2</Tab>
</SimpleAltTabs>, root);
expect('.tab-simple-alt').toExist();
});
it('renders the BaseTabs component with tabType="tab-simple-alt"', function() {
const result = shallowRender(
<SimpleAltTabs>
I am children
</SimpleAltTabs>
);
expect(result.type).toEqual(BaseTabs);
expect(result.props.tabType).toEqual('tab-simple-alt');
expect(result.props.children).toEqual('I am children');
});
it('passes all properties', function() {
const onSelect = jasmine.createSpy();
const result = shallowRender(
<SimpleAltTabs defaultActiveKey={1}
responsiveBreakpoint="sm"
largeScreenClassName="lgclass"
smallScreenClassName="smclass"
onSelect={onSelect}>
</SimpleAltTabs>
);
expect(result.props.defaultActiveKey).toEqual(1);
expect(result.props.responsiveBreakpoint).toEqual('sm');
expect(result.props.smallScreenClassName).toEqual('smclass');
expect(result.props.largeScreenClassName).toEqual('lgclass');
expect(result.props.onSelect).toEqual(onSelect);
});
});
describe('LeftTabs', function() {
it('renders the BaseTabs component with tabType="tab-left"', function() {
const result = shallowRender(
<LeftTabs>
I am children
</LeftTabs>
);
expect(result.type).toEqual(BaseTabs);
expect(result.props.position).toEqual('left');
expect(result.props.tabType).toEqual('tab-left');
expect(result.props.children).toEqual('I am children');
});
it('passes all properties', function() {
const onSelect = jasmine.createSpy();
const result = shallowRender(
<LeftTabs defaultActiveKey={1}
responsiveBreakpoint="sm"
largeScreenClassName="lgclass"
smallScreenClassName="smclass"
onSelect={onSelect}>
</LeftTabs>
);
expect(result.props.defaultActiveKey).toEqual(1);
expect(result.props.responsiveBreakpoint).toEqual('sm');
expect(result.props.smallScreenClassName).toEqual('smclass');
expect(result.props.largeScreenClassName).toEqual('lgclass');
expect(result.props.onSelect).toEqual(onSelect);
});
describe('when props are passed for tabWidth and paneWidth', function() {
it('passes the provided column sizes tp BaseTabs', function() {
const result = shallowRender(
<LeftTabs tabWidth={4} paneWidth={6}/>
);
expect(result.props.tabWidth).toEqual(4);
expect(result.props.paneWidth).toEqual(6);
});
});
describe('when tabWidth is passed and paneWidth is not', function() {
it('passes the correct column sizes to BaseTabs', function() {
const result = shallowRender(
<LeftTabs tabWidth={4}/>
);
expect(result.props.tabWidth).toEqual(4);
expect(result.props.paneWidth).toEqual(20);
});
});
describe('when neither tabWidth nor paneWidth are passed', function() {
it('passes the correct column sizes to BaseTabs', function() {
const result = shallowRender(
<LeftTabs />
);
expect(result.props.tabWidth).toEqual(6);
expect(result.props.paneWidth).toEqual(18);
});
});
});
});
| CanopyCloud/pivotal-ui | spec/pivotal-ui-react/tab/tab_spec.js | JavaScript | mit | 11,791 |
import ExecutionEnvironment from 'exenv'
export const appendUrl = (url) => {
//there is no point of working with pushState if there is no DOM
if (!ExecutionEnvironment.canUseDOM) {
return
}
//history API behaves differntly if current url ends with "/" or not, so it's safer
//to use absolute url
const currentLocation = window.location.href
if (currentLocation.endsWith('/')) {
window.history.pushState(null, null, `${currentLocation}${url}`)
} else {
window.history.pushState(null, null, `${currentLocation}/${url}`)
}
}
| Restuta/rcn.io | src/client/utils/history.js | JavaScript | mit | 557 |
export default `flf2a$ 6 5 15 1 1
rectangles.flf by David Villegas <mnementh@netcom.com> 12/94
$$@
$$@
$$@
$$@
$$@
$$@@
__ @
| |@
| |@
|__|@
|__|@
@@
_ _ @
| | |@
|_|_|@
$$$ @
$$$ @
$$$ @@
_ _ @
_| | |_ @
|_ _|@
|_ _|@
|_|_| @
@@
_ @
_| |_ @
| __|@
|__ |@
|_ _|@
|_| @@
@
__ __ @
|__| |@
| __|@
|__|__|@
@@
_ @
_| |_ @
| __|@
| __|@
|_ _|@
|_| @@
_ @
| |@
|_|@
$ @
$ @
$ @@
_ @
_|_|@
| | @
| | @
|_|_ @
|_|@@
_ @
|_|_ @
| |@
| |@
_|_|@
|_| @@
@
_____ @
| | | |@
|- -|@
|_|_|_|@
@@
@
_ @
_| |_ @
|_ _|@
|_| @
@@
$ @
$ @
$ @
_ @
| |@
|_|@@
$$$ @
$$$ @
___ @
|___|@
$$$ @
$$$ @@
$ @
$ @
$ @
_ @
|_|@
$ @@
@
_ @
/ |@
/ / @
|_/ @
@@
@
___ @
| |@
| | |@
|___|@
@@
@
___ @
|_ | @
_| |_ @
|_____|@
@@
@
___ @
|_ |@
| _|@
|___|@
@@
@
___ @
|_ |@
|_ |@
|___|@
@@
@
___ @
| | |@
|_ |@
|_|@
@@
@
___ @
| _|@
|_ |@
|___|@
@@
@
___ @
| _|@
| . |@
|___|@
@@
@
___ @
|_ |@
| |@
|_|@
@@
@
___ @
| . |@
| . |@
|___|@
@@
@
___ @
| . |@
|_ |@
|___|@
@@
@
_ @
|_|@
_ @
|_|@
@@
@
_ @
|_|@
_ @
| |@
|_|@@
__@
/ /@
/ / @
< < @
\\ \\ @
\\_\\@@
$$$$$ @
$$$$$ @
_____ @
|_____|@
|_____|@
$$$$$ @@
__ @
\\ \\ @
\\ \\ @
> >@
/ / @
/_/ @@
_____ @
|___ |@
| _|@
|_| @
|_| @
@@
@
_____ @
| __ |@
| |___|@
|_____|@
@@
@
_____ @
| _ |@
| |@
|__|__|@
@@
@
_____ @
| __ |@
| __ -|@
|_____|@
@@
@
_____ @
| |@
| --|@
|_____|@
@@
@
____ @
| \\ @
| | |@
|____/ @
@@
@
_____ @
| __|@
| __|@
|_____|@
@@
@
_____ @
| __|@
| __|@
|__| @
@@
@
_____ @
| __|@
| | |@
|_____|@
@@
@
_____ @
| | |@
| |@
|__|__|@
@@
@
_____ @
| |@
|- -|@
|_____|@
@@
@
__ @
__| |@
| | |@
|_____|@
@@
@
_____ @
| | |@
| -|@
|__|__|@
@@
@
__ @
| | @
| |__ @
|_____|@
@@
@
_____ @
| |@
| | | |@
|_|_|_|@
@@
@
_____ @
| | |@
| | | |@
|_|___|@
@@
@
_____ @
| |@
| | |@
|_____|@
@@
@
_____ @
| _ |@
| __|@
|__| @
@@
@
_____ @
| |@
| | |@
|__ _|@
|__|@@
@
_____ @
| __ |@
| -|@
|__|__|@
@@
@
_____ @
| __|@
|__ |@
|_____|@
@@
@
_____ @
|_ _|@
| | @
|_| @
@@
@
_____ @
| | |@
| | |@
|_____|@
@@
@
_____ @
| | |@
| | |@
\\___/ @
@@
@
_ _ _ @
| | | |@
| | | |@
|_____|@
@@
@
__ __ @
| | |@
|- -|@
|__|__|@
@@
@
__ __ @
| | |@
|_ _|@
|_| @
@@
@
_____ @
|__ |@
| __|@
|_____|@
@@
___ @
| _|@
| | @
| | @
| |_ @
|___|@@
@
_ @
| \\ @
\\ \\ @
\\_|@
@@
___ @
|_ |@
| |@
| |@
_| |@
|___|@@
_____ @
| _ |@
|_| |_|@
$$$$$ @
$$$$$ @
$$$$$ @@
$$$$$ @
$$$$$ @
$$$$$ @
$$$$$ @
_____ @
|_____|@@
___ @
|_ |@
|_|@
$$$ @
$$$ @
$$$ @@
@
@
___ @
| .'|@
|__,|@
@@
@
_ @
| |_ @
| . |@
|___|@
@@
@
@
___ @
| _|@
|___|@
@@
@
_ @
_| |@
| . |@
|___|@
@@
@
@
___ @
| -_|@
|___|@
@@
@
___ @
| _|@
| _|@
|_| @
@@
@
@
___ @
| . |@
|_ |@
|___|@@
@
_ @
| |_ @
| |@
|_|_|@
@@
@
_ @
|_|@
| |@
|_|@
@@
@
_ @
|_|@
| |@
_| |@
|___|@@
@
_ @
| |_ @
| '_|@
|_,_|@
@@
@
_ @
| |@
| |@
|_|@
@@
@
@
_____ @
| |@
|_|_|_|@
@@
@
@
___ @
| |@
|_|_|@
@@
@
@
___ @
| . |@
|___|@
@@
@
@
___ @
| . |@
| _|@
|_| @@
@
@
___ @
| . |@
|_ |@
|_|@@
@
@
___ @
| _|@
|_| @
@@
@
@
___ @
|_ -|@
|___|@
@@
@
_ @
| |_ @
| _|@
|_| @
@@
@
@
_ _ @
| | |@
|___|@
@@
@
@
_ _ @
| | |@
\\_/ @
@@
@
@
_ _ _ @
| | | |@
|_____|@
@@
@
@
_ _ @
|_'_|@
|_,_|@
@@
@
@
_ _ @
| | |@
|_ |@
|___|@@
@
@
___ @
|- _|@
|___|@
@@
___ @
| _|@
_| | @
|_ | @
| |_ @
|___|@@
_ @
| |@
| |@
| |@
| |@
|_|@@
___ @
|_ | @
| |_ @
| _|@
_| | @
|___| @@
_____ @
| | |@
|_|___|@
$$$$$ @
$$$$$ @
$$$$$ @@
__ __ @
|__|__|@
| _ |@
| |@
|__|__|@
@@
__ __ @
|__|__|@
| |@
| | |@
|_____|@
@@
__ __ @
|__|__|@
| | |@
| | |@
|_____|@
@@
_ _ @
|_|_|@
___ @
| .'|@
|__,|@
@@
_ _ @
|_|_|@
___ @
| . |@
|___|@
@@
_ _ @
|_|_|@
_ _ @
| | |@
|___|@
@@
@
_____ @
| __ |@
| __ -|@
| ___|@
|_| @@
` | patorjk/figlet.js | importable-fonts/Rectangles.js | JavaScript | mit | 5,567 |
/* eslint-env mocha */
'use strict'
import { Controller, Module } from 'cerebral'
import shortcuts from './'
const jsdom = require('jsdom')
const { JSDOM } = jsdom
const jsdomInstance = new JSDOM(`<!doctype html><html><body></body></html>`)
global.window = jsdomInstance.window
global.document = jsdomInstance.window.document
describe('Shortcuts module', () => {
it('should trigger signal upon keypress of letter "z"', done => {
const rootModule = Module({
signals: {
test: function() {
done()
},
},
modules: {
shortcuts: shortcuts({
z: 'test',
}),
},
})
Controller(rootModule)
document.dispatchEvent(
new window.KeyboardEvent('keyup', { key: 'z', char: 'z', keyCode: 90 })
)
})
})
| christianalfoni/cerebral | packages/node_modules/@cerebral/shortcuts/src/index.test.js | JavaScript | mit | 791 |
"use babel";
// @flow
import * as React from "react";
import path from "path";
import styled from "styled-components";
import AnsiToHtml from "ansi-to-html";
import type { MoleculeDiagnostic } from "../Types/types";
import type { Range } from "../../LanguageServerProtocolFeature/Types/standard";
import { compose, lifecycle, withHandlers, withState } from "recompose";
import ReactDOM from "react-dom";
const getSeverityColor = (severity: number) => {
switch (severity) {
case 1:
return "red";
case 2:
return "yellow";
case 3:
return "blue";
case 5:
return "green";
default:
return "blue";
}
};
const getSeverityClasses = (severity: any): string => {
switch (severity) {
case 3:
return "diagnostic-color-info-text icon icon-info";
case 2:
return "diagnostic-color-warning-text icon icon-alert";
case 1:
return "diagnostic-color-error-text icon icon-issue-opened";
case 5:
return "diagnostic-color-success-text icon icon-check";
default:
return "";
}
};
const Box = styled.div`
display: flex;
flex: 0 0 auto;
flex-direction: column;
border-bottom: 1px black solid;
border-radius: 3px;
padding: 4px;
align-items: stretch;
`;
const Header = styled.div`
margin: 0px 4px 4px 4px;
display: flex;
flex: 0 0 auto;
`;
const Content = styled.div`
display: flex;
list-style: none;
flex: 0 0 auto;
align-items: stretch;
flex-direction: row;
`;
const Severity = styled.div`
background-color: ${props => getSeverityColor(props.severity)};
border-radius: 10px;
width: 2px;
margin: 2px 12px 2px 12px;
`;
const Message = styled.div`
margin-left: 4px;
display: flex;
flex-direction: column;
align-items: stretch;
flex: 0 0 auto;
`;
const Path = styled.span`
display: inline;
cursor: pointer;
margin: 0px 8px;
&:hover {
text-decoration: underline;
}
`;
const RangeIndicator = styled.span`
display: inline;
`;
const SeverityIcon = styled.span`
height: 16px;
width: 16px;
`;
const HeaderAndContentBox = styled.div`
display: flex;
flex-direction: column;
flex: 0 0 auto;
align-items: stretch;
`;
const MessageBox = styled.div`
display: flex;
flex-direction: column;
flex: 1 0 0;
align-items: stretch;
`;
export const withTooltip = compose(
withState("tip", "setTip", null),
withHandlers({
disableTip: ({ tip }) => () => tip.dispose(),
}),
lifecycle({
componentDidMount() {
if (this.props.tooltip) {
this.props.setTip(
global.atom.tooltips.add(ReactDOM.findDOMNode(this), {
title: this.props.tooltip,
}),
);
}
},
componentWillUnmount() {
if (this.props.tip) this.props.disableTip();
},
}),
);
const TooltipPath = withTooltip(Path);
export default class DiagnosticDetails extends React.Component<Props, State> {
state: State;
props: Props;
static defaultProps: DefaultProps;
convert: any;
defaultRange: any;
constructor(props: Props) {
super(props);
this.convert = new AnsiToHtml();
this.defaultRange = {
start: { line: 0, character: 0 },
end: { line: 0, character: 0 },
};
}
convertMessageToHtml(message: string) {
return this.convert.toHtml(message.replace(/(?:\r\n|\r|\n)/g, "<br/>"));
}
render() {
const Comp = this.props.view;
return (
<Box>
{Comp ? (
<Comp {...this.props.diagnostic} jumpToFile={this.props.jumpTo} />
) : (
<HeaderAndContentBox>
<Header>
<SeverityIcon
className={getSeverityClasses(this.props.diagnostic.severity)}
/>
<TooltipPath
tooltip={this.props.diagnostic.path || ""}
className="text-highlight"
onClick={e =>
this.props.jumpTo(
this.props.diagnostic.path || "",
this.props.diagnostic.range || this.defaultRange,
e.detail === 1,
)
}
>
{path.basename(this.props.diagnostic.path || "")}
</TooltipPath>
{this.props.diagnostic.range &&
this.props.diagnostic.range.start.line != -1 ? (
<RangeIndicator className="text-subtle">
{`${this.props.diagnostic.range.start.line}:${
this.props.diagnostic.range.start.character
}`}
</RangeIndicator>
) : (
false
)}
</Header>
<Content>
<Severity severity={this.props.diagnostic.severity} />
<MessageBox>
<Message
dangerouslySetInnerHTML={{
__html: this.convertMessageToHtml(
this.props.diagnostic.message,
),
}}
/>
</MessageBox>
</Content>
</HeaderAndContentBox>
)}
</Box>
);
}
}
DiagnosticDetails.defaultProps = {};
type DefaultProps = {};
type Props = {
view?: React.ComponentType<any>,
diagnostic: MoleculeDiagnostic,
jumpTo: (path: string, range: Range, pending: boolean) => void,
};
type State = {};
| alanzanattadev/atom-molecule-dev-environment | lib/ExecutionControlEpic/DiagnosticsFeature/Presenters/DiagnosticDetails.js | JavaScript | mit | 5,335 |
/**
* Usage:
* element(selector, label).count() get the number of elements that match selector
* element(selector, label).click() clicks an element
* element(selector, label).mouseover() mouseover an element
* element(selector, label).query(fn) executes fn(selectedElements, done)
* element(selector, label).{method}() gets the value (as defined by jQuery, ex. val)
* element(selector, label).{method}(value) sets the value (as defined by jQuery, ex. val)
* element(selector, label).{method}(key) gets the value (as defined by jQuery, ex. attr)
* element(selector, label).{method}(key, value) sets the value (as defined by jQuery, ex. attr)
*/
angular.scenario.dsl('element', function() {
var KEY_VALUE_METHODS = ['attr', 'css', 'prop'];
var VALUE_METHODS = [
'val', 'text', 'html', 'height', 'innerHeight', 'outerHeight', 'width',
'innerWidth', 'outerWidth', 'position', 'scrollLeft', 'scrollTop', 'offset'
];
var chain = {};
chain.count = function() {
return this.addFutureAction("element '" + this.label + "' count", function($window, $document, done) {
try {
done(null, $document.elements().length);
} catch (e) {
done(null, 0);
}
});
};
chain.click = function() {
return this.addFutureAction("element '" + this.label + "' click", function($window, $document, done) {
var elements = $document.elements();
var href = elements.attr('href');
var eventProcessDefault = elements.trigger('click')[0];
if (href && elements[0].nodeName.toUpperCase() === 'A' && eventProcessDefault) {
this.application.navigateTo(href, function() {
done();
}, done);
} else {
done();
}
});
};
chain.dblclick = function() {
return this.addFutureAction("element '" + this.label + "' dblclick", function($window, $document, done) {
var elements = $document.elements();
var href = elements.attr('href');
var eventProcessDefault = elements.trigger('dblclick')[0];
if (href && elements[0].nodeName.toUpperCase() === 'A' && eventProcessDefault) {
this.application.navigateTo(href, function() {
done();
}, done);
} else {
done();
}
});
};
chain.mouseover = function() {
return this.addFutureAction("element '" + this.label + "' mouseover", function($window, $document, done) {
var elements = $document.elements();
elements.trigger('mouseover');
done();
});
};
chain.query = function(fn) {
return this.addFutureAction('element ' + this.label + ' custom query', function($window, $document, done) {
fn.call(this, $document.elements(), done);
});
};
angular.forEach(KEY_VALUE_METHODS, function(methodName) {
chain[methodName] = function(name, value) {
var args = arguments,
futureName = (args.length == 1)
? "element '" + this.label + "' get " + methodName + " '" + name + "'"
: "element '" + this.label + "' set " + methodName + " '" + name + "' to " + "'" + value + "'";
return this.addFutureAction(futureName, function($window, $document, done) {
var element = $document.elements();
done(null, element[methodName].apply(element, args));
});
};
});
angular.forEach(VALUE_METHODS, function(methodName) {
chain[methodName] = function(value) {
var args = arguments,
futureName = (args.length == 0)
? "element '" + this.label + "' " + methodName
: futureName = "element '" + this.label + "' set " + methodName + " to '" + value + "'";
return this.addFutureAction(futureName, function($window, $document, done) {
var element = $document.elements();
done(null, element[methodName].apply(element, args));
});
};
});
return function(selector, label) {
this.dsl.using(selector, label);
return chain;
};
});
angular.scenario.dsl('input', function() {
var chain = {};
var supportInputEvent = 'oninput' in document.createElement('div');
chain.enter = function(value, event) {
return this.addFutureAction("input '" + this.name + "' enter '" + value + "'", function($window, $document, done) {
var input = $document.elements('[data-ng-model="$1"]', this.name).filter(':input');
input.val(value);
input.trigger(event || (supportInputEvent ? 'input' : 'change'));
done();
});
};
chain.check = function() {
return this.addFutureAction("checkbox '" + this.name + "' toggle", function($window, $document, done) {
var input = $document.elements('[data-ng-model="$1"]', this.name).filter(':checkbox');
input.trigger('click');
done();
});
};
chain.select = function(value) {
return this.addFutureAction("radio button '" + this.name + "' toggle '" + value + "'", function($window, $document, done) {
var input = $document.elements('[data-ng-model="$1"][value="$2"]', this.name, value).filter(':radio');
input.trigger('click');
done();
});
};
chain.val = function() {
return this.addFutureAction("return input val", function($window, $document, done) {
var input = $document.elements('[data-ng-model="$1"]', this.name).filter(':input');
done(null,input.val());
});
};
return function(name) {
this.name = name;
return chain;
};
});
angular.scenario.dsl('binding', function() {
return function(name) {
return this.addFutureAction("select binding '" + name + "'", function($window, $document, done) {
var values = $document.elements().bindings($window.angular.element, name);
if (!values.length) {
return done("Binding selector '" + name + "' did not match.");
}
done(null, values[0]);
});
};
});
angular.scenario.dsl('alert', function() {
var chain = {};
chain.msgs = function(index){
return this.addFutureAction('alert msgs', function($window, $document, done){
var msgs = $window.parent.MOCK.alert.msgs;
if(typeof index !== 'undefined'){
msgs = msgs[index];
}
done(null, msgs);
});
};
chain.reset = function(){
return this.addFutureAction('reset alert msgs', function($window, $document, done){
$window.parent.MOCK_RESET();
done(null, true);
});
};
chain.ok = function(){
return this.addFutureAction('press OK on alert', function($window, $document, done){
$window.parent.MOCK.confirm.ok = true;
done(null, true);
});
};
return function() {
return chain;
};
});
angular.scenario.dsl('confirm', function() {
var chain = {};
chain.msgs = function(index){
return this.addFutureAction('confirm msgs', function($window, $document, done){
var msgs = $window.parent.MOCK.confirm.msgs;
if(typeof index !== 'undefined'){
msgs = msgs[index];
}
done(null, msgs);
});
};
chain.reset = function(){
return this.addFutureAction('reset mock msgs', function($window, $document, done){
$window.parent.MOCK_RESET();
done(null, true);
});
};
chain.ok = function(){
return this.addFutureAction('press OK on confirm', function($window, $document, done){
$window.parent.MOCK.confirm.ok = true;
done(null, true);
});
};
chain.cancel = function(){
return this.addFutureAction('press CANCEL on confirm', function($window, $document, done){
$window.parent.MOCK.confirm.ok = false;
done(null, true);
});
};
return function() {
return chain;
};
});
angular.scenario.dsl('history', function() {
var chain = {};
chain.back = function(numberOfTimes){
return this.addFutureAction('use window.history.back', function($window, $document, done){
if(typeof numberOfTimes === 'undefined') numberOfTimes = 1; // default
for(var i =0; i < numberOfTimes; i++){
$window.history.back();
}
done(null, true);
});
};
return function() {
return chain;
};
});
/**
* Usage:
* select(name).option('value') select one option
* select(name).options('value1', 'value2', ...) select options from a multi select
*/
angular.scenario.dsl('select', function() {
var chain = {};
chain.option = function(value) {
return this.addFutureAction("select '" + this.name + "' option '" + value + "'", function($window, $document, done) {
var select = $document.elements('select[data-ng-model="$1"]', this.name);
var option = select.find('option[value="' + value + '"]');
if (option.length) {
select.val(value);
} else {
option = select.find('option:contains("' + value + '")');
if (option.length) {
select.val(option.val());
} else {
return done("option '" + value + "' not found");
}
}
select.trigger('change');
done();
});
};
chain.options = function() {
var values = arguments;
return this.addFutureAction("select '" + this.name + "' options '" + values + "'", function($window, $document, done) {
var select = $document.elements('select[multiple][data-ng-model="$1"]', this.name);
select.val(values);
select.trigger('change');
done();
});
};
return function(name) {
this.name = name;
return chain;
};
}); | UseFedora/infowrap-filepicker | test/lib/custom-e2e-steps.js | JavaScript | mit | 9,366 |
/* */
var baseRandom = require('../internal/baseRandom'),
isIterateeCall = require('../internal/isIterateeCall'),
toArray = require('../lang/toArray'),
toIterable = require('../internal/toIterable');
var nativeMin = Math.min;
function sample(collection, n, guard) {
if (guard ? isIterateeCall(collection, n, guard) : n == null) {
collection = toIterable(collection);
var length = collection.length;
return length > 0 ? collection[baseRandom(0, length - 1)] : undefined;
}
var index = -1,
result = toArray(collection),
length = result.length,
lastIndex = length - 1;
n = nativeMin(n < 0 ? 0 : (+n || 0), length);
while (++index < n) {
var rand = baseRandom(index, lastIndex),
value = result[rand];
result[rand] = result[index];
result[index] = value;
}
result.length = n;
return result;
}
module.exports = sample;
| nayashooter/ES6_React-Bootstrap | public/jspm_packages/npm/lodash-compat@3.10.2/collection/sample.js | JavaScript | mit | 892 |
import Vue from 'vue'
export const EMAIL_REGEX = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9_-]+?\.[a-zA-Z]{2,5}$/
function commonValidator (regex, defaultMessage, rule, value, callback) {
if (!value || regex.test(value)) {
callback()
} else {
callback(new Error(rule.message || defaultMessage))
}
}
/**
* 邮箱验证
*/
export function email (rule, value, callback) {
commonValidator(EMAIL_REGEX, Vue.t('validation.email'), rule, value, callback)
}
| erguotou520/vue-fullstack | template/client/src/shared/validators.js | JavaScript | mit | 456 |
//@flow
declare var x : ?{foo : string};
x.
//^
| mroch/flow | tests/autocomplete/suggest_optional_chaining_1.js | JavaScript | mit | 49 |
// Modified slightly from
// https://github.com/andris9/rai/blob/master/lib/starttls.js
// (This code is MIT licensed.)
//
// Target API:
//
// var s = require('net').createStream(25, 'smtp.example.com');
// s.on('connect', function() {
// require('starttls')(s, options, function() {
// if (!s.authorized) {
// s.destroy();
// return;
// }
//
// s.end("hello world\n");
// });
// });
//
//
var tls = require('tls');
var crypto = require('crypto');
// From Node docs for TLS module.
var RECOMMENDED_CIPHERS = 'ECDHE-RSA-AES256-SHA:AES256-SHA:RC4-SHA:RC4:HIGH:!MD5:!aNULL:!EDH:!AESGCM';
function starttlsServer(socket, options, callback) {
return starttls(socket, options, callback, true);
}
function starttlsClient(socket, options, callback) {
return starttls(socket, options, callback, false);
}
function starttls(socket, options, callback, isServer) {
var sslcontext;
var opts = {};
Object.keys(options).forEach(function(key) {
opts[key] = options[key];
});
if (!opts.ciphers) {
opts.ciphers = RECOMMENDED_CIPHERS;
}
socket.removeAllListeners('data');
if (tls.createSecureContext) {
sslcontext = tls.createSecureContext(opts);
} else {
sslcontext = crypto.createCredentials(opts);
}
var pair = tls.createSecurePair(sslcontext, isServer);
var cleartext = pipe(pair, socket);
var erroredOut = false;
pair.on('secure', function() {
if (erroredOut) {
pair.end();
return;
}
var verifyError = (pair._ssl || pair.ssl).verifyError();
if (verifyError) {
cleartext.authorized = false;
cleartext.authorizationError = verifyError;
} else {
cleartext.authorized = true;
}
callback(null, cleartext);
});
pair.once('error', function(err) {
if (!erroredOut) {
erroredOut = true;
callback(err);
}
});
cleartext._controlReleased = true;
pair;
}
function forwardEvents(events, emitterSource, emitterDestination) {
var map = [];
for (var i = 0, len = events.length; i < len; i++) {
var name = events[i];
var handler = forwardEvent.bind(emitterDestination, name);
map.push(name);
emitterSource.on(name, handler);
}
return map;
}
function forwardEvent() {
this.emit.apply(this, arguments);
}
function removeEvents(map, emitterSource) {
for (var i = 0, len = map.length; i < len; i++) {
emitterSource.removeAllListeners(map[i]);
}
}
function pipe(pair, socket) {
pair.encrypted.pipe(socket);
socket.pipe(pair.encrypted);
pair.fd = socket.fd;
var cleartext = pair.cleartext;
cleartext.socket = socket;
cleartext.encrypted = pair.encrypted;
cleartext.authorized = false;
function onerror(e) {
if (cleartext._controlReleased) {
cleartext.emit('error', e);
}
}
var map = forwardEvents(['timeout', 'end', 'close', 'drain', 'error'], socket, cleartext);
function onclose() {
socket.removeListener('error', onerror);
socket.removeListener('close', onclose);
removeEvents(map, socket);
}
socket.on('error', onerror);
socket.on('close', onclose);
return cleartext;
}
exports.starttlsServer = starttlsServer;
exports.starttlsClient = starttlsClient;
exports.RECOMMENDED_CIPHERS = RECOMMENDED_CIPHERS;
| oleksiyk/nodeftpd | lib/starttls.js | JavaScript | mit | 3,263 |
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M6.8 10.61 5.37 9.19C5.73 8.79 6.59 8 7.75 8c.8 0 1.39.39 1.81.67.31.21.51.33.69.33.37 0 .8-.41.95-.61l1.42 1.42c-.36.4-1.22 1.19-2.37 1.19-.79 0-1.37-.38-1.79-.66-.33-.22-.52-.34-.71-.34-.37 0-.8.41-.95.61zM7.75 15c.19 0 .38.12.71.34.42.28 1 .66 1.79.66 1.16 0 2.01-.79 2.37-1.19l-1.42-1.42c-.15.2-.59.61-.95.61-.18 0-.38-.12-.69-.33-.42-.28-1.01-.67-1.81-.67-1.16 0-2.02.79-2.38 1.19l1.42 1.42c.16-.2.59-.61.96-.61zM22 6v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2h16c1.1 0 2 .9 2 2zm-8 0H4v12h10V6zm5 10c0-.55-.45-1-1-1s-1 .45-1 1 .45 1 1 1 1-.45 1-1zm0-4c0-.55-.45-1-1-1s-1 .45-1 1 .45 1 1 1 1-.45 1-1zm0-5h-2v2h2V7z"
}), 'Microwave');
exports.default = _default; | oliviertassinari/material-ui | packages/mui-icons-material/lib/Microwave.js | JavaScript | mit | 1,093 |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _reactIconBase = require('react-icon-base');
var _reactIconBase2 = _interopRequireDefault(_reactIconBase);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var IoIosAmericanfootball = function IoIosAmericanfootball(props) {
return _react2.default.createElement(
_reactIconBase2.default,
_extends({ viewBox: '0 0 40 40' }, props),
_react2.default.createElement(
'g',
null,
_react2.default.createElement('path', { d: 'm29.4 10.4c8.7 8.7 6.3 25.5 6.3 25.5s-2 0.4-5.1 0.4c-5.7 0-14.8-1-20.5-6.7-8.7-8.7-6.3-25.5-6.3-25.5s2-0.4 5.1-0.4c5.7 0 14.8 1 20.5 6.7z m-24.3 4.8l0.2 1.4 11.1-11.1-1.4-0.2z m15.5 11l0.9 0.9 2.2-2.3 1.8 1.8-2.2 2.2 0.9 0.9 5.2-5.2-0.8-1-2.3 2.3-1.7-1.8 2.3-2.2-1-0.9-2.2 2.2-1.8-1.8 2.3-2.2-0.9-0.9-2.2 2.3-1.8-1.8 2.2-2.2-0.9-1-2.2 2.3-1.8-1.8 2.3-2.2-1-0.9-2.1 2.3-1.8-1.8 2.2-2.2-0.9-0.9-5.2 5.2 0.8 1 2.3-2.3 1.7 1.8-2.3 2.2 1 0.9 2.2-2.2 1.8 1.8-2.3 2.2 0.9 0.9 2.2-2.3 1.8 1.8-2.2 2.2 0.9 1 2.2-2.3 1.8 1.8z m3.9 8.5l9.9-9.9-0.2-1.4-11.1 11.1z' })
)
);
};
exports.default = IoIosAmericanfootball;
module.exports = exports['default']; | bengimbel/Solstice-React-Contacts-Project | node_modules/react-icons/lib/io/ios-americanfootball.js | JavaScript | mit | 1,609 |
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { inject, bindable, bindingMode, customElement } from 'aurelia-framework';
import { getLogger } from 'aurelia-logging';
import { MDCCheckbox } from '@material/checkbox';
import * as util from '../../util';
let MdcCheckbox = MdcCheckbox_1 = class MdcCheckbox {
constructor(element) {
this.element = element;
this.checked = false;
this.indeterminate = false;
this.disabled = false;
this.controlId = '';
this.controlId = `mdc-checkbox-${MdcCheckbox_1.id++}`;
this.log = getLogger('mdc-checkbox');
}
bind() {
this.mdcCheckbox = new MDCCheckbox(this.elementCheckbox);
this.disabledChanged(this.disabled);
this.indeterminateChanged(this.indeterminate);
this.mdcCheckbox.checked = this.checked;
}
unbind() {
this.mdcCheckbox.destroy();
}
handleChange(e) {
this.checked = this.mdcCheckbox.checked;
e.stopPropagation();
}
checkedChanged(newValue) {
this.indeterminate = false;
const value = util.getBoolean(newValue);
if (this.mdcCheckbox.checked !== value) {
this.mdcCheckbox.checked = value;
}
util.fireEvent(this.element, 'on-change', value);
}
disabledChanged(newValue) {
this.mdcCheckbox.disabled = util.getBoolean(newValue);
}
indeterminateChanged(newValue) {
this.mdcCheckbox.indeterminate = util.getBoolean(newValue);
}
};
MdcCheckbox.id = 0;
__decorate([
bindable({ defaultBindingMode: bindingMode.twoWay }),
__metadata("design:type", Object)
], MdcCheckbox.prototype, "checked", void 0);
__decorate([
bindable({ defaultBindingMode: bindingMode.twoWay }),
__metadata("design:type", Object)
], MdcCheckbox.prototype, "indeterminate", void 0);
__decorate([
bindable(),
__metadata("design:type", Object)
], MdcCheckbox.prototype, "disabled", void 0);
MdcCheckbox = MdcCheckbox_1 = __decorate([
customElement('mdc-checkbox'),
inject(Element),
__metadata("design:paramtypes", [Element])
], MdcCheckbox);
export { MdcCheckbox };
var MdcCheckbox_1;
| Ullfis/aurelia-mdc-bridge | dist/es2017/inputs/checkbox/checkbox.js | JavaScript | mit | 2,870 |
var config = require('../knexfile');
var knex = require('knex')(config);
var bookshelf = require('bookshelf')(knex);
bookshelf.plugin('virtuals');
knex.migrate.latest();
module.exports = bookshelf;
| sahat/megaboilerplate | examples/express-nunjucks-postcss-unstyled-react-webpack-mocha-sqlite-twitter/config/bookshelf.js | JavaScript | mit | 201 |
(function () {
'use strict';
angular.module('ariaNg').directive('ngAutoFocus', ['$timeout', function ($timeout) {
return {
restrict: 'A',
link: function (scope, element) {
$timeout(function () {
element[0].focus();
});
}
};
}]);
}());
| SquirrelMajik/AriaNg | src/scripts/directives/autoFocus.js | JavaScript | mit | 352 |
'use strict'
var config = require('./config.js')
var util = require('./util.js')
module.exports = {
'name': 'rtlcss',
'priority': 100,
'directives': {
'control': {
'ignore': {
'expect': { 'atrule': true, 'comment': true, 'decl': true, 'rule': true },
'endNode': null,
'begin': function (node, metadata, context) {
// find the ending node in case of self closing directive
if (!this.endNode && metadata.begin && metadata.end) {
var n = node
while (n && n.nodes) {
n = n.nodes[n.nodes.length - 1]
}
this.endNode = n
}
var prevent = true
if (node.type === 'comment' && (node.text === '!rtl:end:ignore' || node.text === 'rtl:end:ignore')) {
prevent = false
}
return prevent
},
'end': function (node, metadata, context) {
// end if:
// 1. block directive and the node is comment
// 2. self closing directive and node is endNode
if (metadata.begin !== metadata.end && node.type === 'comment' || metadata.begin && metadata.end && node === this.endNode) {
// clear ending node
this.endNode = null
return true
}
return false
}
},
'rename': {
'expect': {'rule': true},
'begin': function (node, metadata, context) {
node.selector = context.util.applyStringMap(node.selector, false)
return false
},
'end': function (node, context) {
return true
}
},
'raw': {
'expect': {'self': true},
'begin': function (node, metadata, context) {
var nodes = context.postcss.parse(metadata.param)
node.parent.insertBefore(node, nodes)
return true
},
'end': function (node, context) {
return true
}
},
'remove': {
'expect': {'atrule': true, 'rule': true, 'decl': true},
'begin': function (node, metadata, context) {
var prevent = false
switch (node.type) {
case 'atrule':
case 'rule':
case 'decl':
prevent = true
node.remove()
}
return prevent
},
'end': function (node, metadata, context) {
return true
}
},
'options': {
'expect': {'self': true},
'stack': [],
'begin': function (node, metadata, context) {
this.stack.push(util.extend({}, context.config))
var options
try {
options = JSON.parse(metadata.param)
} catch (e) {
throw node.error('Invlaid options object', { 'details': e })
}
context.config = config.configure(options, context.config.plugins)
context.util = util.configure(context.config)
return true
},
'end': function (node, metadata, context) {
var config = this.stack.pop()
if (config && !metadata.begin) {
context.config = config
context.util = util.configure(context.config)
}
return true
}
},
'config': {
'expect': {'self': true},
'expr': {
'fn': /function([^\(]*)\(([^\(\)]*?)\)[^\{]*\{([^]*)\}/ig,
'rx': /\/([^\/]*)\/(.*)/ig
},
'stack': [],
'begin': function (node, metadata, context) {
this.stack.push(util.extend({}, context.config))
var configuration
try {
configuration = eval('(' + metadata.param + ')') // eslint-disable-line no-eval
} catch (e) {
throw node.error('Invlaid config object', { 'details': e })
}
context.config = config.configure(configuration.options, configuration.plugins)
context.util = util.configure(context.config)
return true
},
'end': function (node, metadata, context) {
var config = this.stack.pop()
if (config && !metadata.begin) {
context.config = config
context.util = util.configure(context.config)
}
return true
}
}
},
'value': [
{
'name': 'ignore',
'action': function (decl, expr, context) {
return true
}
},
{
'name': 'prepend',
'action': function (decl, expr, context) {
var prefix = ''
decl.raws.value.raw.replace(expr, function (m, v) {
prefix += v
})
decl.value = decl.raws.value.raw = prefix + decl.raws.value.raw
return true
}
},
{
'name': 'append',
'action': function (decl, expr, context) {
decl.value = decl.raws.value.raw = decl.raws.value.raw.replace(expr, function (match, value) {
return match + value
})
return true
}
},
{
'name': 'insert',
'action': function (decl, expr, context) {
decl.value = decl.raws.value.raw = decl.raws.value.raw.replace(expr, function (match, value) {
return value + match
})
return true
}
},
{
'name': '',
'action': function (decl, expr, context) {
decl.raws.value.raw.replace(expr, function (match, value) {
decl.value = decl.raws.value.raw = value + match
})
return true
}
}
]
},
'processors': [
{
'name': 'direction',
'expr': /direction/im,
'action': function (prop, value, context) {
return { 'prop': prop, 'value': context.util.swapLtrRtl(value) }
}
},
{
'name': 'left',
'expr': /left/im,
'action': function (prop, value, context) {
return { 'prop': prop.replace(this.expr, function () { return 'right' }), 'value': value }
}
},
{
'name': 'right',
'expr': /right/im,
'action': function (prop, value, context) {
return { 'prop': prop.replace(this.expr, function () { return 'left' }), 'value': value }
}
},
{
'name': 'four-value syntax',
'expr': /^(margin|padding|border-(color|style|width))$/ig,
'cache': null,
'action': function (prop, value, context) {
if (this.cache === null) {
this.cache = {
'match': /[^\s\uFFFD]+/g
}
}
var state = context.util.guardFunctions(value)
var result = state.value.match(this.cache.match)
if (result && result.length === 4 && (state.store.length > 0 || result[1] !== result[3])) {
var i = 0
state.value = state.value.replace(this.cache.match, function () {
return result[(4 - i++) % 4]
})
}
return { 'prop': prop, 'value': context.util.unguardFunctions(state) }
}
},
{
'name': 'border radius',
'expr': /border-radius/ig,
'cache': null,
'flip': function (value) {
var parts = value.match(this.cache.match)
var i
if (parts) {
switch (parts.length) {
case 2:
i = 1
if (parts[0] !== parts[1]) {
value = value.replace(this.cache.match, function () {
return parts[i--]
})
}
break
case 3:
// preserve leading whitespace.
value = value.replace(this.cache.white, function (m) {
return m + parts[1] + ' '
})
break
case 4:
i = 0
if (parts[0] !== parts[1] || parts[2] !== parts[3]) {
value = value.replace(this.cache.match, function () {
return parts[(5 - i++) % 4]
})
}
break
}
}
return value
},
'action': function (prop, value, context) {
if (this.cache === null) {
this.cache = {
'match': /[^\s\uFFFD]+/g,
'slash': /[^\/]+/g,
'white': /(^\s*)/
}
}
var state = context.util.guardFunctions(value)
state.value = state.value.replace(this.cache.slash, function (m) {
return this.flip(m)
}.bind(this))
return { 'prop': prop, 'value': context.util.unguardFunctions(state) }
}
},
{
'name': 'shadow',
'expr': /shadow/ig,
'cache': null,
'action': function (prop, value, context) {
if (this.cache === null) {
this.cache = {
'replace': /[^,]+/g
}
}
var colorSafe = context.util.guardHexColors(value)
var funcSafe = context.util.guardFunctions(colorSafe.value)
funcSafe.value = funcSafe.value.replace(this.cache.replace, function (m) { return context.util.negate(m) })
colorSafe.value = context.util.unguardFunctions(funcSafe)
return { 'prop': prop, 'value': context.util.unguardHexColors(colorSafe) }
}
},
{
'name': 'transform origin',
'expr': /transform-origin/ig,
'cache': null,
'flip': function (value, context) {
if (value === '0') {
value = '100%'
} else if (value.match(this.cache.percent)) {
value = context.util.complement(value)
}
return value
},
'action': function (prop, value, context) {
if (this.cache === null) {
this.cache = {
'match': context.util.regex(['calc', 'percent', 'length'], 'g'),
'percent': context.util.regex(['calc', 'percent'], 'i'),
'xKeyword': /(left|right)/i
}
}
if (value.match(this.cache.xKeyword)) {
value = context.util.swapLeftRight(value)
} else {
var state = context.util.guardFunctions(value)
var parts = state.value.match(this.cache.match)
if (parts && parts.length > 0) {
parts[0] = this.flip(parts[0], context)
state.value = state.value.replace(this.cache.match, function () { return parts.shift() })
value = context.util.unguardFunctions(state)
}
}
return { 'prop': prop, 'value': value }
}
},
{
'name': 'transform',
'expr': /^(?!text\-).*?transform$/ig,
'cache': null,
'flip': function (value, process, context) {
var i = 0
return value.replace(this.cache.unit, function (num) {
return process(++i, num)
})
},
'flipMatrix': function (value, context) {
return this.flip(value, function (i, num) {
if (i === 2 || i === 3 || i === 5) {
return context.util.negate(num)
}
return num
}, context)
},
'flipMatrix3D': function (value, context) {
return this.flip(value, function (i, num) {
if (i === 2 || i === 4 || i === 5 || i === 13) {
return context.util.negate(num)
}
return num
}, context)
},
'flipRotate3D': function (value, context) {
return this.flip(value, function (i, num) {
if (i === 2 || i === 4) {
return context.util.negate(num)
}
return num
}, context)
},
'action': function (prop, value, context) {
if (this.cache === null) {
this.cache = {
'negatable': /((translate)(x|3d)?|rotate(z)?)$/ig,
'unit': context.util.regex(['calc', 'number'], 'g'),
'matrix': /matrix$/i,
'matrix3D': /matrix3d$/i,
'skewXY': /skew(x|y)?$/i,
'rotate3D': /rotate3d$/i
}
}
var state = context.util.guardFunctions(value)
return {
'prop': prop,
'value': context.util.unguardFunctions(state, function (v, n) {
if (n.length) {
if (n.match(this.cache.matrix3D)) {
v = this.flipMatrix3D(v, context)
} else if (n.match(this.cache.matrix)) {
v = this.flipMatrix(v, context)
} else if (n.match(this.cache.rotate3D)) {
v = this.flipRotate3D(v, context)
} else if (n.match(this.cache.skewXY)) {
v = context.util.negateAll(v)
} else if (n.match(this.cache.negatable)) {
v = context.util.negate(v)
}
}
return v
}.bind(this))
}
}
},
{
'name': 'transition',
'expr': /transition(-property)?$/i,
'action': function (prop, value, context) {
return { 'prop': prop, 'value': context.util.swapLeftRight(value) }
}
},
{
'name': 'background',
'expr': /background(-position(-x)?|-image)?$/i,
'cache': null,
'flip': function (value, context, isPosition) {
var state = util.saveTokens(value, true)
var parts = state.value.match(this.cache.match)
if (parts && parts.length > 0) {
var keywords = (state.value.match(this.cache.position) || '').length
if (isPosition && (/* edge offsets */ parts.length >= 3 || /* keywords only */ keywords === 2)) {
state.value = util.swapLeftRight(state.value)
} else {
parts[0] = parts[0] === '0'
? '100%'
: (parts[0].match(this.cache.percent)
? context.util.complement(parts[0])
: context.util.swapLeftRight(parts[0]))
state.value = state.value.replace(this.cache.match, function () { return parts.shift() })
}
}
return util.restoreTokens(state)
},
'update': function (context, value, name) {
if (name.match(this.cache.gradient)) {
value = context.util.swapLeftRight(value)
if (value.match(this.cache.angle)) {
value = context.util.negate(value)
}
} else if (context.config.processUrls === true || context.config.processUrls.decl === true && name.match(this.cache.url)) {
value = context.util.applyStringMap(value, true)
}
return value
},
'action': function (prop, value, context) {
if (this.cache === null) {
this.cache = {
'match': context.util.regex(['position', 'percent', 'length', 'calc'], 'ig'),
'percent': context.util.regex(['calc', 'percent'], 'i'),
'position': context.util.regex(['position'], 'g'),
'gradient': /gradient$/i,
'angle': /\d+(deg|g?rad|turn)/i,
'url': /^url/i
}
}
var colorSafe = context.util.guardHexColors(value)
var funcSafe = context.util.guardFunctions(colorSafe.value)
var parts = funcSafe.value.split(',')
var lprop = prop.toLowerCase()
if (lprop !== 'background-image') {
var isPosition = lprop === 'background-position'
for (var x = 0; x < parts.length; x++) {
parts[x] = this.flip(parts[x], context, isPosition)
}
}
funcSafe.value = parts.join(',')
colorSafe.value = context.util.unguardFunctions(funcSafe, this.update.bind(this, context))
return {
'prop': prop,
'value': context.util.unguardHexColors(colorSafe)
}
}
},
{
'name': 'keyword',
'expr': /float|clear|text-align/i,
'action': function (prop, value, context) {
return { 'prop': prop, 'value': context.util.swapLeftRight(value) }
}
},
{
'name': 'cursor',
'expr': /cursor/i,
'cache': null,
'update': function (context, value, name) {
if (context.config.processUrls === true || context.config.processUrls.decl === true && name.match(this.cache.url)) {
value = context.util.applyStringMap(value, true)
}
return value
},
'flip': function (value) {
return value.replace(this.cache.replace, function (s, m) {
return s.replace(m, m.replace(this.cache.e, '*').replace(this.cache.w, 'e').replace(this.cache.star, 'w'))
}.bind(this))
},
'action': function (prop, value, context) {
if (this.cache === null) {
this.cache = {
'replace': /\b(ne|nw|se|sw|nesw|nwse)-resize/ig,
'url': /^url/i,
'e': /e/i,
'w': /w/i,
'star': /\*/i
}
}
var state = context.util.guardFunctions(value)
var parts = state.value.split(',')
for (var x = 0; x < parts.length; x++) {
parts[x] = this.flip(parts[x])
}
state.value = parts.join(',')
return {
'prop': prop,
'value': context.util.unguardFunctions(state, this.update.bind(this, context))
}
}
}
]
}
| alicegraziosi/semaphore | node_modules/rtlcss/lib/plugin.js | JavaScript | mit | 17,036 |
'use strict';
var webpack = require( 'webpack' );
var path = require( 'path' );
var ROOT_PATH = __dirname;
var SOURCES_PATH = path.join( ROOT_PATH, 'sources' );
var VENDORS_PATH = path.join( ROOT_PATH, '/examples/vendors' );
var NODE_PATH = path.join( ROOT_PATH, 'node_modules' );
var BUILD_PATH = path.join( ROOT_PATH, 'builds/dist/' );
module.exports = {
entry: {
OSG: [ './sources/OSG.js' ],
tests: [ './tests/tests.js' ]
},
output: {
path: BUILD_PATH,
filename: '[name].js',
libraryTarget: 'umd',
library: 'OSG'
},
externals: [ {
'qunit': {
root: 'QUnit',
commonjs2: 'qunit',
commonjs: 'qunit',
amd: 'qunit'
}
}, {
'zlib': {
root: 'Zlib',
commonjs2: 'zlib',
commonjs: 'zlib',
amd: 'zlib'
}
}, {
'q': {
root: 'Q',
commonjs2: 'q',
commonjs: 'q',
amd: 'q'
}
}, {
'hammer': {
root: 'Hammer',
commonjs2: 'hammerjs',
commonjs: 'hammerjs',
amd: 'hammer'
}
}, {
'leap': {
root: 'Leap',
commonjs2: 'leapjs',
commonjs: 'leapjs',
amd: 'leap'
}
}, {
'jquery': {
root: '$',
commonjs2: 'jquery',
commonjs: 'jquery',
amd: 'jquery'
}
} ],
resolve: {
root: [
SOURCES_PATH,
VENDORS_PATH,
ROOT_PATH,
NODE_PATH
]
},
module: {
loaders: [ {
// shaders
test: /\.(frag|vert|glsl)$/,
loader: 'raw-loader'
} ]
},
devtool: 'eval',
plugins: [
new webpack.BannerPlugin( [
'OSGJS',
'Cedric Pinson <trigrou@trigrou.com> (http://cedricpinson.com)'
].join( '\n' ) )
]
};
| jmirabel/osgjs | webpack.config.js | JavaScript | mit | 2,006 |
var app = require('express')(),
wizard = require('hmpo-form-wizard'),
steps = require('./steps'),
fields = require('./fields');
app.use(require('hmpo-template-mixins')(fields, { sharedTranslationKey: 'prototype' }));
app.use(wizard(steps, fields, {
controller: require('../../../controllers/form'),
templatePath: 'priority_service_170202/renew',
name: 'common',
params: '/:action?'
}));
module.exports = app;
| maxinedivers/pass-max | routes/priority_service_170202/renew/index.js | JavaScript | mit | 440 |
import { SIGNUP_PATH as path } from 'constants'
import component from './containers/SignupContainer'
export default {
path,
component
}
| ronihcohen/magic-vote | src/routes/Signup/index.js | JavaScript | mit | 141 |
import { call } from 'redux-saga/effects';
import createDucks from '../utils/createDucks';
import rootSelector from '../rootSelector';
import namespace from '../namespace';
const ducks = createDucks({
key: 'logout',
apiName: 'logout',
rootSelector,
namespace,
sagas: {
* api({ logout }) {
yield call(logout);
if (process.env.browser) {
yield call(window.location.href = '/');
}
},
},
});
export default ducks.default; export const actions = ducks.actions; export const selector = ducks.selector; export const sagas = ducks.sagas;
| theseushu/runcai | app/api/logout/ducks.js | JavaScript | mit | 578 |
const RtmClient = require( "@slack/client" ).RtmClient;
const CLIENT_EVENTS = require( "@slack/client" ).CLIENT_EVENTS;
const MemoryDataStore = require( "@slack/client" ).MemoryDataStore;
function send( rtm, channels, logger, message ) {
for ( let i = 0; i < channels.length; i++ ) {
try {
const name = channels[ i ];
const id = rtm.dataStore.getChannelByName( name ).id;
rtm.sendMessage( message, id, err => {
if ( err ) {
console.error( err );
}
} );
} catch ( e ) {
if ( logger ) {
logger( `Error sending message "${message} to channel ${channels[ i ]}: ${e}"` );
}
}
}
}
module.exports = function( token, channels, logger ) {
if ( !token ) {
console.warn( "Slack is not configured. No Messages will be sent" );
return {
send() {}
};
}
const rtm = new RtmClient( token, {
// Sets the level of logging we require
logLevel: "warn",
// Initialise a data store for our client, this will load additional helper functions for the storing and retrieval of data
dataStore: new MemoryDataStore(),
// Boolean indicating whether Slack should automatically reconnect after an error response
autoReconnect: false,
// Boolean indicating whether each message should be marked as read or not after it is processed
autoMark: true
} );
rtm.on( CLIENT_EVENTS.RTM.AUTHENTICATED, rtmStartData => {
console.log( `Logged in as ${ rtmStartData.self.name } of team ${ rtmStartData.team.name }, but not yet connected to a channel` );
} );
rtm.on( CLIENT_EVENTS.RTM.DISCONNECT, () => {
console.warn( "Disconnected from slack" );
rtm.reconnect();
} );
rtm.on( CLIENT_EVENTS.RTM.ATTEMPTING_RECONNECT, () => {
console.warn( "Attempting reconnect to slack" );
} );
rtm.on( CLIENT_EVENTS.RTM.WS_ERROR, () => {
console.error( "Slack Error" );
} );
rtm.on( CLIENT_EVENTS.RTM.RTM_CONNECTION_OPENED, () => {
console.log( "Ready to send messages" );
} );
rtm.start();
return {
send: send.bind( undefined, rtm, channels, logger )
};
};
| shawnHartsell/cowpoke | src/slack.js | JavaScript | mit | 2,005 |
YUI.add('console', function (Y, NAME) {
/**
* Console creates a visualization for messages logged through calls to a YUI
* instance's <code>Y.log( message, category, source )</code> method. The
* debug versions of YUI modules will include logging statements to offer some
* insight into the steps executed during that module's operation. Including
* log statements in your code will cause those messages to also appear in the
* Console. Use Console to aid in developing your page or application.
*
* Entry categories "info", "warn", and "error"
* are also referred to as the log level, and entries are filtered against the
* configured logLevel.
*
* @module console
* @class Console
* @extends Widget
* @param conf {Object} Configuration object (see Configuration attributes)
* @constructor
*/
var getCN = Y.ClassNameManager.getClassName,
CHECKED = 'checked',
CLEAR = 'clear',
CLICK = 'click',
COLLAPSED = 'collapsed',
CONSOLE = 'console',
CONTENT_BOX = 'contentBox',
DISABLED = 'disabled',
ENTRY = 'entry',
ERROR = 'error',
HEIGHT = 'height',
INFO = 'info',
LAST_TIME = 'lastTime',
PAUSE = 'pause',
PAUSED = 'paused',
RESET = 'reset',
START_TIME = 'startTime',
TITLE = 'title',
WARN = 'warn',
DOT = '.',
C_BUTTON = getCN(CONSOLE,'button'),
C_CHECKBOX = getCN(CONSOLE,'checkbox'),
C_CLEAR = getCN(CONSOLE,CLEAR),
C_COLLAPSE = getCN(CONSOLE,'collapse'),
C_COLLAPSED = getCN(CONSOLE,COLLAPSED),
C_CONSOLE_CONTROLS = getCN(CONSOLE,'controls'),
C_CONSOLE_HD = getCN(CONSOLE,'hd'),
C_CONSOLE_BD = getCN(CONSOLE,'bd'),
C_CONSOLE_FT = getCN(CONSOLE,'ft'),
C_CONSOLE_TITLE = getCN(CONSOLE,TITLE),
C_ENTRY = getCN(CONSOLE,ENTRY),
C_ENTRY_CAT = getCN(CONSOLE,ENTRY,'cat'),
C_ENTRY_CONTENT = getCN(CONSOLE,ENTRY,'content'),
C_ENTRY_META = getCN(CONSOLE,ENTRY,'meta'),
C_ENTRY_SRC = getCN(CONSOLE,ENTRY,'src'),
C_ENTRY_TIME = getCN(CONSOLE,ENTRY,'time'),
C_PAUSE = getCN(CONSOLE,PAUSE),
C_PAUSE_LABEL = getCN(CONSOLE,PAUSE,'label'),
RE_INLINE_SOURCE = /^(\S+)\s/,
RE_AMP = /&(?!#?[a-z0-9]+;)/g,
RE_GT = />/g,
RE_LT = /</g,
ESC_AMP = '&',
ESC_GT = '>',
ESC_LT = '<',
ENTRY_TEMPLATE_STR =
'<div class="{entry_class} {cat_class} {src_class}">'+
'<p class="{entry_meta_class}">'+
'<span class="{entry_src_class}">'+
'{sourceAndDetail}'+
'</span>'+
'<span class="{entry_cat_class}">'+
'{category}</span>'+
'<span class="{entry_time_class}">'+
' {totalTime}ms (+{elapsedTime}) {localTime}'+
'</span>'+
'</p>'+
'<pre class="{entry_content_class}">{message}</pre>'+
'</div>',
L = Y.Lang,
create = Y.Node.create,
isNumber = L.isNumber,
isString = L.isString,
merge = Y.merge,
substitute = Y.Lang.sub;
function Console() {
Console.superclass.constructor.apply(this,arguments);
}
Y.Console = Y.extend(Console, Y.Widget,
// Y.Console prototype
{
/**
* Category to prefix all event subscriptions to allow for ease of detach
* during destroy.
*
* @property _evtCat
* @type string
* @protected
*/
_evtCat : null,
/**
* Reference to the Node instance containing the header contents.
*
* @property _head
* @type Node
* @default null
* @protected
*/
_head : null,
/**
* Reference to the Node instance that will house the console messages.
*
* @property _body
* @type Node
* @default null
* @protected
*/
_body : null,
/**
* Reference to the Node instance containing the footer contents.
*
* @property _foot
* @type Node
* @default null
* @protected
*/
_foot : null,
/**
* Holds the object API returned from <code>Y.later</code> for the print
* loop interval.
*
* @property _printLoop
* @type Object
* @default null
* @protected
*/
_printLoop : null,
/**
* Array of normalized message objects awaiting printing.
*
* @property buffer
* @type Array
* @default null
* @protected
*/
buffer : null,
/**
* Wrapper for <code>Y.log</code>.
*
* @method log
* @param arg* {MIXED} (all arguments passed through to <code>Y.log</code>)
* @chainable
*/
log : function () {
Y.log.apply(Y,arguments);
return this;
},
/**
* Clear the console of messages and flush the buffer of pending messages.
*
* @method clearConsole
* @chainable
*/
clearConsole : function () {
// TODO: clear event listeners from console contents
this._body.empty();
this._cancelPrintLoop();
this.buffer = [];
return this;
},
/**
* Clears the console and resets internal timers.
*
* @method reset
* @chainable
*/
reset : function () {
this.fire(RESET);
return this;
},
/**
* Collapses the body and footer.
*
* @method collapse
* @chainable
*/
collapse : function () {
this.set(COLLAPSED, true);
return this;
},
/**
* Expands the body and footer if collapsed.
*
* @method expand
* @chainable
*/
expand : function () {
this.set(COLLAPSED, false);
return this;
},
/**
* Outputs buffered messages to the console UI. This is typically called
* from a scheduled interval until the buffer is empty (referred to as the
* print loop). The number of buffered messages output to the Console is
* limited to the number provided as an argument. If no limit is passed,
* all buffered messages are rendered.
*
* @method printBuffer
* @param limit {Number} (optional) max number of buffered entries to write
* @chainable
*/
printBuffer: function (limit) {
var messages = this.buffer,
debug = Y.config.debug,
entries = [],
consoleLimit= this.get('consoleLimit'),
newestOnTop = this.get('newestOnTop'),
anchor = newestOnTop ? this._body.get('firstChild') : null,
i;
if (messages.length > consoleLimit) {
messages.splice(0, messages.length - consoleLimit);
}
limit = Math.min(messages.length, (limit || messages.length));
// turn off logging system
Y.config.debug = false;
if (!this.get(PAUSED) && this.get('rendered')) {
for (i = 0; i < limit && messages.length; ++i) {
entries[i] = this._createEntryHTML(messages.shift());
}
if (!messages.length) {
this._cancelPrintLoop();
}
if (entries.length) {
if (newestOnTop) {
entries.reverse();
}
this._body.insertBefore(create(entries.join('')), anchor);
if (this.get('scrollIntoView')) {
this.scrollToLatest();
}
this._trimOldEntries();
}
}
// restore logging system
Y.config.debug = debug;
return this;
},
/**
* Constructor code. Set up the buffer and entry template, publish
* internal events, and subscribe to the configured logEvent.
*
* @method initializer
* @protected
*/
initializer : function () {
this._evtCat = Y.stamp(this) + '|';
this.buffer = [];
this.get('logSource').on(this._evtCat +
this.get('logEvent'),Y.bind("_onLogEvent",this));
/**
* Transfers a received message to the print loop buffer. Default
* behavior defined in _defEntryFn.
*
* @event entry
* @param event {Event.Facade} An Event Facade object with the following attribute specific properties added:
* <dl>
* <dt>message</dt>
* <dd>The message data normalized into an object literal (see _normalizeMessage)</dd>
* </dl>
* @preventable _defEntryFn
*/
this.publish(ENTRY, { defaultFn: this._defEntryFn });
/**
* Triggers the reset behavior via the default logic in _defResetFn.
*
* @event reset
* @param event {Event.Facade} Event Facade object
* @preventable _defResetFn
*/
this.publish(RESET, { defaultFn: this._defResetFn });
this.after('rendered', this._schedulePrint);
},
/**
* Tears down the instance, flushing event subscriptions and purging the UI.
*
* @method destructor
* @protected
*/
destructor : function () {
var bb = this.get('boundingBox');
this._cancelPrintLoop();
this.get('logSource').detach(this._evtCat + '*');
bb.purge(true);
},
/**
* Generate the Console UI.
*
* @method renderUI
* @protected
*/
renderUI : function () {
this._initHead();
this._initBody();
this._initFoot();
// Apply positioning to the bounding box if appropriate
var style = this.get('style');
if (style !== 'block') {
this.get('boundingBox').addClass(this.getClassName(style));
}
},
/**
* Sync the UI state to the current attribute state.
*
* @method syncUI
*/
syncUI : function () {
this._uiUpdatePaused(this.get(PAUSED));
this._uiUpdateCollapsed(this.get(COLLAPSED));
this._uiSetHeight(this.get(HEIGHT));
},
/**
* Set up event listeners to wire up the UI to the internal state.
*
* @method bindUI
* @protected
*/
bindUI : function () {
this.get(CONTENT_BOX).one('button.'+C_COLLAPSE).
on(CLICK,this._onCollapseClick,this);
this.get(CONTENT_BOX).one('input[type=checkbox].'+C_PAUSE).
on(CLICK,this._onPauseClick,this);
this.get(CONTENT_BOX).one('button.'+C_CLEAR).
on(CLICK,this._onClearClick,this);
// Attribute changes
this.after(this._evtCat + 'stringsChange',
this._afterStringsChange);
this.after(this._evtCat + 'pausedChange',
this._afterPausedChange);
this.after(this._evtCat + 'consoleLimitChange',
this._afterConsoleLimitChange);
this.after(this._evtCat + 'collapsedChange',
this._afterCollapsedChange);
},
/**
* Create the DOM structure for the header elements.
*
* @method _initHead
* @protected
*/
_initHead : function () {
var cb = this.get(CONTENT_BOX),
info = merge(Console.CHROME_CLASSES, {
str_collapse : this.get('strings.collapse'),
str_title : this.get('strings.title')
});
this._head = create(substitute(Console.HEADER_TEMPLATE,info));
cb.insertBefore(this._head,cb.get('firstChild'));
},
/**
* Create the DOM structure for the console body—where messages are
* rendered.
*
* @method _initBody
* @protected
*/
_initBody : function () {
this._body = create(substitute(
Console.BODY_TEMPLATE,
Console.CHROME_CLASSES));
this.get(CONTENT_BOX).appendChild(this._body);
},
/**
* Create the DOM structure for the footer elements.
*
* @method _initFoot
* @protected
*/
_initFoot : function () {
var info = merge(Console.CHROME_CLASSES, {
id_guid : Y.guid(),
str_pause : this.get('strings.pause'),
str_clear : this.get('strings.clear')
});
this._foot = create(substitute(Console.FOOTER_TEMPLATE,info));
this.get(CONTENT_BOX).appendChild(this._foot);
},
/**
* Determine if incoming log messages are within the configured logLevel
* to be buffered for printing.
*
* @method _isInLogLevel
* @protected
*/
_isInLogLevel : function (e) {
var cat = e.cat, lvl = this.get('logLevel');
if (lvl !== INFO) {
cat = cat || INFO;
if (isString(cat)) {
cat = cat.toLowerCase();
}
if ((cat === WARN && lvl === ERROR) ||
(cat === INFO && lvl !== INFO)) {
return false;
}
}
return true;
},
/**
* Create a log entry message from the inputs including the following keys:
* <ul>
* <li>time - this moment</li>
* <li>message - leg message</li>
* <li>category - logLevel or custom category for the message</li>
* <li>source - when provided, the widget or util calling Y.log</li>
* <li>sourceAndDetail - same as source but can include instance info</li>
* <li>localTime - readable version of time</li>
* <li>elapsedTime - ms since last entry</li>
* <li>totalTime - ms since Console was instantiated or reset</li>
* </ul>
*
* @method _normalizeMessage
* @param e {Event} custom event containing the log message
* @return Object the message object
* @protected
*/
_normalizeMessage : function (e) {
var msg = e.msg,
cat = e.cat,
src = e.src,
m = {
time : new Date(),
message : msg,
category : cat || this.get('defaultCategory'),
sourceAndDetail : src || this.get('defaultSource'),
source : null,
localTime : null,
elapsedTime : null,
totalTime : null
};
// Extract m.source "Foo" from m.sourceAndDetail "Foo bar baz"
m.source = RE_INLINE_SOURCE.test(m.sourceAndDetail) ?
RegExp.$1 : m.sourceAndDetail;
m.localTime = m.time.toLocaleTimeString ?
m.time.toLocaleTimeString() : (m.time + '');
m.elapsedTime = m.time - this.get(LAST_TIME);
m.totalTime = m.time - this.get(START_TIME);
this._set(LAST_TIME,m.time);
return m;
},
/**
* Sets an interval for buffered messages to be output to the console.
*
* @method _schedulePrint
* @protected
*/
_schedulePrint : function () {
if (!this._printLoop && !this.get(PAUSED) && this.get('rendered')) {
this._printLoop = Y.later(
this.get('printTimeout'),
this, this.printBuffer,
this.get('printLimit'), true);
}
},
/**
* Translates message meta into the markup for a console entry.
*
* @method _createEntryHTML
* @param m {Object} object literal containing normalized message metadata
* @return String
* @protected
*/
_createEntryHTML : function (m) {
m = merge(
this._htmlEscapeMessage(m),
Console.ENTRY_CLASSES,
{
cat_class : this.getClassName(ENTRY,m.category),
src_class : this.getClassName(ENTRY,m.source)
});
return this.get('entryTemplate').replace(/\{(\w+)\}/g,
function (_,token) {
return token in m ? m[token] : '';
});
},
/**
* Scrolls to the most recent entry
*
* @method scrollToLatest
* @chainable
*/
scrollToLatest : function () {
var scrollTop = this.get('newestOnTop') ?
0 :
this._body.get('scrollHeight');
this._body.set('scrollTop', scrollTop);
},
/**
* Performs HTML escaping on strings in the message object.
*
* @method _htmlEscapeMessage
* @param m {Object} the normalized message object
* @return Object the message object with proper escapement
* @protected
*/
_htmlEscapeMessage : function (m) {
m.message = this._encodeHTML(m.message);
m.source = this._encodeHTML(m.source);
m.sourceAndDetail = this._encodeHTML(m.sourceAndDetail);
m.category = this._encodeHTML(m.category);
return m;
},
/**
* Removes the oldest message entries from the UI to maintain the limit
* specified in the consoleLimit configuration.
*
* @method _trimOldEntries
* @protected
*/
_trimOldEntries : function () {
// Turn off the logging system for the duration of this operation
// to prevent an infinite loop
Y.config.debug = false;
var bd = this._body,
limit = this.get('consoleLimit'),
debug = Y.config.debug,
entries,e,i,l;
if (bd) {
entries = bd.all(DOT+C_ENTRY);
l = entries.size() - limit;
if (l > 0) {
if (this.get('newestOnTop')) {
i = limit;
l = entries.size();
} else {
i = 0;
}
this._body.setStyle('display','none');
for (;i < l; ++i) {
e = entries.item(i);
if (e) {
e.remove();
}
}
this._body.setStyle('display','');
}
}
Y.config.debug = debug;
},
/**
* Returns the input string with ampersands (&), <, and > encoded
* as HTML entities.
*
* @method _encodeHTML
* @param s {String} the raw string
* @return String the encoded string
* @protected
*/
_encodeHTML : function (s) {
return isString(s) ?
s.replace(RE_AMP,ESC_AMP).
replace(RE_LT, ESC_LT).
replace(RE_GT, ESC_GT) :
s;
},
/**
* Clears the timeout for printing buffered messages.
*
* @method _cancelPrintLoop
* @protected
*/
_cancelPrintLoop : function () {
if (this._printLoop) {
this._printLoop.cancel();
this._printLoop = null;
}
},
/**
* Validates input value for style attribute. Accepts only values 'inline',
* 'block', and 'separate'.
*
* @method _validateStyle
* @param style {String} the proposed value
* @return {Boolean} pass/fail
* @protected
*/
_validateStyle : function (style) {
return style === 'inline' || style === 'block' || style === 'separate';
},
/**
* Event handler for clicking on the Pause checkbox to update the paused
* attribute.
*
* @method _onPauseClick
* @param e {Event} DOM event facade for the click event
* @protected
*/
_onPauseClick : function (e) {
this.set(PAUSED,e.target.get(CHECKED));
},
/**
* Event handler for clicking on the Clear button. Pass-through to
* <code>this.clearConsole()</code>.
*
* @method _onClearClick
* @param e {Event} DOM event facade for the click event
* @protected
*/
_onClearClick : function (e) {
this.clearConsole();
},
/**
* Event handler for clicking on the Collapse/Expand button. Sets the
* "collapsed" attribute accordingly.
*
* @method _onCollapseClick
* @param e {Event} DOM event facade for the click event
* @protected
*/
_onCollapseClick : function (e) {
this.set(COLLAPSED, !this.get(COLLAPSED));
},
/**
* Validator for logSource attribute.
*
* @method _validateLogSource
* @param v {Object} the desired logSource
* @return {Boolean} true if the input is an object with an <code>on</code>
* method
* @protected
*/
_validateLogSource: function (v) {
return v && Y.Lang.isFunction(v.on);
},
/**
* Setter method for logLevel attribute. Acceptable values are
* "error", "warn", and "info" (case
* insensitive). Other values are treated as "info".
*
* @method _setLogLevel
* @param v {String} the desired log level
* @return String One of Console.LOG_LEVEL_INFO, _WARN, or _ERROR
* @protected
*/
_setLogLevel : function (v) {
if (isString(v)) {
v = v.toLowerCase();
}
return (v === WARN || v === ERROR) ? v : INFO;
},
/**
* Getter method for useBrowserConsole attribute. Just a pass through to
* the YUI instance configuration setting.
*
* @method _getUseBrowserConsole
* @return {Boolean} or null if logSource is not a YUI instance
* @protected
*/
_getUseBrowserConsole: function () {
var logSource = this.get('logSource');
return logSource instanceof YUI ?
logSource.config.useBrowserConsole : null;
},
/**
* Setter method for useBrowserConsole attributes. Only functional if the
* logSource attribute points to a YUI instance. Passes the value down to
* the YUI instance. NOTE: multiple Console instances cannot maintain
* independent useBrowserConsole values, since it is just a pass through to
* the YUI instance configuration.
*
* @method _setUseBrowserConsole
* @param v {Boolean} false to disable browser console printing (default)
* @return {Boolean} true|false if logSource is a YUI instance
* @protected
*/
_setUseBrowserConsole: function (v) {
var logSource = this.get('logSource');
if (logSource instanceof YUI) {
v = !!v;
logSource.config.useBrowserConsole = v;
return v;
} else {
return Y.Attribute.INVALID_VALUE;
}
},
/**
* Set the height of the Console container. Set the body height to the
* difference between the configured height and the calculated heights of
* the header and footer.
* Overrides Widget.prototype._uiSetHeight.
*
* @method _uiSetHeight
* @param v {String|Number} the new height
* @protected
*/
_uiSetHeight : function (v) {
Console.superclass._uiSetHeight.apply(this,arguments);
if (this._head && this._foot) {
var h = this.get('boundingBox').get('offsetHeight') -
this._head.get('offsetHeight') -
this._foot.get('offsetHeight');
this._body.setStyle(HEIGHT,h+'px');
}
},
/**
* Over-ride default content box sizing to do nothing, since we're sizing
* the body section to fill out height ourselves.
*
* @method _uiSizeCB
* @protected
*/
_uiSizeCB : function() {
// Do Nothing. Ideally want to move to Widget-StdMod, which accounts for
// _uiSizeCB
},
/**
* Updates the UI if changes are made to any of the strings in the strings
* attribute.
*
* @method _afterStringsChange
* @param e {Event} Custom event for the attribute change
* @protected
*/
_afterStringsChange : function (e) {
var prop = e.subAttrName ? e.subAttrName.split(DOT)[1] : null,
cb = this.get(CONTENT_BOX),
before = e.prevVal,
after = e.newVal;
if ((!prop || prop === TITLE) && before.title !== after.title) {
cb.all(DOT+C_CONSOLE_TITLE).setHTML(after.title);
}
if ((!prop || prop === PAUSE) && before.pause !== after.pause) {
cb.all(DOT+C_PAUSE_LABEL).setHTML(after.pause);
}
if ((!prop || prop === CLEAR) && before.clear !== after.clear) {
cb.all(DOT+C_CLEAR).set('value',after.clear);
}
},
/**
* Updates the UI and schedules or cancels the print loop.
*
* @method _afterPausedChange
* @param e {Event} Custom event for the attribute change
* @protected
*/
_afterPausedChange : function (e) {
var paused = e.newVal;
if (e.src !== Y.Widget.SRC_UI) {
this._uiUpdatePaused(paused);
}
if (!paused) {
this._schedulePrint();
} else if (this._printLoop) {
this._cancelPrintLoop();
}
},
/**
* Checks or unchecks the paused checkbox
*
* @method _uiUpdatePaused
* @param on {Boolean} the new checked state
* @protected
*/
_uiUpdatePaused : function (on) {
var node = this._foot.all('input[type=checkbox].'+C_PAUSE);
if (node) {
node.set(CHECKED,on);
}
},
/**
* Calls this._trimOldEntries() in response to changes in the configured
* consoleLimit attribute.
*
* @method _afterConsoleLimitChange
* @param e {Event} Custom event for the attribute change
* @protected
*/
_afterConsoleLimitChange : function () {
this._trimOldEntries();
},
/**
* Updates the className of the contentBox, which should trigger CSS to
* hide or show the body and footer sections depending on the new value.
*
* @method _afterCollapsedChange
* @param e {Event} Custom event for the attribute change
* @protected
*/
_afterCollapsedChange : function (e) {
this._uiUpdateCollapsed(e.newVal);
},
/**
* Updates the UI to reflect the new Collapsed state
*
* @method _uiUpdateCollapsed
* @param v {Boolean} true for collapsed, false for expanded
* @protected
*/
_uiUpdateCollapsed : function (v) {
var bb = this.get('boundingBox'),
button = bb.all('button.'+C_COLLAPSE),
method = v ? 'addClass' : 'removeClass',
str = this.get('strings.'+(v ? 'expand' : 'collapse'));
bb[method](C_COLLAPSED);
if (button) {
button.setHTML(str);
}
this._uiSetHeight(v ? this._head.get('offsetHeight'): this.get(HEIGHT));
},
/**
* Makes adjustments to the UI if needed when the Console is hidden or shown
*
* @method _afterVisibleChange
* @param e {Event} the visibleChange event
* @protected
*/
_afterVisibleChange : function (e) {
Console.superclass._afterVisibleChange.apply(this,arguments);
this._uiUpdateFromHideShow(e.newVal);
},
/**
* Recalculates dimensions and updates appropriately when shown
*
* @method _uiUpdateFromHideShow
* @param v {Boolean} true for visible, false for hidden
* @protected
*/
_uiUpdateFromHideShow : function (v) {
if (v) {
this._uiSetHeight(this.get(HEIGHT));
}
},
/**
* Responds to log events by normalizing qualifying messages and passing
* them along through the entry event for buffering etc.
*
* @method _onLogEvent
* @param msg {String} the log message
* @param cat {String} OPTIONAL the category or logLevel of the message
* @param src {String} OPTIONAL the source of the message (e.g. widget name)
* @protected
*/
_onLogEvent : function (e) {
if (!this.get(DISABLED) && this._isInLogLevel(e)) {
var debug = Y.config.debug;
/* TODO: needed? */
Y.config.debug = false;
this.fire(ENTRY, {
message : this._normalizeMessage(e)
});
Y.config.debug = debug;
}
},
/**
* Clears the console, resets the startTime attribute, enables and
* unpauses the widget.
*
* @method _defResetFn
* @protected
*/
_defResetFn : function () {
this.clearConsole();
this.set(START_TIME,new Date());
this.set(DISABLED,false);
this.set(PAUSED,false);
},
/**
* Buffers incoming message objects and schedules the printing.
*
* @method _defEntryFn
* @param e {Event} The Custom event carrying the message in its payload
* @protected
*/
_defEntryFn : function (e) {
if (e.message) {
this.buffer.push(e.message);
this._schedulePrint();
}
}
},
// Y.Console static properties
{
/**
* The identity of the widget.
*
* @property NAME
* @type String
* @static
*/
NAME : CONSOLE,
/**
* Static identifier for logLevel configuration setting to allow all
* incoming messages to generate Console entries.
*
* @property LOG_LEVEL_INFO
* @type String
* @static
*/
LOG_LEVEL_INFO : INFO,
/**
* Static identifier for logLevel configuration setting to allow only
* incoming messages of logLevel "warn" or "error"
* to generate Console entries.
*
* @property LOG_LEVEL_WARN
* @type String
* @static
*/
LOG_LEVEL_WARN : WARN,
/**
* Static identifier for logLevel configuration setting to allow only
* incoming messages of logLevel "error" to generate
* Console entries.
*
* @property LOG_LEVEL_ERROR
* @type String
* @static
*/
LOG_LEVEL_ERROR : ERROR,
/**
* Map (object) of classNames used to populate the placeholders in the
* Console.ENTRY_TEMPLATE markup when rendering a new Console entry.
*
* <p>By default, the keys contained in the object are:</p>
* <ul>
* <li>entry_class</li>
* <li>entry_meta_class</li>
* <li>entry_cat_class</li>
* <li>entry_src_class</li>
* <li>entry_time_class</li>
* <li>entry_content_class</li>
* </ul>
*
* @property ENTRY_CLASSES
* @type Object
* @static
*/
ENTRY_CLASSES : {
entry_class : C_ENTRY,
entry_meta_class : C_ENTRY_META,
entry_cat_class : C_ENTRY_CAT,
entry_src_class : C_ENTRY_SRC,
entry_time_class : C_ENTRY_TIME,
entry_content_class : C_ENTRY_CONTENT
},
/**
* Map (object) of classNames used to populate the placeholders in the
* Console.HEADER_TEMPLATE, Console.BODY_TEMPLATE, and
* Console.FOOTER_TEMPLATE markup when rendering the Console UI.
*
* <p>By default, the keys contained in the object are:</p>
* <ul>
* <li>console_hd_class</li>
* <li>console_bd_class</li>
* <li>console_ft_class</li>
* <li>console_controls_class</li>
* <li>console_checkbox_class</li>
* <li>console_pause_class</li>
* <li>console_pause_label_class</li>
* <li>console_button_class</li>
* <li>console_clear_class</li>
* <li>console_collapse_class</li>
* <li>console_title_class</li>
* </ul>
*
* @property CHROME_CLASSES
* @type Object
* @static
*/
CHROME_CLASSES : {
console_hd_class : C_CONSOLE_HD,
console_bd_class : C_CONSOLE_BD,
console_ft_class : C_CONSOLE_FT,
console_controls_class : C_CONSOLE_CONTROLS,
console_checkbox_class : C_CHECKBOX,
console_pause_class : C_PAUSE,
console_pause_label_class : C_PAUSE_LABEL,
console_button_class : C_BUTTON,
console_clear_class : C_CLEAR,
console_collapse_class : C_COLLAPSE,
console_title_class : C_CONSOLE_TITLE
},
/**
* Markup template used to generate the DOM structure for the header
* section of the Console when it is rendered. The template includes
* these {placeholder}s:
*
* <ul>
* <li>console_button_class - contributed by Console.CHROME_CLASSES</li>
* <li>console_collapse_class - contributed by Console.CHROME_CLASSES</li>
* <li>console_hd_class - contributed by Console.CHROME_CLASSES</li>
* <li>console_title_class - contributed by Console.CHROME_CLASSES</li>
* <li>str_collapse - pulled from attribute strings.collapse</li>
* <li>str_title - pulled from attribute strings.title</li>
* </ul>
*
* @property HEADER_TEMPLATE
* @type String
* @static
*/
HEADER_TEMPLATE :
'<div class="{console_hd_class}">'+
'<h4 class="{console_title_class}">{str_title}</h4>'+
'<button type="button" class="'+
'{console_button_class} {console_collapse_class}">{str_collapse}'+
'</button>'+
'</div>',
/**
* Markup template used to generate the DOM structure for the Console body
* (where the messages are inserted) when it is rendered. The template
* includes only the {placeholder} "console_bd_class", which is
* constributed by Console.CHROME_CLASSES.
*
* @property BODY_TEMPLATE
* @type String
* @static
*/
BODY_TEMPLATE : '<div class="{console_bd_class}"></div>',
/**
* Markup template used to generate the DOM structure for the footer
* section of the Console when it is rendered. The template includes
* many of the {placeholder}s from Console.CHROME_CLASSES as well as:
*
* <ul>
* <li>id_guid - generated unique id, relates the label and checkbox</li>
* <li>str_pause - pulled from attribute strings.pause</li>
* <li>str_clear - pulled from attribute strings.clear</li>
* </ul>
*
* @property FOOTER_TEMPLATE
* @type String
* @static
*/
FOOTER_TEMPLATE :
'<div class="{console_ft_class}">'+
'<div class="{console_controls_class}">'+
'<label class="{console_pause_label_class}"><input type="checkbox" class="{console_checkbox_class} {console_pause_class}" value="1" id="{id_guid}"> {str_pause}</label>' +
'<button type="button" class="'+
'{console_button_class} {console_clear_class}">{str_clear}'+
'</button>'+
'</div>'+
'</div>',
/**
* Default markup template used to create the DOM structure for Console
* entries. The markup contains {placeholder}s for content and classes
* that are replaced via Y.Lang.sub. The default template contains
* the {placeholder}s identified in Console.ENTRY_CLASSES as well as the
* following placeholders that will be populated by the log entry data:
*
* <ul>
* <li>cat_class</li>
* <li>src_class</li>
* <li>totalTime</li>
* <li>elapsedTime</li>
* <li>localTime</li>
* <li>sourceAndDetail</li>
* <li>message</li>
* </ul>
*
* @property ENTRY_TEMPLATE
* @type String
* @static
*/
ENTRY_TEMPLATE : ENTRY_TEMPLATE_STR,
/**
* Static property used to define the default attribute configuration of
* the Widget.
*
* @property ATTRS
* @Type Object
* @static
*/
ATTRS : {
/**
* Name of the custom event that will communicate log messages.
*
* @attribute logEvent
* @type String
* @default "yui:log"
*/
logEvent : {
value : 'yui:log',
writeOnce : true,
validator : isString
},
/**
* Object that will emit the log events. By default the YUI instance.
* To have a single Console capture events from all YUI instances, set
* this to the Y.Global object.
*
* @attribute logSource
* @type EventTarget
* @default Y
*/
logSource : {
value : Y,
writeOnce : true,
validator : function (v) {
return this._validateLogSource(v);
}
},
/**
* Collection of strings used to label elements in the Console UI.
* Default collection contains the following name:value pairs:
*
* <ul>
* <li>title : "Log Console"</li>
* <li>pause : "Pause"</li>
* <li>clear : "Clear"</li>
* <li>collapse : "Collapse"</li>
* <li>expand : "Expand"</li>
* </ul>
*
* @attribute strings
* @type Object
*/
strings : {
valueFn: function() { return Y.Intl.get("console"); }
},
/**
* Boolean to pause the outputting of new messages to the console.
* When paused, messages will accumulate in the buffer.
*
* @attribute paused
* @type boolean
* @default false
*/
paused : {
value : false,
validator : L.isBoolean
},
/**
* If a category is not specified in the Y.log(..) statement, this
* category will be used. Categories "info",
* "warn", and "error" are also called log level.
*
* @attribute defaultCategory
* @type String
* @default "info"
*/
defaultCategory : {
value : INFO,
validator : isString
},
/**
* If a source is not specified in the Y.log(..) statement, this
* source will be used.
*
* @attribute defaultSource
* @type String
* @default "global"
*/
defaultSource : {
value : 'global',
validator : isString
},
/**
* Markup template used to create the DOM structure for Console entries.
*
* @attribute entryTemplate
* @type String
* @default Console.ENTRY_TEMPLATE
*/
entryTemplate : {
value : ENTRY_TEMPLATE_STR,
validator : isString
},
/**
* Minimum entry log level to render into the Console. The initial
* logLevel value for all Console instances defaults from the
* Y.config.logLevel YUI configuration, or Console.LOG_LEVEL_INFO if
* that configuration is not set.
*
* Possible values are "info", "warn",
* "error" (case insensitive), or their corresponding statics
* Console.LOG_LEVEL_INFO and so on.
*
* @attribute logLevel
* @type String
* @default Y.config.logLevel or Console.LOG_LEVEL_INFO
*/
logLevel : {
value : Y.config.logLevel || INFO,
setter : function (v) {
return this._setLogLevel(v);
}
},
/**
* Millisecond timeout between iterations of the print loop, moving
* entries from the buffer to the UI.
*
* @attribute printTimeout
* @type Number
* @default 100
*/
printTimeout : {
value : 100,
validator : isNumber
},
/**
* Maximum number of entries printed in each iteration of the print
* loop. This is used to prevent excessive logging locking the page UI.
*
* @attribute printLimit
* @type Number
* @default 50
*/
printLimit : {
value : 50,
validator : isNumber
},
/**
* Maximum number of Console entries allowed in the Console body at one
* time. This is used to keep acquired messages from exploding the
* DOM tree and impacting page performance.
*
* @attribute consoleLimit
* @type Number
* @default 300
*/
consoleLimit : {
value : 300,
validator : isNumber
},
/**
* New entries should display at the top of the Console or the bottom?
*
* @attribute newestOnTop
* @type Boolean
* @default true
*/
newestOnTop : {
value : true
},
/**
* When new entries are added to the Console UI, should they be
* scrolled into view?
*
* @attribute scrollIntoView
* @type Boolean
* @default true
*/
scrollIntoView : {
value : true
},
/**
* The baseline time for this Console instance, used to measure elapsed
* time from the moment the console module is <code>use</code>d to the
* moment each new entry is logged (not rendered).
*
* This value is reset by the instance method myConsole.reset().
*
* @attribute startTime
* @type Date
* @default The moment the console module is <code>use</code>d
*/
startTime : {
value : new Date()
},
/**
* The precise time the last entry was logged. Used to measure elapsed
* time between log messages.
*
* @attribute lastTime
* @type Date
* @default The moment the console module is <code>use</code>d
*/
lastTime : {
value : new Date(),
readOnly: true
},
/**
* Controls the collapsed state of the Console
*
* @attribute collapsed
* @type Boolean
* @default false
*/
collapsed : {
value : false
},
/**
* String with units, or number, representing the height of the Console,
* inclusive of header and footer. If a number is provided, the default
* unit, defined by Widget's DEF_UNIT, property is used.
*
* @attribute height
* @default "300px"
* @type {String | Number}
*/
height: {
value: "300px"
},
/**
* String with units, or number, representing the width of the Console.
* If a number is provided, the default unit, defined by Widget's
* DEF_UNIT, property is used.
*
* @attribute width
* @default "300px"
* @type {String | Number}
*/
width: {
value: "300px"
},
/**
* Pass through to the YUI instance useBrowserConsole configuration.
* By default this is set to false, which will disable logging to the
* browser console when a Console instance is created. If the
* logSource is not a YUI instance, this has no effect.
*
* @attribute useBrowserConsole
* @type {Boolean}
* @default false
*/
useBrowserConsole : {
lazyAdd: false,
value: false,
getter : function () {
return this._getUseBrowserConsole();
},
setter : function (v) {
return this._setUseBrowserConsole(v);
}
},
/**
* Allows the Console to flow in the document. Available values are
* 'inline', 'block', and 'separate' (the default).
*
* @attribute style
* @type {String}
* @default 'separate'
*/
style : {
value : 'separate',
writeOnce : true,
validator : function (v) {
return this._validateStyle(v);
}
}
}
});
}, '3.10.3', {"requires": ["yui-log", "widget"], "skinnable": true, "lang": ["en", "es", "it", "ja"]});
| braz/mojito-helloworld | node_modules/mojito/node_modules/yui/console/console.js | JavaScript | mit | 44,387 |
version https://git-lfs.github.com/spec/v1
oid sha256:2c64720cce2738482dbc7541c56080f660da6fed0974372396b4ac583ea533b9
size 2042
| yogeshsaroya/new-cdnjs | ajax/libs/ace/1.1.3/snippets/sh.js | JavaScript | mit | 129 |
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M20 8h-3V6.21c0-2.61-1.91-4.94-4.51-5.19C9.51.74 7 3.08 7 6h2c0-1.13.6-2.24 1.64-2.7C12.85 2.31 15 3.9 15 6v2H4v14h16V8zm-2 12H6V10h12v10zm-6-3c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2z"
}), 'LockOpenSharp');
exports.default = _default; | oliviertassinari/material-ui | packages/mui-icons-material/lib/LockOpenSharp.js | JavaScript | mit | 656 |
version https://git-lfs.github.com/spec/v1
oid sha256:c54ab568b73e88af409e7615e9c6730d701234ebe9d64b131a08fccb0bef3deb
size 22927
| yogeshsaroya/new-cdnjs | ajax/libs/history.js/1.8/bundled/html4+html5/jquery.history.min.js | JavaScript | mit | 130 |
/*!
* jQuery UI Draggable @VERSION
*
* Copyright 2012, AUTHORS.txt (http://jqueryui.com/about)
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* http://docs.jquery.com/UI/Draggables
*
* Depends:
* jquery.ui.core.js
* jquery.ui.mouse.js
* jquery.ui.widget.js
*/
(function(c,x){c.widget("ui.draggable",c.ui.mouse,{widgetEventPrefix:"drag",options:{addClasses:!0,appendTo:"parent",axis:!1,connectToSortable:!1,containment:!1,cursor:"auto",cursorAt:!1,grid:!1,handle:!1,helper:"original",iframeFix:!1,opacity:!1,refreshPositions:!1,revert:!1,revertDuration:500,scope:"default",scroll:!0,scrollSensitivity:20,scrollSpeed:20,snap:!1,snapMode:"both",snapTolerance:20,stack:!1,zIndex:!1},_create:function(){"original"!=this.options.helper||/^(?:r|a|f)/.test(this.element.css("position"))||
(this.element[0].style.position="relative");this.options.addClasses&&this.element.addClass("ui-draggable");this.options.disabled&&this.element.addClass("ui-draggable-disabled");this._mouseInit()},destroy:function(){if(this.element.data("draggable"))return this.element.removeData("draggable").unbind(".draggable").removeClass("ui-draggable ui-draggable-dragging ui-draggable-disabled"),this._mouseDestroy(),this},_mouseCapture:function(b){var d=this.options;if(this.helper||d.disabled||c(b.target).is(".ui-resizable-handle"))return!1;
this.handle=this._getHandle(b);if(!this.handle)return!1;d.iframeFix&&c(!0===d.iframeFix?"iframe":d.iframeFix).each(function(){c('<div class="ui-draggable-iframeFix" style="background: #fff;"></div>').css({width:this.offsetWidth+"px",height:this.offsetHeight+"px",position:"absolute",opacity:"0.001",zIndex:1E3}).css(c(this).offset()).appendTo("body")});return!0},_mouseStart:function(b){var d=this.options;this.helper=this._createHelper(b);this._cacheHelperProportions();c.ui.ddmanager&&(c.ui.ddmanager.current=
this);this._cacheMargins();this.cssPosition=this.helper.css("position");this.scrollParent=this.helper.scrollParent();this.offset=this.positionAbs=this.element.offset();this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left};c.extend(this.offset,{click:{left:b.pageX-this.offset.left,top:b.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()});this.originalPosition=this.position=this._generatePosition(b);this.originalPageX=b.pageX;
this.originalPageY=b.pageY;d.cursorAt&&this._adjustOffsetFromHelper(d.cursorAt);d.containment&&this._setContainment();if(!1===this._trigger("start",b))return this._clear(),!1;this._cacheHelperProportions();c.ui.ddmanager&&!d.dropBehaviour&&c.ui.ddmanager.prepareOffsets(this,b);this.helper.addClass("ui-draggable-dragging");this._mouseDrag(b,!0);c.ui.ddmanager&&c.ui.ddmanager.dragStart(this,b);return!0},_mouseDrag:function(b,d){this.position=this._generatePosition(b);this.positionAbs=this._convertPositionTo("absolute");
if(!d){var a=this._uiHash();if(!1===this._trigger("drag",b,a))return this._mouseUp({}),!1;this.position=a.position}this.options.axis&&"y"==this.options.axis||(this.helper[0].style.left=this.position.left+"px");this.options.axis&&"x"==this.options.axis||(this.helper[0].style.top=this.position.top+"px");c.ui.ddmanager&&c.ui.ddmanager.drag(this,b);return!1},_mouseStop:function(b){var d=!1;c.ui.ddmanager&&!this.options.dropBehaviour&&(d=c.ui.ddmanager.drop(this,b));this.dropped&&(d=this.dropped,this.dropped=
!1);for(var a=this.element[0],e=!1;a&&(a=a.parentNode);)a==document&&(e=!0);if(!e&&"original"===this.options.helper)return!1;if("invalid"==this.options.revert&&!d||"valid"==this.options.revert&&d||!0===this.options.revert||c.isFunction(this.options.revert)&&this.options.revert.call(this.element,d)){var f=this;c(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){!1!==f._trigger("stop",b)&&f._clear()})}else!1!==this._trigger("stop",b)&&this._clear();return!1},
_mouseUp:function(b){!0===this.options.iframeFix&&c("div.ui-draggable-iframeFix").each(function(){this.parentNode.removeChild(this)});c.ui.ddmanager&&c.ui.ddmanager.dragStop(this,b);return c.ui.mouse.prototype._mouseUp.call(this,b)},cancel:function(){this.helper.is(".ui-draggable-dragging")?this._mouseUp({}):this._clear();return this},_getHandle:function(b){var d=this.options.handle&&c(this.options.handle,this.element).length?!1:!0;c(this.options.handle,this.element).find("*").andSelf().each(function(){this==
b.target&&(d=!0)});return d},_createHelper:function(b){var d=this.options;b=c.isFunction(d.helper)?c(d.helper.apply(this.element[0],[b])):"clone"==d.helper?this.element.clone().removeAttr("id"):this.element;b.parents("body").length||b.appendTo("parent"==d.appendTo?this.element[0].parentNode:d.appendTo);b[0]==this.element[0]||/(fixed|absolute)/.test(b.css("position"))||b.css("position","absolute");return b},_adjustOffsetFromHelper:function(b){"string"==typeof b&&(b=b.split(" "));c.isArray(b)&&(b={left:+b[0],
top:+b[1]||0});"left"in b&&(this.offset.click.left=b.left+this.margins.left);"right"in b&&(this.offset.click.left=this.helperProportions.width-b.right+this.margins.left);"top"in b&&(this.offset.click.top=b.top+this.margins.top);"bottom"in b&&(this.offset.click.top=this.helperProportions.height-b.bottom+this.margins.top)},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var b=this.offsetParent.offset();"absolute"==this.cssPosition&&this.scrollParent[0]!=document&&c.ui.contains(this.scrollParent[0],
this.offsetParent[0])&&(b.left+=this.scrollParent.scrollLeft(),b.top+=this.scrollParent.scrollTop());if(this.offsetParent[0]==document.body||this.offsetParent[0].tagName&&"html"==this.offsetParent[0].tagName.toLowerCase()&&c.browser.msie)b={top:0,left:0};return{top:b.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:b.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if("relative"==this.cssPosition){var b=this.element.position();return{top:b.top-
(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:b.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.element.css("marginLeft"),10)||0,top:parseInt(this.element.css("marginTop"),10)||0,right:parseInt(this.element.css("marginRight"),10)||0,bottom:parseInt(this.element.css("marginBottom"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),
height:this.helper.outerHeight()}},_setContainment:function(){var b=this.options;"parent"==b.containment&&(b.containment=this.helper[0].parentNode);if("document"==b.containment||"window"==b.containment)this.containment=["document"==b.containment?0:c(window).scrollLeft()-this.offset.relative.left-this.offset.parent.left,"document"==b.containment?0:c(window).scrollTop()-this.offset.relative.top-this.offset.parent.top,("document"==b.containment?0:c(window).scrollLeft())+c("document"==b.containment?document:
window).width()-this.helperProportions.width-this.margins.left,("document"==b.containment?0:c(window).scrollTop())+(c("document"==b.containment?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top];if(/^(document|window|parent)$/.test(b.containment)||b.containment.constructor==Array)b.containment.constructor==Array&&(this.containment=b.containment);else{var b=c(b.containment),d=b[0];if(d){b.offset();var a="hidden"!=c(d).css("overflow");this.containment=
[(parseInt(c(d).css("borderLeftWidth"),10)||0)+(parseInt(c(d).css("paddingLeft"),10)||0),(parseInt(c(d).css("borderTopWidth"),10)||0)+(parseInt(c(d).css("paddingTop"),10)||0),(a?Math.max(d.scrollWidth,d.offsetWidth):d.offsetWidth)-(parseInt(c(d).css("borderLeftWidth"),10)||0)-(parseInt(c(d).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left-this.margins.right,(a?Math.max(d.scrollHeight,d.offsetHeight):d.offsetHeight)-(parseInt(c(d).css("borderTopWidth"),10)||0)-(parseInt(c(d).css("paddingBottom"),
10)||0)-this.helperProportions.height-this.margins.top-this.margins.bottom];this.relative_container=b}}},_convertPositionTo:function(b,d){d||(d=this.position);var a="absolute"==b?1:-1,e="absolute"!=this.cssPosition||this.scrollParent[0]!=document&&c.ui.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,f=/(html|body)/i.test(e[0].tagName);return{top:d.top+this.offset.relative.top*a+this.offset.parent.top*a-(c.browser.safari&&526>c.browser.version&&"fixed"==this.cssPosition?
0:("fixed"==this.cssPosition?-this.scrollParent.scrollTop():f?0:e.scrollTop())*a),left:d.left+this.offset.relative.left*a+this.offset.parent.left*a-(c.browser.safari&&526>c.browser.version&&"fixed"==this.cssPosition?0:("fixed"==this.cssPosition?-this.scrollParent.scrollLeft():f?0:e.scrollLeft())*a)}},_generatePosition:function(b){var d=this.options,a="absolute"!=this.cssPosition||this.scrollParent[0]!=document&&c.ui.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,
e=/(html|body)/i.test(a[0].tagName),f=b.pageX,h=b.pageY;if(this.originalPosition){var g;this.containment&&(this.relative_container?(g=this.relative_container.offset(),g=[this.containment[0]+g.left,this.containment[1]+g.top,this.containment[2]+g.left,this.containment[3]+g.top]):g=this.containment,b.pageX-this.offset.click.left<g[0]&&(f=g[0]+this.offset.click.left),b.pageY-this.offset.click.top<g[1]&&(h=g[1]+this.offset.click.top),b.pageX-this.offset.click.left>g[2]&&(f=g[2]+this.offset.click.left),
b.pageY-this.offset.click.top>g[3]&&(h=g[3]+this.offset.click.top));d.grid&&(h=d.grid[1]?this.originalPageY+Math.round((h-this.originalPageY)/d.grid[1])*d.grid[1]:this.originalPageY,h=g?h-this.offset.click.top<g[1]||h-this.offset.click.top>g[3]?h-this.offset.click.top<g[1]?h+d.grid[1]:h-d.grid[1]:h:h,f=d.grid[0]?this.originalPageX+Math.round((f-this.originalPageX)/d.grid[0])*d.grid[0]:this.originalPageX,f=g?f-this.offset.click.left<g[0]||f-this.offset.click.left>g[2]?f-this.offset.click.left<g[0]?
f+d.grid[0]:f-d.grid[0]:f:f)}return{top:h-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(c.browser.safari&&526>c.browser.version&&"fixed"==this.cssPosition?0:"fixed"==this.cssPosition?-this.scrollParent.scrollTop():e?0:a.scrollTop()),left:f-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+(c.browser.safari&&526>c.browser.version&&"fixed"==this.cssPosition?0:"fixed"==this.cssPosition?-this.scrollParent.scrollLeft():e?0:a.scrollLeft())}},_clear:function(){this.helper.removeClass("ui-draggable-dragging");
this.helper[0]==this.element[0]||this.cancelHelperRemoval||this.helper.remove();this.helper=null;this.cancelHelperRemoval=!1},_trigger:function(b,d,a){a=a||this._uiHash();c.ui.plugin.call(this,b,[d,a]);"drag"==b&&(this.positionAbs=this._convertPositionTo("absolute"));return c.Widget.prototype._trigger.call(this,b,d,a)},plugins:{},_uiHash:function(b){return{helper:this.helper,position:this.position,originalPosition:this.originalPosition,offset:this.positionAbs}}});c.extend(c.ui.draggable,{version:"@VERSION"});
c.ui.plugin.add("draggable","connectToSortable",{start:function(b,d){var a=c(this).data("draggable"),e=a.options,f=c.extend({},d,{item:a.element});a.sortables=[];c(e.connectToSortable).each(function(){var d=c.data(this,"sortable");d&&!d.options.disabled&&(a.sortables.push({instance:d,shouldRevert:d.options.revert}),d.refreshPositions(),d._trigger("activate",b,f))})},stop:function(b,d){var a=c(this).data("draggable"),e=c.extend({},d,{item:a.element});c.each(a.sortables,function(){this.instance.isOver?
(this.instance.isOver=0,a.cancelHelperRemoval=!0,this.instance.cancelHelperRemoval=!1,this.shouldRevert&&(this.instance.options.revert=!0),this.instance._mouseStop(b),this.instance.options.helper=this.instance.options._helper,"original"==a.options.helper&&this.instance.currentItem.css({top:"auto",left:"auto"})):(this.instance.cancelHelperRemoval=!1,this.instance._trigger("deactivate",b,e))})},drag:function(b,d){var a=c(this).data("draggable"),e=this;c.each(a.sortables,function(f){this.instance.positionAbs=
a.positionAbs;this.instance.helperProportions=a.helperProportions;this.instance.offset.click=a.offset.click;this.instance._intersectsWith(this.instance.containerCache)?(this.instance.isOver||(this.instance.isOver=1,this.instance.currentItem=c(e).clone().removeAttr("id").appendTo(this.instance.element).data("sortable-item",!0),this.instance.options._helper=this.instance.options.helper,this.instance.options.helper=function(){return d.helper[0]},b.target=this.instance.currentItem[0],this.instance._mouseCapture(b,
!0),this.instance._mouseStart(b,!0,!0),this.instance.offset.click.top=a.offset.click.top,this.instance.offset.click.left=a.offset.click.left,this.instance.offset.parent.left-=a.offset.parent.left-this.instance.offset.parent.left,this.instance.offset.parent.top-=a.offset.parent.top-this.instance.offset.parent.top,a._trigger("toSortable",b),a.dropped=this.instance.element,a.currentItem=a.element,this.instance.fromOutside=a),this.instance.currentItem&&this.instance._mouseDrag(b)):this.instance.isOver&&
(this.instance.isOver=0,this.instance.cancelHelperRemoval=!0,this.instance.options.revert=!1,this.instance._trigger("out",b,this.instance._uiHash(this.instance)),this.instance._mouseStop(b,!0),this.instance.options.helper=this.instance.options._helper,this.instance.currentItem.remove(),this.instance.placeholder&&this.instance.placeholder.remove(),a._trigger("fromSortable",b),a.dropped=!1)})}});c.ui.plugin.add("draggable","cursor",{start:function(b,d){var a=c("body"),e=c(this).data("draggable").options;
a.css("cursor")&&(e._cursor=a.css("cursor"));a.css("cursor",e.cursor)},stop:function(b,d){var a=c(this).data("draggable").options;a._cursor&&c("body").css("cursor",a._cursor)}});c.ui.plugin.add("draggable","opacity",{start:function(b,d){var a=c(d.helper),e=c(this).data("draggable").options;a.css("opacity")&&(e._opacity=a.css("opacity"));a.css("opacity",e.opacity)},stop:function(b,d){var a=c(this).data("draggable").options;a._opacity&&c(d.helper).css("opacity",a._opacity)}});c.ui.plugin.add("draggable",
"scroll",{start:function(b,d){var a=c(this).data("draggable");a.scrollParent[0]!=document&&"HTML"!=a.scrollParent[0].tagName&&(a.overflowOffset=a.scrollParent.offset())},drag:function(b,d){var a=c(this).data("draggable"),e=a.options,f=!1;a.scrollParent[0]!=document&&"HTML"!=a.scrollParent[0].tagName?(e.axis&&"x"==e.axis||(a.overflowOffset.top+a.scrollParent[0].offsetHeight-b.pageY<e.scrollSensitivity?a.scrollParent[0].scrollTop=f=a.scrollParent[0].scrollTop+e.scrollSpeed:b.pageY-a.overflowOffset.top<
e.scrollSensitivity&&(a.scrollParent[0].scrollTop=f=a.scrollParent[0].scrollTop-e.scrollSpeed)),e.axis&&"y"==e.axis||(a.overflowOffset.left+a.scrollParent[0].offsetWidth-b.pageX<e.scrollSensitivity?a.scrollParent[0].scrollLeft=f=a.scrollParent[0].scrollLeft+e.scrollSpeed:b.pageX-a.overflowOffset.left<e.scrollSensitivity&&(a.scrollParent[0].scrollLeft=f=a.scrollParent[0].scrollLeft-e.scrollSpeed))):(e.axis&&"x"==e.axis||(b.pageY-c(document).scrollTop()<e.scrollSensitivity?f=c(document).scrollTop(c(document).scrollTop()-
e.scrollSpeed):c(window).height()-(b.pageY-c(document).scrollTop())<e.scrollSensitivity&&(f=c(document).scrollTop(c(document).scrollTop()+e.scrollSpeed))),e.axis&&"y"==e.axis||(b.pageX-c(document).scrollLeft()<e.scrollSensitivity?f=c(document).scrollLeft(c(document).scrollLeft()-e.scrollSpeed):c(window).width()-(b.pageX-c(document).scrollLeft())<e.scrollSensitivity&&(f=c(document).scrollLeft(c(document).scrollLeft()+e.scrollSpeed))));!1!==f&&c.ui.ddmanager&&!e.dropBehaviour&&c.ui.ddmanager.prepareOffsets(a,
b)}});c.ui.plugin.add("draggable","snap",{start:function(b,d){var a=c(this).data("draggable"),e=a.options;a.snapElements=[];c(e.snap.constructor!=String?e.snap.items||":data(draggable)":e.snap).each(function(){var b=c(this),d=b.offset();this!=a.element[0]&&a.snapElements.push({item:this,width:b.outerWidth(),height:b.outerHeight(),top:d.top,left:d.left})})},drag:function(b,d){for(var a=c(this).data("draggable"),e=a.options,f=e.snapTolerance,h=d.offset.left,g=h+a.helperProportions.width,q=d.offset.top,
r=q+a.helperProportions.height,k=a.snapElements.length-1;0<=k;k--){var l=a.snapElements[k].left,n=l+a.snapElements[k].width,m=a.snapElements[k].top,p=m+a.snapElements[k].height;if(l-f<h&&h<n+f&&m-f<q&&q<p+f||l-f<h&&h<n+f&&m-f<r&&r<p+f||l-f<g&&g<n+f&&m-f<q&&q<p+f||l-f<g&&g<n+f&&m-f<r&&r<p+f){if("inner"!=e.snapMode){var s=Math.abs(m-r)<=f,t=Math.abs(p-q)<=f,u=Math.abs(l-g)<=f,v=Math.abs(n-h)<=f;s&&(d.position.top=a._convertPositionTo("relative",{top:m-a.helperProportions.height,left:0}).top-a.margins.top);
t&&(d.position.top=a._convertPositionTo("relative",{top:p,left:0}).top-a.margins.top);u&&(d.position.left=a._convertPositionTo("relative",{top:0,left:l-a.helperProportions.width}).left-a.margins.left);v&&(d.position.left=a._convertPositionTo("relative",{top:0,left:n}).left-a.margins.left)}var w=s||t||u||v;"outer"!=e.snapMode&&(s=Math.abs(m-q)<=f,t=Math.abs(p-r)<=f,u=Math.abs(l-h)<=f,v=Math.abs(n-g)<=f,s&&(d.position.top=a._convertPositionTo("relative",{top:m,left:0}).top-a.margins.top),t&&(d.position.top=
a._convertPositionTo("relative",{top:p-a.helperProportions.height,left:0}).top-a.margins.top),u&&(d.position.left=a._convertPositionTo("relative",{top:0,left:l}).left-a.margins.left),v&&(d.position.left=a._convertPositionTo("relative",{top:0,left:n-a.helperProportions.width}).left-a.margins.left));!a.snapElements[k].snapping&&(s||t||u||v||w)&&a.options.snap.snap&&a.options.snap.snap.call(a.element,b,c.extend(a._uiHash(),{snapItem:a.snapElements[k].item}));a.snapElements[k].snapping=s||t||u||v||w}else a.snapElements[k].snapping&&
a.options.snap.release&&a.options.snap.release.call(a.element,b,c.extend(a._uiHash(),{snapItem:a.snapElements[k].item})),a.snapElements[k].snapping=!1}}});c.ui.plugin.add("draggable","stack",{start:function(b,d){var a=c(this).data("draggable").options,a=c.makeArray(c(a.stack)).sort(function(a,b){return(parseInt(c(a).css("zIndex"),10)||0)-(parseInt(c(b).css("zIndex"),10)||0)});if(a.length){var e=parseInt(a[0].style.zIndex)||0;c(a).each(function(a){this.style.zIndex=e+a});this[0].style.zIndex=e+a.length}}});
c.ui.plugin.add("draggable","zIndex",{start:function(b,d){var a=c(d.helper),e=c(this).data("draggable").options;a.css("zIndex")&&(e._zIndex=a.css("zIndex"));a.css("zIndex",e.zIndex)},stop:function(b,d){var a=c(this).data("draggable").options;a._zIndex&&c(d.helper).css("zIndex",a._zIndex)}})})(jQuery);
| cfox89/EE-Integration-to-API | themes/javascript/compressed/jquery/ui/jquery.ui.draggable.js | JavaScript | mit | 18,652 |
var Promise = require("bluebird");
var moment = require("moment");
var fs = Promise.promisifyAll(require("fs"));
var path = require("path");
var ent = require("ent");
var ObjectId = require("mongodb").ObjectID;
var User = require("../models/User");
var Fight = require("../models/Fight");
var FightRound = require("../models/FightRound");
var HangmanUserStatistics = require("../models/HangmanUserStatistics");
module.exports.getLeaderboard = function() {
return generateLeaderboard();
};
module.exports.getLoserboard = function() {
return generateLoserboard();
};
function generateLoserboard() {
var sort = 1;
return Promise.join(
fs.readFileAsync(path.join(__dirname, "./templates/loserboardTemplate.ejs")),
getFightAggregateData(sort),
getFightRoundAggregateData(sort),
getHangmanPrivateGameData(sort),
getHangmanAccuracyData(sort)
).spread(function(template, fightData, fightRoundData, hangmanPrivateGameData, hangmanGuessAccuracyData) {
return generateResults(template, fightData, fightRoundData, hangmanPrivateGameData, hangmanGuessAccuracyData);
});
}
function generateLeaderboard() {
var sort = -1;
return Promise.join(
fs.readFileAsync(path.join(__dirname, "./templates/leaderboardTemplate.ejs")),
getFightAggregateData(sort),
getFightRoundAggregateData(sort),
getHangmanPrivateGameData(sort),
getHangmanAccuracyData(sort)
).spread(function(template, fightData, fightRoundData, hangmanPrivateGameData, hangmanGuessAccuracyData) {
return generateResults(template, fightData, fightRoundData, hangmanPrivateGameData, hangmanGuessAccuracyData);
});
}
function generateResults(template, fightData, fightRoundData, hangmanPrivateGameData, hangmanGuessAccuracyData) {
// get all our users so that we can get our nicks to display
var userIds = [];
_.forEach(fightData, function(fightDataElement) {
userIds.push(fightDataElement._id);
});
_.forEach(fightRoundData, function(fightRoundDataElement) {
userIds.push(fightRoundDataElement._id);
});
_.forEach(hangmanPrivateGameData, function(hangmanPrivateGameDataElement) {
userIds.push(hangmanPrivateGameDataElement.userId);
});
_.forEach(hangmanGuessAccuracyData, function(hangmanGuessAccuracyDataElement) {
userIds.push(hangmanGuessAccuracyDataElement.userId);
});
userIds = _.uniq(userIds);
return User.find({ _id: { $in: userIds } }).then(function(users) {
var data;
console.log(users, fightData);
if (users) {
// add user nick to the data we have retrieved
_.forEach(fightData, function(fightDataElement) {
var userIndex = _.findIndex(users, function(user) {
return user._id == fightDataElement._id;
});
fightDataElement.userNick = users[userIndex].nick;
});
_.forEach(fightRoundData, function(fightRoundDataElement) {
var userIndex = _.findIndex(users, function(user) {
return user._id == fightRoundDataElement._id;
});
fightRoundDataElement.userNick = users[userIndex].nick;
});
_.forEach(hangmanPrivateGameData, function(hangmanPrivateGameDataElement) {
var userIndex = _.findIndex(users, function(user) {
return user._id == hangmanPrivateGameDataElement.userId;
});
hangmanPrivateGameDataElement.userNick = users[userIndex].nick;
});
_.forEach(hangmanGuessAccuracyData, function(hangmanGuessAccuracyDataElement) {
var userIndex = _.findIndex(users, function(user) {
return user._id == hangmanGuessAccuracyDataElement.userId;
});
hangmanGuessAccuracyDataElement.userNick = users[userIndex].nick;
});
data = {
fightRank1: fightData[0]
? fightData[0].userNick +
" " +
fightData[0].winPercentage +
"% (" +
fightData[0].wins +
"-" +
fightData[0].losses +
"-" +
fightData[0].ties +
")"
: "N/A",
fightRank2: fightData[1]
? fightData[1].userNick +
" " +
fightData[1].winPercentage +
"% (" +
fightData[1].wins +
"-" +
fightData[1].losses +
"-" +
fightData[1].ties +
")"
: "N/A",
fightRank3: fightData[2]
? fightData[2].userNick +
" " +
fightData[2].winPercentage +
"% (" +
fightData[2].wins +
"-" +
fightData[2].losses +
"-" +
fightData[2].ties +
")"
: "N/A",
fightRank4: fightData[3]
? fightData[3].userNick +
" " +
fightData[3].winPercentage +
"% (" +
fightData[3].wins +
"-" +
fightData[3].losses +
"-" +
fightData[3].ties +
")"
: "N/A",
fightRank5: fightData[4]
? fightData[4].userNick +
" " +
fightData[4].winPercentage +
"% (" +
fightData[4].wins +
"-" +
fightData[4].losses +
"-" +
fightData[4].ties +
")"
: "N/A",
fightRank6: fightData[5]
? fightData[5].userNick +
" " +
fightData[5].winPercentage +
"% (" +
fightData[5].wins +
"-" +
fightData[5].losses +
"-" +
fightData[5].ties +
")"
: "N/A",
fightRank7: fightData[6]
? fightData[6].userNick +
" " +
fightData[6].winPercentage +
"% (" +
fightData[6].wins +
"-" +
fightData[6].losses +
"-" +
fightData[6].ties +
")"
: "N/A",
fightRank8: fightData[7]
? fightData[7].userNick +
" " +
fightData[7].winPercentage +
"% (" +
fightData[7].wins +
"-" +
fightData[7].losses +
"-" +
fightData[7].ties +
")"
: "N/A",
fightRank9: fightData[8]
? fightData[8].userNick +
" " +
fightData[8].winPercentage +
"% (" +
fightData[8].wins +
"-" +
fightData[8].losses +
"-" +
fightData[8].ties +
")"
: "N/A",
fightRank10: fightData[9]
? fightData[9].userNick +
" " +
fightData[9].winPercentage +
"% (" +
fightData[9].wins +
"-" +
fightData[9].losses +
"-" +
fightData[9].ties +
")"
: "N/A",
fightRounds1: fightRoundData[0] ? fightRoundData[0].userNick + " " + fightRoundData[0].totalWins : "N/A",
fightRounds2: fightRoundData[1] ? fightRoundData[1].userNick + " " + fightRoundData[1].totalWins : "N/A",
fightRounds3: fightRoundData[2] ? fightRoundData[2].userNick + " " + fightRoundData[2].totalWins : "N/A",
fightRounds4: fightRoundData[3] ? fightRoundData[3].userNick + " " + fightRoundData[3].totalWins : "N/A",
fightRounds5: fightRoundData[4] ? fightRoundData[4].userNick + " " + fightRoundData[4].totalWins : "N/A",
hangmanGuessAccuracy1: hangmanGuessAccuracyData[0]
? hangmanGuessAccuracyData[0].userNick +
" " +
Math.round(hangmanGuessAccuracyData[0].guessAccuracy * 100) +
"%"
: "N/A",
hangmanGuessAccuracy2: hangmanGuessAccuracyData[1]
? hangmanGuessAccuracyData[1].userNick +
" " +
Math.round(hangmanGuessAccuracyData[1].guessAccuracy * 100) +
"%"
: "N/A",
hangmanGuessAccuracy3: hangmanGuessAccuracyData[2]
? hangmanGuessAccuracyData[2].userNick +
" " +
Math.round(hangmanGuessAccuracyData[2].guessAccuracy * 100) +
"%"
: "N/A",
hangmanGuessAccuracy4: hangmanGuessAccuracyData[3]
? hangmanGuessAccuracyData[3].userNick +
" " +
Math.round(hangmanGuessAccuracyData[3].guessAccuracy * 100) +
"%"
: "N/A",
hangmanGuessAccuracy5: hangmanGuessAccuracyData[4]
? hangmanGuessAccuracyData[4].userNick +
" " +
Math.round(hangmanGuessAccuracyData[4].guessAccuracy * 100) +
"%"
: "N/A",
hangmanPrivateGames1: hangmanPrivateGameData[0]
? hangmanPrivateGameData[0].userNick + " " + Math.round(hangmanPrivateGameData[0].winPercentage * 100) + "%"
: "N/A",
hangmanPrivateGames2: hangmanPrivateGameData[1]
? hangmanPrivateGameData[1].userNick + " " + Math.round(hangmanPrivateGameData[1].winPercentage * 100) + "%"
: "N/A",
hangmanPrivateGames3: hangmanPrivateGameData[2]
? hangmanPrivateGameData[2].userNick + " " + Math.round(hangmanPrivateGameData[2].winPercentage * 100) + "%"
: "N/A",
hangmanPrivateGames4: hangmanPrivateGameData[3]
? hangmanPrivateGameData[3].userNick + " " + Math.round(hangmanPrivateGameData[3].winPercentage * 100) + "%"
: "N/A",
hangmanPrivateGames5: hangmanPrivateGameData[4]
? hangmanPrivateGameData[4].userNick + " " + Math.round(hangmanPrivateGameData[4].winPercentage * 100) + "%"
: "N/A"
};
} else {
data = {
fightRank1: "N/A",
fightRank2: "N/A",
fightRank3: "N/A",
fightRank4: "N/A",
fightRank5: "N/A",
fightRounds1: "N/A",
fightRounds2: "N/A",
fightRounds3: "N/A",
fightRounds4: "N/A",
fightRounds5: "N/A",
hangmanGuessAccuracy1: "N/A",
hangmanGuessAccuracy2: "N/A",
hangmanGuessAccuracy3: "N/A",
hangmanGuessAccuracy4: "N/A",
hangmanGuessAccuracy5: "N/A",
hangmanPrivateGames1: "N/A",
hangmanPrivateGames2: "N/A",
hangmanPrivateGames3: "N/A",
hangmanPrivateGames4: "N/A",
hangmanPrivateGames5: "N/A"
};
}
return ent.encode(_.template(template)(data));
}); // end find Users
}
function getFightAggregateData(sort) {
return new Promise(function(resolve, reject) {
Fight.aggregate(
[
{
$project: {
winningUser: "$winningUser",
losingUser: {
$cond: [
{ $ne: ["$winningUser", null] },
{ $cond: [{ $ne: ["$winningUser", "$challenger"] }, "$challenger", "$opponent"] },
null
]
},
opponentUser: "$opponent",
challengerUser: "$challenger"
}
}
],
function(err, fightData) {
if (err) return reject(err);
resolve(fightData);
}
);
}).then(function(fightData) {
if (fightData) {
var userStats = {};
_.forEach(fightData, function(fightDataElement) {
if (!userStats[fightDataElement.opponentUser]) {
userStats[fightDataElement.opponentUser] = {};
userStats[fightDataElement.opponentUser].wins = 0;
userStats[fightDataElement.opponentUser].losses = 0;
userStats[fightDataElement.opponentUser].ties = 0;
userStats[fightDataElement.opponentUser].totalGames = 0;
userStats[fightDataElement.opponentUser]._id = fightDataElement.opponentUser;
}
if (!userStats[fightDataElement.challengerUser]) {
userStats[fightDataElement.challengerUser] = {};
userStats[fightDataElement.challengerUser].wins = 0;
userStats[fightDataElement.challengerUser].losses = 0;
userStats[fightDataElement.challengerUser].ties = 0;
userStats[fightDataElement.challengerUser].totalGames = 0;
userStats[fightDataElement.challengerUser]._id = fightDataElement.challengerUser;
}
if (fightDataElement.winningUser) {
userStats[fightDataElement.winningUser].wins++;
userStats[fightDataElement.winningUser].totalGames++;
userStats[fightDataElement.losingUser].losses++;
userStats[fightDataElement.losingUser].totalGames++;
} else {
userStats[fightDataElement.opponentUser].ties++;
userStats[fightDataElement.opponentUser].totalGames++;
userStats[fightDataElement.challengerUser].ties++;
userStats[fightDataElement.challengerUser].totalGames++;
}
userStats[fightDataElement.opponentUser].winPercentage =
userStats[fightDataElement.opponentUser].wins > 0
? Math.round(
((userStats[fightDataElement.opponentUser].wins + userStats[fightDataElement.opponentUser].ties * 0.5) /
userStats[fightDataElement.opponentUser].totalGames) *
100
)
: 0;
userStats[fightDataElement.challengerUser].winPercentage =
userStats[fightDataElement.challengerUser].wins > 0
? Math.round(
((userStats[fightDataElement.challengerUser].wins +
userStats[fightDataElement.challengerUser].ties * 0.5) /
userStats[fightDataElement.challengerUser].totalGames) *
100
)
: 0;
});
var sortString = sort != -1;
var usersWithMoreThan10Games = _.filter(userStats, function(user) {
return user.totalGames >= 10;
});
return _.take(_.sortByOrder(usersWithMoreThan10Games, ["winPercentage"], [sortString]), 10);
}
return null;
});
}
function getFightRoundAggregateData(sort) {
return new Promise(function(resolve, reject) {
FightRound.aggregate(
[
{ $match: { winningUser: { $ne: null } } },
{ $group: { _id: "$winningUser", totalWins: { $sum: 1 } } },
{ $sort: { totalWins: sort } },
{ $limit: 5 }
],
function(err, fightRoundData) {
if (err) return reject(err);
resolve(fightRoundData);
}
);
});
}
function getHangmanPrivateGameData(sort) {
return new Promise(function(resolve, reject) {
HangmanUserStatistics.aggregate(
[
{
$match: {
$or: [{ privateGameWinCount: { $gt: 0 } }, { privateGameLossCount: { $gt: 0 } }]
}
},
{
$project: {
userId: "$user",
winPercentage: {
$cond: [
{ $gt: ["$privateGameWinCount", 0] },
{
$divide: [
"$privateGameWinCount",
{
$add: ["$privateGameWinCount", "$privateGameLossCount"]
}
]
},
0
]
}
}
},
{ $sort: { winPercentage: sort } },
{ $limit: 5 }
],
function(err, hangmanPrivateGameData) {
if (err) return reject(err);
resolve(hangmanPrivateGameData);
}
);
});
}
function getHangmanAccuracyData(sort) {
return new Promise(function(resolve, reject) {
HangmanUserStatistics.aggregate(
[
{
$match: {
$or: [{ guessHits: { $gt: 0 } }, { guessMisses: { $gt: 0 } }]
}
},
{
$project: {
userId: "$user",
guessAccuracy: {
$cond: [
{ $gt: ["$guessHits", 0] },
{
$divide: ["$guessHits", { $add: ["$guessMisses", "$guessHits"] }]
},
0
]
}
}
},
{ $sort: { guessAccuracy: sort } },
{ $limit: 5 }
],
function(err, hangmanAccuracyData) {
if (err) return reject(err);
resolve(hangmanAccuracyData);
}
);
});
}
| djbielejeski/bunker | server/services/leaderboardService.js | JavaScript | mit | 14,247 |
import _ from 'underscore';
if (typeof _ === 'undefined') {
if (typeof Package.underscore === 'undefined') {
throw new Error('underscore is missing');
}
}
export default _ || Package.underscore._;
| kamilkisiela/angular-meteor | packages/angular-meteor/src/lib/underscore.js | JavaScript | mit | 207 |
'use strict';
/*global Subledger*/
angular.module('banker').factory('subledgerServices', ['$http', 'toaster', function($http, toaster) {
var subledger = new Subledger();
var credentials = {};
var cred = {};
var setCredentials = function(data) {
subledger.setCredentials(data.key_id, data.secret_id);
cred = data;
};
var getSystemBalance = function(org_id, book_id, account_id) {
return subledger.organization(org_id).book(book_id).account(account_id);
};
var createAndPostTransaction = function(org_id, book_id) {
return subledger.organization(org_id).book(book_id).journalEntry();
};
var getJournalReports = function(org_id, book_id, account_id) {
var org = subledger.organization(org_id);
var book = org.book(book_id);
var account = book.account(account_id);
return account.line();
};
var getCredentials = function() {
return $http.get('/bank/credentials').success(function(data, status, header, config) {
credentials = data;
});
};
//Get SystemBalance
var getBalance = function(account, cb) {
var date = new Date().toISOString();
getSystemBalance(cred.org_id, cred.book_id, account).balance({
description: 'USD',
at: date
}, function(error, apiRes) {
if (error) {
// toaster.pop('error', 'An Error Occurred' + error);
return error;
} else {
var amount = parseInt(apiRes.balance.value.amount);
cb(amount);
}
});
};
/* WITHDRAW and DEPOSIT in and Out of the Syetem.
Performs Crediting and Debiting of Accounts
Action == credit or Debit
transaction = {
amount: Amount to Credit/Debit
reason : Reason for Debiting or Crediting If Its from a Distributor to a User other transactions do not have reasons
}
inititorAccount ="Account that initiated the transaction which can be a banker"
recipientAccoutn = "Accoutn that accepts the transation"
initiatorl: this is the logged in user that authorises the transaction.
cb : callback
*/
var bankerAction = function(action, transaction, initiatorAccount, recipientAccount, initiator, cb) {
var otherAction = action === 'debit' ? 'credit' : 'debit';
var description = (action === 'debit') ? transaction.reason || 'Cash Withrawal from Bank' : transaction.reason || 'Cash Deposit To Bank';
var initiatorToString = JSON.stringify({
name: initiator.displayName,
email: initiator.email,
description: description
});
createAndPostTransaction(cred.org_id, cred.book_id).createAndPost({
'effective_at': new Date().toISOString(),
'description': initiatorToString,
'reference': 'http://andonation-mando.herokuapp.com',
'lines': [{
'account': recipientAccount,
'description': initiatorToString,
'reference': 'http://andonation-mando.herokuapp.com',
'value': {
'type': action,
'amount': transaction.amount
}
}, {
'account': initiatorAccount,
'description': initiatorToString,
'reference': 'http://andonation-mando.herokuapp.com',
'value': {
'type': otherAction,
'amount': transaction.amount
}
}]
}, function(error, apiRes) {
if (error) {
return error;
} else {
cb(apiRes);
}
});
};
//Get Journal Reports for any Transaction.
// PARAMs account to get the journal and a callback
var getJournals = function(account, cb) {
getJournalReports(cred.org_id, cred.book_id, account).get({
'description': 'USD',
'action': 'before',
'effective_at': new Date().toISOString()
}, function(error, apiRes) {
if (error) {
return error;
} else {
for (var i = 0; i < apiRes.posted_lines.length; i++) {
try {
var stringToObj = JSON.parse(apiRes.posted_lines[i].description);
apiRes.posted_lines[i].description = stringToObj;
} catch (e) {
apiRes.posted_lines[i].description = {
'name': 'anonymous',
'description': apiRes.posted_lines[i].description
};
}
}
cb(apiRes);
}
});
};
return {
getSystemBalance: getSystemBalance,
createAndPostTransaction: createAndPostTransaction,
getJournalReports: getJournalReports,
getCredentials: getCredentials,
setCredentials: setCredentials,
getBalance: getBalance,
bankerAction: bankerAction,
getJournals: getJournals
};
}]);
| hisabimbola/mando | public/modules/banker/services/subledger.client.services.js | JavaScript | mit | 4,565 |
/* eslint-disable no-unused-expressions, max-len */
import React from 'react';
import chai, { expect } from 'chai';
import { merge } from 'lodash';
import chaiEnzyme from 'chai-enzyme';
import { mount, shallow } from 'enzyme';
chai.use(chaiEnzyme());
import Tooltip from '../src/tooltip';
describe('<Tooltip />', () => {
describe('basic behavior', () => {
it('does not render if props.show is false', () => {
const wrapper = shallow(<Tooltip show={false} />);
expect(wrapper).to.have.style('visibility', 'hidden');
});
it('renders if props.show is true', () => {
const wrapper = shallow(<Tooltip show />);
expect(wrapper).to.have.style('visibility', 'visible');
});
it('updates position/style if any properties neceessary for calculating position/style is updated', () => {
const wrapper = mount(
<Tooltip
bounds={{ x: [0, 1000], y: [0, 800] }}
mouseX={5}
mouseY={5}
show
/>
);
let style = wrapper.state('style');
Object.entries({
bounds: {
x: [200, 300],
y: [600, 900],
},
mouseX: 20,
mouseY: 30,
offsetX: 5,
offsetY: 6,
paddingX: 20,
paddingY: 20,
style: { backgroundColor: 'red' },
}).forEach(([key, value]) => {
expect(wrapper.state('style')).to.equal(style);
wrapper.setProps({
[key]: value
});
const updatedStyle = wrapper.state('style');
expect(updatedStyle).to.not.equal(style);
style = updatedStyle;
});
});
it('does not update style if a property not necessary for calculating styles is updated', () => {
const wrapper = mount(
<Tooltip
bounds={{ x: [0, 1000], y: [0, 800] }}
mouseX={5}
mouseY={5}
show
/>
);
const style = wrapper.state('style');
Object.entries({
className: 'new-class-name',
}).forEach(([key, value]) => {
expect(wrapper.state('style')).to.equal(style);
wrapper.setProps({
[key]: value
});
const nonUpdatedStyle = wrapper.state('style');
expect(nonUpdatedStyle).to.equal(style);
});
});
});
describe('position', () => {
const baseParams = {
bounds: {
x: [0, 1200],
y: [0, 600],
},
height: 100,
mouseX: 300,
mouseY: 300,
offsetX: 0,
offsetY: 0,
paddingX: 0,
paddingY: 0,
width: 100,
};
it('positions the tooltip centered around mouseX', () => {
const position = Tooltip.getPosition(baseParams);
const [x] = position;
expect(position)
.to.be.an('array')
.to.have.length(2);
expect(x).to.equal(250);
});
it('positions the tooltip offsetY above/below from mouseY', () => {
// above
const [, yAbove] = Tooltip.getPosition(Object.assign({}, baseParams, { offsetY: 25 }));
expect(yAbove).to.equal(175);
// below
const [, yBelow] = Tooltip.getPosition(Object.assign({}, baseParams, { offsetY: -25 }));
expect(yBelow).to.equal(325);
});
it('shifts the tooltip offsetX pixels in the x-direction', () => {
const assertions = [
{
params: {
offsetX: 10
},
expectation: ([x]) => {
expect(x).to.equal(260);
},
},
{
params: {
offsetX: 0
},
expectation: ([x]) => {
expect(x).to.equal(250);
},
},
{
params: {
offsetX: -10
},
expectation: ([x]) => {
expect(x).to.equal(240);
},
}
];
assertions.forEach((assert) => {
assert.expectation(Tooltip.getPosition(
Object.assign({}, baseParams, assert.params)
));
});
});
it('shifts the tooltip offsetY pixels in the y-direction', () => {
const assertions = [
{
params: {
offsetY: 10
},
expectation: ([, y]) => {
expect(y).to.equal(190);
},
},
{
params: {
offsetY: 0
},
expectation: ([, y]) => {
expect(y).to.equal(200);
},
},
{
params: {
offsetY: -10
},
expectation: ([, y]) => {
expect(y).to.equal(310);
},
}
];
assertions.forEach((assert) => {
assert.expectation(Tooltip.getPosition(
Object.assign({}, baseParams, assert.params)
));
});
});
it('guards placement of the tooltip within x-bounds', () => {
const assertions = [
{
params: {
mouseX: 25,
},
expectation: ([x]) => {
expect(x).to.equal(0);
},
},
{
params: {
mouseX: 25,
paddingX: 50,
},
expectation: ([x]) => {
expect(x).to.equal(50);
},
},
{
params: {
mouseX: 1175,
},
expectation: ([x]) => {
expect(x).to.equal(1100);
},
},
{
params: {
mouseX: 1000,
offsetX: 200,
},
expectation: ([x]) => {
expect(x).to.equal(1100);
},
},
{
params: {
bounds: {
x: [400, 700],
},
mouseX: 200,
},
expectation: ([x]) => {
expect(x).to.equal(400);
},
},
{
params: {
bounds: {
x: [400, 700],
},
mouseX: 800,
},
expectation: ([x]) => {
expect(x).to.equal(600);
},
}
];
assertions.forEach((assert) => {
assert.expectation(Tooltip.getPosition(
merge({}, baseParams, assert.params)
));
});
});
it('guards placement of the tooltip within y-bounds', () => {
const assertions = [
{
params: {
mouseY: 25,
paddingY: 10,
},
expectation: ([, y]) => {
expect(y).to.equal(35);
},
},
{
params: {
mouseY: 25,
offsetY: 10,
paddingY: 50,
},
expectation: ([, y]) => {
expect(y).to.equal(75);
},
},
{
params: {
mouseY: 550,
offsetY: -10,
},
expectation: ([, y]) => {
expect(y).to.equal(440);
},
},
{
params: {
bounds: {
y: [200, 400],
},
mouseY: 100,
},
expectation: ([, y]) => {
expect(y).to.equal(200);
},
},
{
params: {
bounds: {
y: [200, 400],
},
mouseY: 600,
},
expectation: ([, y]) => {
expect(y).to.equal(300);
},
}
];
assertions.forEach((assert) => {
assert.expectation(Tooltip.getPosition(
merge({}, baseParams, assert.params)
));
});
});
});
});
| ihmeuw/beaut | src/ui/tooltip/test/tooltip.test.js | JavaScript | mit | 7,495 |
var sip=require('sip');
var util=require('util');
var contexts = {};
function makeContextId(msg) {
var via = msg.headers.via[0];
return [via.params.branch, via.protocol, via.host, via.port, msg.headers['call-id'], msg.headers.cseq.seq];
}
function defaultCallback(rs) {
rs.headers.via.shift();
exports.send(rs);
}
exports.send = function(msg, callback) {
var ctx = contexts[makeContextId(msg)];
if(!ctx) {
sip.send.apply(sip, arguments);
return;
}
return msg.method ? forwardRequest(ctx, msg, callback || defaultCallback) : forwardResponse(ctx, msg);
};
function forwardResponse(ctx, rs, callback) {
if(+rs.status >= 200) {
delete contexts[makeContextId(rs)];
}
sip.send(rs);
}
function sendCancel(rq, via) {
sip.send({
method: 'CANCEL',
uri: rq.uri,
headers: {
via: [via],
to: rq.headers.to,
from: rq.headers.from,
'call-id': rq.headers['call-id'],
cseq: {method: 'CANCEL', seq: rq.headers.cseq.seq}
}
});
}
function forwardRequest(ctx, rq, callback) {
sip.send(rq, function(rs, remote) {
if(+rs.status < 200) {
var via = rs.headers.via[0];
ctx.cancellers[rs.headers.via[0].params.branch] = function() { sendCancel(rq, via); };
if(ctx.cancelled)
sendCancel(rq, via);
}
else {
delete ctx.cancellers[rs.headers.via[0].params.branch];
}
callback(rs, remote);
});
}
function onRequest(rq, route, remote) {
var id = makeContextId(rq);
contexts[id] = { cancellers: {} };
try {
route(sip.copyMessage(rq), remote);
} catch(e) {
delete contexts[id];
throw e;
}
};
exports.start = function(options, route) {
sip.start(options, function(rq) {
if(rq.method === 'CANCEL') {
var ctx = contexts[makeContextId(rq)];
if(ctx) {
sip.send(sip.makeResponse(rq, 200));
ctx.cancelled = true;
if(ctx.cancellers) {
Object.keys(ctx.cancellers).forEach(function(c) { ctx.cancellers[c](); });
}
}
else {
sip.send(sip.makeResponse(rq, 481));
}
}
else {
onRequest(rq, route);
}
});
};
exports.stop = sip.stop;
| lxfontes/sip.js | proxy.js | JavaScript | mit | 2,182 |
const { getMacros } = require('../../../../../test/unit/macro-helper')
const entitiesMacros = getMacros('entity')
describe('Entity macro', () => {
describe('invalid props', () => {
it('should not render if props is not given', () => {
const component = entitiesMacros.renderToDom('Entity')
expect(component).to.be.null
})
it('should not render if required props are not given', () => {
const component = entitiesMacros.renderToDom('Entity', {
id: '12345',
name: 'Horse',
})
expect(component).to.be.null
})
})
describe('valid props', () => {
it('should render entity component', () => {
const component = entitiesMacros.renderToDom('Entity', {
id: '12345',
name: 'Horse',
type: 'animal',
})
expect(component.className.trim()).to.equal('c-entity c-entity--animal')
expect(component.querySelector('.c-entity__title a')).to.have.property(
'href',
'/animals/12345'
)
})
it('should render entity component with meta items', () => {
const component = entitiesMacros.renderToDom('Entity', {
id: '12345',
name: 'Horse',
type: 'animal',
meta: [
{ label: 'Colour', value: 'brown', type: 'badge' },
{
label: 'DOB',
value: '2015-11-10',
type: 'date',
name: 'date_of_birth',
},
],
})
expect(component.querySelector('.c-entity__header .c-entity__badges')).to
.exist
expect(
component
.querySelector('.c-entity__header .c-meta-list__item')
.textContent.replace(/\s+/g, ' ')
.trim()
).to.equal('Colour brown')
expect(
component
.querySelector('.c-entity__content .c-meta-list__item')
.textContent.replace(/\s+/g, ' ')
.trim()
).to.equal('DOB 10 November 2015')
})
it('should render a title without a link if no id passed', () => {
const component = entitiesMacros.renderToDom('Entity', {
name: 'Horse',
type: 'animal',
})
expect(
component
.querySelector('.c-entity__title')
.textContent.replace(/\s+/g, ' ')
.trim()
).to.equal('Horse')
expect(component.querySelector('.c-entity__title a')).not.to.exist
})
it('should render a custom url if passed', () => {
const component = entitiesMacros.renderToDom('Entity', {
id: '12345',
name: 'Horse',
type: 'animal',
urlPrefix: 'horses/',
})
expect(component.querySelector('.c-entity__title a')).to.have.property(
'href',
'/horses/12345'
)
})
it('should use a content meta modifier if specified', () => {
const component = entitiesMacros.renderToDom('Entity', {
id: '12345',
name: 'Horse',
type: 'animal',
contentMetaModifier: 'test',
meta: [
{ label: 'Colour', value: 'brown', type: 'badge' },
{
label: 'DOB',
value: '2015-11-10',
type: 'date',
name: 'date_of_birth',
},
],
})
expect(
component.querySelector(
'.c-meta-list.c-meta-list--split.c-meta-list--inline'
)
).not.to.exist
expect(component.querySelector('.c-meta-list.c-meta-list--test')).to.exist
})
})
})
| uktrade/data-hub-fe-beta2 | src/templates/_macros/entity/__test__/entity.test.js | JavaScript | mit | 3,465 |
/*!
* Serverstats for MunkiReport
* requires nv.d3.js (https://github.com/novus/nvd3)
*/
drawServerPlots = function(hours) {
try{
if(serialNumber){}
}
catch(e){
alert('Error: munkireport.serverstats.js - No serialNumber');
return;
}
var colors = d3.scale.category20(),
keyColor = function(d, i) {return colors(d.key)},
dateformat = "L LT", // Moment.js dateformat
charts = [], // Array holding all charts
xTickCount = 4, // Amount of ticks on x axis
siFormat = d3.format('0.2s'),
byteFormat = function(d){ return siFormat(d) + 'B'},
networkFormat = function(d){ return siFormat(d) + 'B/s'};
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
// Call update on all charts when #serverstats
// becomes active so nvd3 knows about the width
// (hidden tabs have no width)
if($(e.target).attr('href') == '#serverstats')
{
charts.forEach(function(callback) {
callback();
});
}
})
$.when(
$.ajax( appUrl + '/module/machine/report/' + serialNumber ),
$.ajax( appUrl + '/module/servermetrics/get_data/' + serialNumber + '/' + hours ) )
.done(function( a1, a2 )
{
// a1 and a2 are arguments resolved for the page1 and page2 ajax requests, respectively.
// Each argument is an array with the following structure: [ data, statusText, jqXHR ]
var maxMemory = Math.min(parseInt(a1[ 0 ]['physical_memory']), 48);
var data = a2[ 0 ];
var networkTraffic = [
{
key: i18n.t('servermetrics.network.inbound_traffic'),
values:[]
},
{
key: i18n.t('servermetrics.network.outbound_traffic'),
color: "#ff7f0e",
values:[]
}
],
cpuUsage = [
{
key: i18n.t('user.user'),
values:[]
},
{
key: i18n.t('system.system'),
color: "#ff7f0e",
values:[]
}
],
memoryUsage = [
{
key: i18n.t('servermetrics.memory.usage'),
values:[]
}
],
memoryPressure = [
{
key: i18n.t('servermetrics.memory.pressure'),
values: []
}
],
cachingServer = [
{
key: i18n.t('servermetrics.caching.from_origin'),
values:[]
},
{
key: i18n.t('servermetrics.caching.from_peers'),
values:[]
},
{
key: i18n.t('servermetrics.caching.from_cache'),
values:[]
}
],
connectedUsers = [
{
key: i18n.t('servermetrics.sharing.afp_users'),
values:[]
},
{
key: i18n.t('servermetrics.sharing.smb_users'),
values:[]
}
]
var datapoints = Object.keys(data).length,
maxPoints = 500,
skip = Math.ceil(datapoints / maxPoints),
start = 0
;
for (var obj in data)
{
// Skip empty items
if(data[obj][12] == 0){
continue;
}
// Skip items (average would be better)
start++;
if( start % skip ){
continue;
}
var date = new Date (obj.replace(' ', 'T'))
cpuUsage[0].values.push({x: date, y: data[obj][5]}) // User
cpuUsage[1].values.push({x: date, y: data[obj][12]}) // System
networkTraffic[0].values.push({x: date, y: data[obj][10]}) // Inbound
networkTraffic[1].values.push({x: date, y: data[obj][13]}) // Outbound
memoryPressure[0].values.push({x: date, y: data[obj][11]})
memoryUsage[0].values.push({x: date, y: data[obj][6] + data[obj][7]}) // Wired + Active
cachingServer[0].values.push({x: date, y: data[obj][3]}) // From Origin
cachingServer[1].values.push({x: date, y: data[obj][4]}) // From Peers
cachingServer[2].values.push({x: date, y: data[obj][2]}) // From Cache
connectedUsers[0].values.push({x: date, y: data[obj][0]}) // AFP
connectedUsers[1].values.push({x: date, y: data[obj][1]}) // SMB
}
//console.log(memoryUsage[0].values.length)
// Memory Usage
nv.addGraph(function() {
chart = nv.models.lineChart()
.y(function(d) { return d.y ? d3.round(d.y / Math.pow(1024, 3), 1): null })
.yDomain([0, maxMemory])
.duration(300);
chart.xAxis
.ticks(xTickCount)
.tickFormat(function(d) { return moment(d).format(dateformat) })
.showMaxMin(false);
chart.yAxis
.ticks(6)
.tickFormat(function(d){return d + ' GB'})
.showMaxMin(false)
d3.select('#memory-usage')
.datum(memoryUsage)
.transition().duration(500)
.call(chart)
charts.push(chart.update);
nv.utils.windowResize(chart.update);
});
// CPU Usage
nv.addGraph(function() {
chart = nv.models.lineChart()
.y(function(d) { return d.y ? d.y : null })
.duration(300);
chart.xAxis
.ticks(xTickCount)
.tickFormat(function(d) { return moment(d).format(dateformat) })
.showMaxMin(false);
chart.yDomain([0,1])
.yAxis
.ticks(4)
.tickFormat(d3.format('%'));
d3.select('#cpu-usage')
.datum(cpuUsage)
.transition().duration(500)
.call(chart)
charts.push(chart.update);
nv.utils.windowResize(chart.update);
return chart;
});
// Network traffic
nv.addGraph(function() {
chart = nv.models.lineChart()
.y(function(d) { return d.y ? d.y : null })
.duration(300);
chart.xAxis
.ticks(xTickCount)
.tickFormat(function(d) { return moment(d).format(dateformat) })
.showMaxMin(false);
chart.yAxis.tickFormat(networkFormat)
.showMaxMin(false);
d3.select('#network-traffic')
.datum(networkTraffic)
.transition().duration(500)
.call(chart)
charts.push(chart.update);
nv.utils.windowResize(chart.update);
return chart;
});
// Memory Pressure
nv.addGraph(function() {
chart = nv.models.lineChart()
.y(function(d) { return d.y ? d.y : null })
.duration(300);
chart.xAxis
.ticks(xTickCount)
.tickFormat(function(d) { return moment(d).format(dateformat) })
.showMaxMin(false);
chart.yDomain([0,1])
.yAxis
.ticks(4)
.tickFormat(d3.format('%'));
d3.select('#memory-pressure')
.datum(memoryPressure)
.transition().duration(500)
.call(chart)
charts.push(chart.update);
nv.utils.windowResize(chart.update);
return chart;
});
// Caching server
nv.addGraph(function() {
chart = nv.models.lineChart()
.y(function(d) { return d.y ? d.y : null })
.duration(300);
chart.xAxis
.ticks(xTickCount)
.tickFormat(function(d) { return moment(d).format(dateformat) })
.showMaxMin(false);
chart.yAxis
.ticks(4)
.tickFormat(byteFormat)
.showMaxMin(false);
d3.select('#caching-bytes-served')
.datum(cachingServer)
.transition().duration(500)
.call(chart)
charts.push(chart.update);
nv.utils.windowResize(chart.update);
return chart;
});
// File Sharing Users
nv.addGraph(function() {
chart = nv.models.lineChart()
.y(function(d) { return d.y ? d.y : null })
.duration(300);
chart.xAxis
.ticks(xTickCount)
.tickFormat(function(d) { return moment(d).format(dateformat) })
.showMaxMin(false);
chart.yDomain([0,1])
.yAxis
.ticks(4)
.tickFormat(d3.format('.0f'));
d3.select('#sharing-connected-users')
.datum(connectedUsers)
.transition().duration(500)
.call(chart)
charts.push(chart.update);
nv.utils.windowResize(chart.update);
return chart;
});
});
};
| poundbangbash/munkireport-php | public/assets/js/munkireport.serverstats.js | JavaScript | mit | 7,200 |
const {Example} = require("../../target/generated/ts/bar/Example.js");
console.log(JSON.stringify(Example.__specialFields, null, 2));
| MasuqaT-NET/BlogExamples | Misc/java-annotation-to-js-decorator-with-jsweet/src/js/index.js | JavaScript | mit | 135 |
import {bool, stories, func, string, className} from '../duckyStories';
import CreateGoalPanel1Desktop from './index';
stories(module, CreateGoalPanel1Desktop, [
'https://github.com/DuckyTeam/ducky-web/issues/1469'
], {
className: className(),
children: string('Bygg en vane eller fullfør prestasjoner iløpet av en fastsatt periode.'),
title: string('Sett nytt personlig mål'),
onClick: func(),
inactive: bool(),
onCancel: func(),
show: bool('false'),
text: string('AVBRYT')
});
| DuckyTeam/ducky-components | src/CreateGoalPanel1Desktop/stories.js | JavaScript | mit | 501 |
const ParentRouter = require('./ParentRouter');
const urlUtils = require('../../../shared/url-utils');
const controllers = require('./controllers');
/**
* @description RSS Router, which should be used as a sub-router in other routes.
*
* "/rss" -> RSS Router
*/
class RSSRouter extends ParentRouter {
constructor() {
super('RSSRouter');
this.route = {value: '/rss/'};
this._registerRoutes();
}
/**
* @description Register all routes of this router.
* @private
*/
_registerRoutes() {
this.mountRoute(this.route.value, controllers.rss);
// REGISTER: redirect rule
this.mountRoute('/feed/', this._redirectFeedRequest.bind(this));
}
/**
* @description Simple controller function to redirect /rss to /feed
* @param {Object} req
* @param {Object}res
* @private
*/
_redirectFeedRequest(req, res) {
urlUtils
.redirect301(
res,
urlUtils.urlJoin(urlUtils.getSubdir(), req.baseUrl, this.route.value)
);
}
}
module.exports = RSSRouter;
| JohnONolan/Ghost | core/frontend/services/routing/RSSRouter.js | JavaScript | mit | 1,119 |
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
const common = require('../common');
const assert = require('assert');
const fs = require('fs');
const join = require('path').join;
const tmpdir = require('../common/tmpdir');
const currentFileData = 'ABCD';
const s = '南越国是前203年至前111年存在于岭南地区的一个国家,国都位于番禺,疆域包括今天中国的广东、' +
'广西两省区的大部份地区,福建省、湖南、贵州、云南的一小部份地区和越南的北部。' +
'南越国是秦朝灭亡后,由南海郡尉赵佗于前203年起兵兼并桂林郡和象郡后建立。' +
'前196年和前179年,南越国曾先后两次名义上臣属于西汉,成为西汉的“外臣”。前112年,' +
'南越国末代君主赵建德与西汉发生战争,被汉武帝于前111年所灭。南越国共存在93年,' +
'历经五代君主。南越国是岭南地区的第一个有记载的政权国家,采用封建制和郡县制并存的制度,' +
'它的建立保证了秦末乱世岭南地区社会秩序的稳定,有效的改善了岭南地区落后的政治、##济现状。\n';
tmpdir.refresh();
const throwNextTick = (e) => { process.nextTick(() => { throw e; }); };
// Test that empty file will be created and have content added (callback API).
{
const filename = join(tmpdir.path, 'append.txt');
fs.appendFile(filename, s, common.mustCall(function(e) {
assert.ifError(e);
fs.readFile(filename, common.mustCall(function(e, buffer) {
assert.ifError(e);
assert.strictEqual(Buffer.byteLength(s), buffer.length);
}));
}));
}
// Test that empty file will be created and have content added (promise API).
{
const filename = join(tmpdir.path, 'append-promise.txt');
fs.promises.appendFile(filename, s)
.then(common.mustCall(() => fs.promises.readFile(filename)))
.then((buffer) => {
assert.strictEqual(Buffer.byteLength(s), buffer.length);
})
.catch(throwNextTick);
}
// Test that appends data to a non-empty file (callback API).
{
const filename = join(tmpdir.path, 'append-non-empty.txt');
fs.writeFileSync(filename, currentFileData);
fs.appendFile(filename, s, common.mustCall(function(e) {
assert.ifError(e);
fs.readFile(filename, common.mustCall(function(e, buffer) {
assert.ifError(e);
assert.strictEqual(Buffer.byteLength(s) + currentFileData.length,
buffer.length);
}));
}));
}
// Test that appends data to a non-empty file (promise API).
{
const filename = join(tmpdir.path, 'append-non-empty-promise.txt');
fs.writeFileSync(filename, currentFileData);
fs.promises.appendFile(filename, s)
.then(common.mustCall(() => fs.promises.readFile(filename)))
.then((buffer) => {
assert.strictEqual(Buffer.byteLength(s) + currentFileData.length,
buffer.length);
})
.catch(throwNextTick);
}
// Test that appendFile accepts buffers (callback API).
{
const filename = join(tmpdir.path, 'append-buffer.txt');
fs.writeFileSync(filename, currentFileData);
const buf = Buffer.from(s, 'utf8');
fs.appendFile(filename, buf, common.mustCall((e) => {
assert.ifError(e);
fs.readFile(filename, common.mustCall((e, buffer) => {
assert.ifError(e);
assert.strictEqual(buf.length + currentFileData.length, buffer.length);
}));
}));
}
// Test that appendFile accepts buffers (promises API).
{
const filename = join(tmpdir.path, 'append-buffer-promises.txt');
fs.writeFileSync(filename, currentFileData);
const buf = Buffer.from(s, 'utf8');
fs.promises.appendFile(filename, buf)
.then(common.mustCall(() => fs.promises.readFile(filename)))
.then((buffer) => {
assert.strictEqual(buf.length + currentFileData.length, buffer.length);
})
.catch(throwNextTick);
}
// Test that appendFile does not accept invalid data type (callback API).
[false, 5, {}, [], null, undefined].forEach(async (data) => {
const errObj = {
code: 'ERR_INVALID_ARG_TYPE',
message: /"data"|"buffer"/
};
const filename = join(tmpdir.path, 'append-invalid-data.txt');
assert.throws(
() => fs.appendFile(filename, data, common.mustNotCall()),
errObj
);
assert.throws(
() => fs.appendFileSync(filename, data),
errObj
);
await assert.rejects(
fs.promises.appendFile(filename, data),
errObj
);
// The filename shouldn't exist if throwing error.
assert.throws(
() => fs.statSync(filename),
{
code: 'ENOENT',
message: /no such file or directory/
}
);
});
// Test that appendFile accepts file descriptors (callback API).
{
const filename = join(tmpdir.path, 'append-descriptors.txt');
fs.writeFileSync(filename, currentFileData);
fs.open(filename, 'a+', common.mustCall((e, fd) => {
assert.ifError(e);
fs.appendFile(fd, s, common.mustCall((e) => {
assert.ifError(e);
fs.close(fd, common.mustCall((e) => {
assert.ifError(e);
fs.readFile(filename, common.mustCall((e, buffer) => {
assert.ifError(e);
assert.strictEqual(Buffer.byteLength(s) + currentFileData.length,
buffer.length);
}));
}));
}));
}));
}
// Test that appendFile accepts file descriptors (promises API).
{
const filename = join(tmpdir.path, 'append-descriptors-promises.txt');
fs.writeFileSync(filename, currentFileData);
let fd;
fs.promises.open(filename, 'a+')
.then(common.mustCall((fileDescriptor) => {
fd = fileDescriptor;
return fs.promises.appendFile(fd, s);
}))
.then(common.mustCall(() => fd.close()))
.then(common.mustCall(() => fs.promises.readFile(filename)))
.then(common.mustCall((buffer) => {
assert.strictEqual(Buffer.byteLength(s) + currentFileData.length,
buffer.length);
}))
.catch(throwNextTick);
}
assert.throws(
() => fs.appendFile(join(tmpdir.path, 'append6.txt'), console.log),
{ code: 'ERR_INVALID_CALLBACK' });
| enclose-io/compiler | current/test/parallel/test-fs-append-file.js | JavaScript | mit | 7,196 |
import { hbs } from 'ember-cli-htmlbars';
import { A as emberArray } from '@ember/array';
import { run } from '@ember/runloop';
import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render } from '@ember/test-helpers';
module('Integration | Helper | {{has-next}}', function(hooks) {
setupRenderingTest(hooks);
test('it checks if an array has a next value', async function(assert) {
let array = [
{ name: 'Ross' },
{ name: 'Rachel' },
{ name: 'Joey' }
];
this.set('array', array);
this.set('value', { name: 'Rachel' });
this.set('useDeepEqual', true);
await render(hbs`{{has-next this.value this.useDeepEqual this.array}}`);
assert.dom().hasText('true', 'should render true');
});
test('It recomputes if array changes', async function(assert) {
this.set('array', emberArray([1, 2, 3]));
this.set('value', 1);
await render(hbs`{{has-next this.value this.array}}`);
assert.dom().hasText('true', 'true is shown');
run(() => this.set('array', [3, 2, 1]));
assert.dom().hasText('false', 'false is shown');
});
test('it allows null array', async function(assert) {
this.set('array', null);
await render(hbs`{{has-next 1 this.array}}`);
assert.dom().hasText('false', 'no error is thrown');
});
test('it allows undefined array', async function(assert) {
this.set('array', undefined);
await render(hbs`{{has-next 1 this.array}}`);
assert.dom().hasText('false', 'no error is thrown');
});
});
| DockYard/ember-functional-helpers | tests/integration/helpers/has-next-test.js | JavaScript | mit | 1,552 |
/**
* Created by standers on 5/14/2014.
*/
| andest01/TroutMaps | www-src/app/modules/blog/index.js | JavaScript | mit | 45 |
function isEventSupported(eventName) {
var element = document.createElement('div'), //#1
isSupported;
eventName = 'on' + eventName; //#2
isSupported = (eventName in element); //#2
if (!isSupported) { //#3
element.setAttribute(eventName, 'return;');
isSupported = typeof element[eventName] == 'function';
}
element = null; //#4
return isSupported;
}
| chroda/secretsofjavascriptninja | ninja-code/chapter-13/event-support.js | JavaScript | mit | 504 |
// ==========================================================================
// Project: SproutCore - JavaScript Application Framework
// Copyright: ©2006-2011 Apple Inc. and contributors.
// License: Licensed under MIT license (see license.js)
// ==========================================================================
var set = SC.set, get = SC.get;
module("SC.View#element");
test("returns null if the view has no element and no parent view", function() {
var view = SC.View.create() ;
equals(get(view, 'parentView'), null, 'precond - has no parentView');
equals(get(view, 'element'), null, 'has no element');
});
test("returns null if the view has no element and parent view has no element", function() {
var parent = SC.View.create({
childViews: [ SC.View.extend() ]
});
var view = parent.childViews[0];
equals(get(view, 'parentView'), parent, 'precond - has parent view');
equals(get(parent, 'element'), null, 'parentView has no element');
equals(get(view, 'element'), null, ' has no element');
});
test("returns element if you set the value", function() {
var view = SC.View.create();
equals(get(view, 'element'), null, 'precond- has no element');
var dom = document.createElement('div');
set(view, 'element', dom);
equals(get(view, 'element'), dom, 'now has set element');
});
var parent, child, parentDom, childDom ;
module("SC.View#element - autodiscovery", {
setup: function() {
parent = SC.ContainerView.create({
childViews: [ SC.View.extend({
elementId: 'child-view'
}) ]
});
child = parent.childViews[0];
// setup parent/child dom
parentDom = SC.$("<div><div id='child-view'></div></div>")[0];
// set parent element...
set(parent, 'element', parentDom);
},
teardown: function() {
parent = child = parentDom = childDom = null ;
}
});
test("discovers element if has no element but parent view does have element", function() {
equals(get(parent, 'element'), parentDom, 'precond - parent has element');
ok(parentDom.firstChild, 'precond - parentDom has first child');
equals(child.$().attr('id'), 'child-view', 'view discovered child');
});
| crofty/sensor_js_message_parsing | vendor/sproutcore-views/tests/views/view/element_test.js | JavaScript | mit | 2,176 |
module.exports = {
env: {
browser: true,
node: true
},
parser: "@typescript-eslint/parser",
parserOptions: {
project: "tsconfig.json",
sourceType: "module",
},
plugins: [
"@typescript-eslint",
"eslint-comments",
"jest",
"react",
"no-null",
"import",
"promise",
],
extends: [
"eslint:recommended",
"plugin:@typescript-eslint/recommended",
"plugin:@typescript-eslint/recommended-requiring-type-checking",
"plugin:eslint-comments/recommended",
"plugin:jest/recommended",
"plugin:promise/recommended",
"plugin:react/recommended",
"plugin:react-hooks/recommended",
"plugin:import/errors",
"plugin:import/warnings",
"plugin:import/typescript",
],
settings: {
react: {
version: "detect"
}
},
rules: {
"@typescript-eslint/await-thenable": "off",
"@typescript-eslint/ban-types": "off",
"@typescript-eslint/consistent-type-assertions": "error",
"@typescript-eslint/explicit-function-return-type": "off",
"@typescript-eslint/explicit-module-boundary-types": "off",
"@typescript-eslint/naming-convention": "off",
"@typescript-eslint/no-empty-function": "off",
"@typescript-eslint/no-explicit-any": "error",
"@typescript-eslint/no-floating-promises": "off",
"@typescript-eslint/no-inferrable-types": "error",
"@typescript-eslint/no-namespace": "off",
"@typescript-eslint/no-unsafe-assignment": "off",
"@typescript-eslint/no-unsafe-call": "off",
"@typescript-eslint/no-unsafe-member-access": "off",
"@typescript-eslint/no-unsafe-return": "off",
"@typescript-eslint/no-unused-vars": [
"error",
{
varsIgnorePattern: "^_",
argsIgnorePattern: "^_",
}
],
"@typescript-eslint/no-var-requires": "off",
"@typescript-eslint/prefer-namespace-keyword": "error",
"@typescript-eslint/prefer-regexp-exec": "off",
"@typescript-eslint/quotes": [
"error",
"double",
{
avoidEscape: true,
}
],
"@typescript-eslint/restrict-plus-operands": "off",
"@typescript-eslint/restrict-template-expressions": "off",
"@typescript-eslint/type-annotation-spacing": "error",
"@typescript-eslint/unbound-method": "off",
"array-bracket-spacing": "error",
"block-spacing": "error",
"brace-style": [
"error",
"1tbs",
{
allowSingleLine: true,
}
],
"comma-dangle": [
"error",
{
objects: "only-multiline",
arrays: "always-multiline",
functions: "always-multiline",
imports: "always-multiline",
}
],
"comma-spacing": "error",
"comma-style": "error",
"complexity": [
"error",
{
max: 14,
}
],
"computed-property-spacing": "error",
"curly": "error",
"eol-last": "error",
"eslint-comments/disable-enable-pair": "off",
"func-call-spacing": "error",
"import/no-default-export": "error",
"import/no-deprecated": "error",
"indent": [
"error",
2,
{
SwitchCase: 1,
}
],
"jest/expect-expect": "off",
"jest/no-conditional-expect": "off",
"key-spacing": "error",
"keyword-spacing": "error",
"max-len": [
"error",
{
code: 100,
}
],
"multiline-ternary": [
"error", "always-multiline"],
"no-bitwise": "error",
"no-caller": "error",
"no-case-declarations": "off",
"no-cond-assign": "error",
"no-duplicate-imports": "error",
"no-eval": "error",
"no-fallthrough": "error",
"no-multi-spaces": "error",
"no-multiple-empty-lines": "error",
"no-nested-ternary": "error",
"no-null/no-null": "error",
"no-prototype-builtins": "off",
"no-redeclare": "error",
"no-shadow": "off",
"no-trailing-spaces": "error",
"no-unneeded-ternary": "error",
"no-var": "error",
"no-whitespace-before-property": "error",
"object-curly-spacing": [
"error",
"always",
],
"prefer-const": "error",
"promise/always-return": "off",
"promise/catch-or-return": "off",
"promise/no-callback-in-promise": "off",
"promise/no-return-wrap": "off",
"react/display-name": "off",
"react/jsx-key": "off",
"react/prop-types": "off",
"semi": "error",
"space-in-parens": "error",
"space-infix-ops": "error",
"space-unary-ops": "error",
"spaced-comment": [
"error",
"always",
{
markers: ["/"],
}
],
"use-isnan": "error",
}
};
| FarmBot/farmbot-web-app | .eslintrc.js | JavaScript | mit | 5,320 |
import chai from 'chai';
import checkIfSeven from '../thirdDigit';
const assert = chai.assert;
describe('Third Digit Function', () => {
it('should exist', (done) => {
assert.isDefined(checkIfSeven);
done();
});
it('should throw error if the argument is not a number', (done) => {
assert.throw(() => {
checkIfSeven('24');
}, Error, 'Input must be a number');
done();
});
it('should return true if the third number from right to left is 7', (done) => {
assert.isTrue(checkIfSeven(1732));
assert.isTrue(checkIfSeven(9703));
assert.isTrue(checkIfSeven(9999799));
done();
});
it('should return false if the third number from right to left is 7', (done) => {
assert.isFalse(checkIfSeven(5));
assert.isFalse(checkIfSeven(877));
assert.isFalse(checkIfSeven(7778877));
done();
});
it('should work with float numbers', (done) => {
assert.isTrue(checkIfSeven(1777.321));
assert.isFalse(checkIfSeven(8827.442));
done();
});
});
| KleoPetroff/telerik-javascript-fundamentals | solutions/2-operators-and-expressions/4-third-digit/tests/thirdDigit.js | JavaScript | mit | 1,008 |
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file. JavaScript code in this file should be added after the last require_* statement.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require tether
//= require bootstrap-sprockets
//= require turbolinks
//= require_tree .
//= require_tree ./channels
//= require src/rating
$('.uploadable-image').click(function(){
$('#user_avatar').click();
});
$(document).on('turbolinks:load', function() {
setTimeout( function() {
$('.alert').alert('close');
}, 5000);
});
| DisruptiveAngels/draft | app/assets/javascripts/application.js | JavaScript | mit | 1,042 |
import CreateCamera from 'perspective-camera'
import CreateMat3 from 'gl-mat3/create'
import CreateMat4 from 'gl-mat4/create'
import UseControls from '../use-controls'
import Update from './update'
import UpdateNormal from './update-normal'
import UpdateModelView from './update-model-view'
function PerspectiveCamera (camera) {
camera.flags = {
autoUpdate: true,
autoUpdateViewport: true,
autoUpdateControls: true
}
camera.modelView = CreateMat4()
camera.normal = CreateMat3()
camera.updateMatrices = camera.update
camera.updateModelView = UpdateModelView.bind(null, camera)
camera.updateNormal = UpdateNormal.bind(null, camera)
camera.update = Update.bind(null, camera)
camera.use = UseControls.bind(null, camera)
return camera
}
export default function perspective (properties) {
return PerspectiveCamera(CreateCamera(properties))
}
| glamjs/glam | lib/camera/perspective/index.js | JavaScript | mit | 875 |
import {D3TextList} from './lib/D3TextList';
let item_array = [
{"label": "d3 es6 is good.", "item_class": "good-value"},
{"label": "d3 es6 is ok.", "item_class": "ok-value"},
{"label": "d3 es6 is not so good.", "item_class": "w3-red"}
];
let param_obj = {};
param_obj.el_container_id = 'el_message_list';
param_obj.item_array = item_array;
let text_list_obj = new D3TextList();
text_list_obj.show_list(param_obj);
| saun4app/hello-d3-es6-gulp-jspm | src/js/main.js | JavaScript | mit | 430 |
{
"frames": {
"dirt" : {
"frame" : {"x" : 0,"y" : 0,"w" : 32,"h" : 32},
"rotated" : false,
"trimmed" : false,
"spriteSourceSize" : {"x" : 0,"y" : 0,"w" : 320,"h" : 320},
"sourceSize" : {"w" : 32,"h" : 32}
},
"grass" : {
"frame" : {"x" : 33,"y" : 33,"w" : 32,"h" : 32},
"rotated" : false,
"trimmed" : false,
"spriteSourceSize" : {"x" : 0,"y" : 0,"w" : 320,"h" : 320},
"sourceSize" : {"w" : 32,"h" : 32}
}
},
"meta": {
"app": "http://www.texturepacker.com",
"version": "1.0",
"image": "SpriteSheet.png",
"format": "RGBA8888",
"size": {"w":320,"h":320},
"scale": "1",
"smartupdate": "$TexturePacker:SmartUpdate:9e3e5afd01ea8e418afabfbdcd724485$"
}
}
| rogueSnake/musicMonstersOnline | client/images/spriteSheet.js | JavaScript | mit | 874 |
/**
* @class tiv.controller.Main
* @extends Ext.app.Controller
*
* Controller for application.
*/
Ext.define('tiv.controller.Main', {
extend: 'Ext.app.Controller',
config: {
refs: {
viewer: 'viewer'
},
control: {
'viewer list': {
itemtap: 'showPicture'
}
}
},
/**
* Handling viewer's list item tap event.
* Add photo view to navigation view.
*
* @param {Ext.dataview.DataView} list
* @param {Number} index The index of the item tapped
* @param {Ext.Element/Ext.dataview.component.DataItem} item The element or DataItem tapped
* @param {Ext.data.Model} record The record assosciated to the item
*/
showPicture: function (list, index, item, record) {
var caption = record.get('caption')
, images = record.get('images')
, user = record.get('user');
this.getViewer().push({
xtype: 'photo',
data: {
caption: caption,
images: images,
user: user
}
});
}
});
| shinobukawano/tiny-instagram-viewer | app/controller/Main.js | JavaScript | mit | 1,007 |
'use strict';
var convert = require('./convert'),
func = convert('cloneDeep', require('../cloneDeep'), require('./_falseOptions'));
func.placeholder = require('./placeholder');
module.exports = func;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL2NsaWVudC9saWIvbG9kYXNoL2ZwL2Nsb25lRGVlcC5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLElBQUksVUFBVSxRQUFRLFdBQVIsQ0FBZDtJQUNJLE9BQU8sUUFBUSxXQUFSLEVBQXFCLFFBQVEsY0FBUixDQUFyQixFQUE4QyxRQUFRLGlCQUFSLENBQTlDLENBRFg7O0FBR0EsS0FBSyxXQUFMLEdBQW1CLFFBQVEsZUFBUixDQUFuQjtBQUNBLE9BQU8sT0FBUCxHQUFpQixJQUFqQiIsImZpbGUiOiJjbG9uZURlZXAuanMiLCJzb3VyY2VzQ29udGVudCI6WyJ2YXIgY29udmVydCA9IHJlcXVpcmUoJy4vY29udmVydCcpLFxuICAgIGZ1bmMgPSBjb252ZXJ0KCdjbG9uZURlZXAnLCByZXF1aXJlKCcuLi9jbG9uZURlZXAnKSwgcmVxdWlyZSgnLi9fZmFsc2VPcHRpb25zJykpO1xuXG5mdW5jLnBsYWNlaG9sZGVyID0gcmVxdWlyZSgnLi9wbGFjZWhvbGRlcicpO1xubW9kdWxlLmV4cG9ydHMgPSBmdW5jO1xuIl19 | vickeetran/hackd.in | compiled/client/lib/lodash/fp/cloneDeep.js | JavaScript | mit | 932 |
setTimeout(function(){
var network_state = navigator.connection.type;
console.log('Connection Type');
var states = {};
states[Connection.UNKNOWN] = 'Unknow';
states[Connection.ETHERNET] = 'ETHERNET';
states[Connection.WIFI] = 'WI-FI';
states[Connection.CELL_2G] = 'CELL 2G';
states[Connection.CELL_3G] = 'CELL 3G';
states[Connection.CELL_4G] = 'CELL 4G';
states[Connection.NONE] = 'NONE';
document.getElementById('network-information').innerHTML = '<h2> Se conecta con: ' + states[network_state] + '</h2>';
}, 500);
| alejo8591/unipiloto-am-2 | labs/lab38/platforms/firefoxos/www/js/lab38.js | JavaScript | mit | 567 |
EstablishmentShowCommentFormView = Backbone.View.extend({
events:{
'submit': 'handleSubmit'
},
initialize: function () {
this.render();
},
render: function () {
this.$el.html('');
this.$el.html(render('establishments/show_comment_form', this.model));
},
handleSubmit: function (e) {
e.preventDefault();
var body = $.trim(e.target[0].value);
var comment_data = {
body: body,
establishment_id: this.model.get('id')
};
if (CurrentUser.logged_in()) {
if (body) {
this.new_comment = new Comment( comment_data );
this.new_comment.save({}, {success: updateCollection});
} else {
alert('Comments cannot be blank.');
}
} else {
CurrentUser.authenticate();
}
var that = this;
function updateCollection (model, response, options) {
$('#comment_input').val('');
model.set('updated_at', moment().utc().format());
model.format_time();
that.collection.add(model);
}
}
});
| sealocal/yumhacker | app/assets/javascripts/views/establishments/show_comment_form_view.js | JavaScript | mit | 1,204 |
'use strict';
const childProcess = require('child_process');
const path = require('path');
const fs = require('fs');
const arrify = require('arrify');
const makeDir = require('make-dir');
const branch = require('git-branch').sync(path.join(__dirname, '..'));
const cliPath = require.resolve('../cli');
function runTests(_args) {
return new Promise(resolve => {
const args = [cliPath].concat(arrify(_args));
const start = Date.now();
childProcess.execFile(process.execPath, args, {
cwd: __dirname,
maxBuffer: 100000 * 200
}, (err, stdout, stderr) => {
const end = Date.now();
resolve({
args: arrify(_args),
time: end - start,
err,
stdout,
stderr
});
});
});
}
let list;
if (process.argv.length === 2) {
list = [
{
args: 'other/failures.js',
shouldFail: true
},
'serial/alternating-sync-async.js',
'serial/async-immediate.js',
'serial/async-timeout.js',
'serial/sync.js',
'concurrent/alternating-sync-async.js',
'concurrent/async-immediate.js',
'concurrent/async-timeout.js',
'concurrent/sync.js',
['concurrent/*.js', 'serial/*.js']
].map(definition => {
if (Array.isArray(definition) || typeof definition === 'string') {
definition = {
shouldFail: false,
args: definition
};
}
return definition;
});
} else {
list = [];
let currentArgs = [];
let shouldFail = false;
for (const arg of process.argv.slice(2)) {
if (arg === '--') {
list.push({
args: currentArgs,
shouldFail
});
currentArgs = [];
shouldFail = false;
continue;
}
if (arg === '--should-fail') {
shouldFail = true;
continue;
}
currentArgs.push(arg);
}
if (currentArgs.length > 0) {
list.push({
args: currentArgs,
shouldFail
});
}
}
for (const definition of list) {
definition.args = ['--verbose'].concat(definition.args);
}
let combined = [];
for (let i = 0; i < 11; i++) {
combined = combined.concat(list);
}
const results = {};
Promise.each(combined, definition => {
const args = definition.args;
return runTests(args).then(result => {
const key = result.args.join(' ');
const passedOrFaild = result.err ? 'failed' : 'passed';
const seconds = result.time / 1000;
console.log('%s %s in %d seconds', key, passedOrFaild, seconds);
if (result.err && !definition.shouldFail) {
console.log(result.stdout);
console.log(result.stderr);
throw result.err;
}
results[key] = results[key] || [];
results[key].push({
passed: !results.err,
shouldFail: definition.shouldFail,
time: seconds
});
});
}).then(() => {
makeDir.sync(path.join(__dirname, '.results'));
results['.time'] = Date.now();
fs.writeFileSync(
path.join(__dirname, '.results', `${branch}.json`),
JSON.stringify(results, null, 4)
);
});
| Collinslenjo/ava | bench/run.js | JavaScript | mit | 2,771 |
/**
* Ejemplo básico
* Demostración sencilla de los modos de funcionamiento de un widget AppliCast(tm)
* y de los manejadores de eventos.
*
* (c) 2009 ILERRED, S.L.
*/
//= require <prototype>
//= require <applicast/applicast>
//= require "basic"
//////////////////////////////////////////////////////
// Core Events
//////////////////////////////////////////////////////
var App = null;
/**
* onLoad
* Iniciamos nuestro objeto widget
*/
function onLoad() {
App = new Widget();
}
/**
* onFocus
*/
function onFocus() {
Event.fire('modechange', {mode: WidgetMode.NORMALFOCUS, focus: true});
}
/**
* onUnfocus
*/
function onUnfocus() {
Event.fire('modechange', {mode: WidgetMode.NORMALFOCUS, focus: false});
}
/**
* onActivate
*/
function onActivate() {
Event.fire('modechange', {mode: WidgetMode.ACTIVE});
}
/**
* onUpKey
*/
function onUpKey() {
Event.fire('keypress', {keyCode: Event.KEY_UP});
}
/**
* onDownKey
*/
function onDownKey() {
Event.fire('keypress', {keyCode: Event.KEY_DOWN});
}
/**
* onRightKey
*/
function onRightKey() {
Event.fire('keypress', {keyCode: Event.KEY_RIGHT});
}
/**
* onLeftKey
*/
function onLeftKey() {
Event.fire('keypress', {keyCode: Event.KEY_LEFT});
}
/**
* onConfirmKey
*/
function onConfirmKey(type) {
if ( type && type == 1 )
Event.fire('keypress', {keyCode: Event.KEY_CONFIRM});
}
/**
* onBlueKey
*/
function onBlueKey() {
Event.fire('keypress', {keyCode: Event.KEY_BLUE});
}
/**
* onRedKey
*/
function onRedKey() {
Event.fire('keypress', {keyCode: Event.KEY_RED});
}
/**
* onGreenKey
*/
function onGreenKey() {
Event.fire('keypress', {keyCode: Event.KEY_GREEN});
}
/**
* onYellowKey
*/
function onYellowKey() {
Event.fire('keypress', {keyCode: Event.KEY_YELLOW});
} | google-code/applicast-toolkit | src/basic-example/core.js | JavaScript | mit | 1,751 |
import m from 'mithril';
import prop from 'mithril/stream';
import _ from 'underscore';
import { catarse } from '../api';
import h from '../h';
import models from '../models';
const I18nScope = _.partial(h.i18nScope, 'pages.press');
const press = {
oninit: function(vnode) {
const stats = prop([]);
const loader = catarse.loader;
const statsLoader = loader(models.statistic.getRowOptions());
statsLoader.load().then(stats);
vnode.state = {
stats
};
},
view: function({state}) {
const stats = _.first(state.stats());
return m('#press', [
m('.hero-jobs.hero-medium',
m('.w-container.u-text-center', [
m('img.icon-hero[alt=\'Icon assets\'][src=\'/assets/icon-assets-98f4556940e31b239cdd5fbdd993b5d5ed3bf67dcc3164b805e224d22e1340b7.png\']'),
m('.u-text-center.u-marginbottom-20.fontsize-largest',
window.I18n.t('page-title', I18nScope())
)
])
),
m('.section-large.bg-gray',
m('.w-container',
m('.w-row',
m('.w-col.w-col-8.w-col-push-2',
m('.u-marginbottom-20.fontsize-large',
window.I18n.t('abstract.title', I18nScope())
)
)
)
)
),
m('.section-large',
m('.w-container',
m('.w-row',
m('.w-col.w-col-8.w-col-push-2', [
m('.fontsize-large.fontweight-semibold.u-marginbottom-10',
window.I18n.t('history.title', I18nScope())
),
m('.fontsize-large.u-marginbottom-20',
window.I18n.t('history.subtitle', I18nScope())
),
m.trust(window.I18n.t('history.cta_html', I18nScope()))
])
)
)
),
m('.section-large.bg-gray',
m('.w-container',
m('.w-row',
m('.w-col.w-col-8.w-col-push-2', [
m('.fontsize-large.fontweight-semibold.u-marginbottom-10',
window.I18n.t('stats.title', I18nScope())
),
m('.fontsize-large.u-marginbottom-40',
window.I18n.t('stats.subtitle', I18nScope())
),
m('.w-row.w.hidden-small.u-text-center.u-marginbottom-40', [
m('.w-col.w-col-4.u-marginbottom-20', [
m('.text-success.lineheight-loose.fontsize-larger',
h.formatNumber(stats.total_contributors, 0, 3)
),
m('.fontsize-smaller', m.trust(window.I18n.t('stats.people_html', I18nScope())))
]),
m('.w-col.w-col-4.u-marginbottom-20', [
m('.text-success.lineheight-loose.fontsize-larger',
h.formatNumber(stats.total_projects_success, 0, 3)
),
m('.fontsize-smaller', m.trust(window.I18n.t('stats.projects_html', I18nScope())))
]),
m('.w-col.w-col-4.u-marginbottom-20', [
m('.text-success.lineheight-loose.fontsize-larger',
`${stats.total_contributed.toString().slice(0, 2)} milhões`
),
m('.fontsize-smaller', m.trust(window.I18n.t('stats.money_html', I18nScope())))
])
]),
m('a.alt-link.fontsize-large[href=\'https://www.catarse.me/dbhero/dataclips/fa0d3570-9fa7-4af3-b070-2b2e386ef060\'][target=\'_blank\']', [
m.trust(window.I18n.t('stats.cta_html', I18nScope()))
])
])
)
)
),
m('.section-large',
m('.w-container', [
m('.w-row.u-marginbottom-30.u-text-center',
m('.w-col.w-col-8.w-col-push-2', [
m('div',
m('img[alt=\'Logo catarse press\'][src=\'/assets/logo-catarse-press-2f2dad49d3e5b256c29e136673b4c4f543c03e0d5548d351ae5a8d1e6e3d2645.png\']')
),
m('.fontsize-base',
window.I18n.t('assets.title', I18nScope())
)
])
),
m('.w-row',
m('.w-col.w-col-4.w-col-push-4.u-text-center',
m('a.alt-link.fontsize-large[href=\'https://www.catarse.me/assets\'][target=\'_blank\']', [
m.trust(window.I18n.t('assets.cta_html', I18nScope()))
])
)
)
])
),
m('.section-large.bg-projectgrid',
m('.w-container', [
m('.fontsize-large.u-text-center.fontweight-semibold.u-marginbottom-30',
window.I18n.t('social.title', I18nScope())
),
m('.w-row', [
m('.w-col.w-col-3',
m('a.btn.btn-dark.btn-large.u-marginbottom-10[href=\'https://www.facebook.com/Catarse.me\'][target=\'_blank\']', [
m('span.fa.fa-facebook'),
' Facebook'
])
),
m('.w-col.w-col-3',
m('a.btn.btn-dark.btn-large.u-marginbottom-10[href=\'https://twitter.com/catarse\'][target=\'_blank\']', [
m('span.fa.fa-twitter'),
' Twitter'
])
),
m('.w-col.w-col-3',
m('a.btn.btn-dark.btn-large.u-marginbottom-10[href=\'https://instagram.com/catarse/\'][target=\'_blank\']', [
m('span.fa.fa-instagram'),
' Instagram'
])
),
m('.w-col.w-col-3',
m('a.btn.btn-dark.btn-large.u-marginbottom-10[href=\'http://blog.catarse.me/\'][target=\'_blank\']', [
m('span.fa.fa-rss'),
' Blog do Catarse'
])
)
])
])
),
m('.section-large.bg-blue-one.fontcolor-negative',
m('.w-container',
m('.w-row',
m('.w-col.w-col-6.w-col-push-3', [
m('.fontsize-large.fontweight-semibold.u-text-center.u-marginbottom-30',
window.I18n.t('social.news', I18nScope())
),
m('.w-form',
m(`form[accept-charset='UTF-8'][action='${h.getNewsletterUrl()}'][id='mailee-form'][method='post']`, [
m('.w-form.footer-newsletter',
m('input.w-input.text-field.prefix[id=\'EMAIL\'][label=\'email\'][name=\'EMAIL\'][placeholder=\'Digite seu email\'][type=\'email\']')
),
m('button.w-inline-block.btn.btn-edit.postfix.btn-attached[type=\'submit\']',
m('img.footer-news-icon[alt=\'Icon newsletter\'][src=\'/assets/catarse_bootstrap/icon-newsletter-9c3ff92b6137fbdb9d928ecdb34c88948277a32cdde3e5b525e97d57735210f5.png\']')
)
])
)
])
)
)
),
m('.section-large.bg-gray.before-footer',
m('.w-container',
m('.w-row.u-text-center',
m('.w-col.w-col-8.w-col-push-2', [
m('.fontsize-larger.fontweight-semibold.u-marginbottom-10',
window.I18n.t('email.title', I18nScope())
),
m('div',
m(`a.alt-link.fontsize-large[href='mailto:${window.I18n.t('email.cta', I18nScope())}']`,
window.I18n.t('email.cta', I18nScope())
)
)
])
)
)
)
]);
}
};
export default press;
| catarse/catarse_admin | legacy/src/root/press.js | JavaScript | mit | 9,489 |
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011 Zynga Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
/**
* <p>
* The current version of Cocos2d-html5 being used.<br/>
* Please DO NOT remove this String, it is an important flag for bug tracking.<br/>
* If you post a bug to forum, please attach this flag.
* </p>
* @constant
* @type String
*/
cc.ENGINE_VERSION = "Cocos2d-html5-v2.2.1";
/**
* <p>
* If enabled, the texture coordinates will be calculated by using this formula: <br/>
* - texCoord.left = (rect.origin.x*2+1) / (texture.wide*2); <br/>
* - texCoord.right = texCoord.left + (rect.size.width*2-2)/(texture.wide*2); <br/>
* <br/>
* The same for bottom and top. <br/>
* <br/>
* This formula prevents artifacts by using 99% of the texture. <br/>
* The "correct" way to prevent artifacts is by using the spritesheet-artifact-fixer.py or a similar tool.<br/>
* <br/>
* Affected nodes: <br/>
* - cc.Sprite / cc.SpriteBatchNode and subclasses: cc.LabelBMFont, cc.TMXTiledMap <br/>
* - cc.LabelAtlas <br/>
* - cc.QuadParticleSystem <br/>
* - cc.TileMap <br/>
* <br/>
* To enabled set it to 1. Disabled by default.
* </p>
* @constant
* @type Number
*/
cc.FIX_ARTIFACTS_BY_STRECHING_TEXEL = 0;
/**
* Position of the FPS (Default: 0,0 (bottom-left corner))
* @constant
* @type cc.Point
*/
cc.DIRECTOR_STATS_POSITION = cc.p(0, 0);
/**
* <p>
* Senconds between FPS updates.<br/>
* 0.5 seconds, means that the FPS number will be updated every 0.5 seconds.<br/>
* Having a bigger number means a more reliable FPS<br/>
* <br/>
* Default value: 0.1f<br/>
* </p>
* @constant
* @type Number
*/
cc.DIRECTOR_FPS_INTERVAL = 0.5;
/**
* <p>
* If enabled, the cc.Node objects (cc.Sprite, cc.Label,etc) will be able to render in subpixels.<br/>
* If disabled, integer pixels will be used.<br/>
* <br/>
* To enable set it to 1. Enabled by default.
* </p>
* @constant
* @type Number
*/
cc.COCOSNODE_RENDER_SUBPIXEL = 1;
/**
* <p>
* If enabled, the cc.Sprite objects rendered with cc.SpriteBatchNode will be able to render in subpixels.<br/>
* If disabled, integer pixels will be used.<br/>
* <br/>
* To enable set it to 1. Enabled by default.
* </p>
* @constant
* @type Number
*/
cc.SPRITEBATCHNODE_RENDER_SUBPIXEL = 1;
/**
* <p>
* If most of your imamges have pre-multiplied alpha, set it to 1 (if you are going to use .PNG/.JPG file images).<br/>
* Only set to 0 if ALL your images by-pass Apple UIImage loading system (eg: if you use libpng or PVR images)<br/>
* <br/>
* To enable set it to a value different than 0. Enabled by default.
* </p>
* @constant
* @type Number
*/
cc.OPTIMIZE_BLEND_FUNC_FOR_PREMULTIPLIED_ALPHA = 0;
/**
* <p>
* Use GL_TRIANGLE_STRIP instead of GL_TRIANGLES when rendering the texture atlas.<br/>
* It seems it is the recommend way, but it is much slower, so, enable it at your own risk<br/>
* <br/>
* To enable set it to a value different than 0. Disabled by default.
* </p>
* @constant
* @type Number
*/
cc.TEXTURE_ATLAS_USE_TRIANGLE_STRIP = 0;
/**
* <p>
* By default, cc.TextureAtlas (used by many cocos2d classes) will use VAO (Vertex Array Objects).<br/>
* Apple recommends its usage but they might consume a lot of memory, specially if you use many of them.<br/>
* So for certain cases, where you might need hundreds of VAO objects, it might be a good idea to disable it.<br/>
* <br/>
* To disable it set it to 0. disable by default.(Not Supported on WebGL)<br/>
* </p>
* @constant
* @type Number
*/
cc.TEXTURE_ATLAS_USE_VAO = 0;
/**
* <p>
* If enabled, NPOT textures will be used where available. Only 3rd gen (and newer) devices support NPOT textures.<br/>
* NPOT textures have the following limitations:<br/>
* - They can't have mipmaps<br/>
* - They only accept GL_CLAMP_TO_EDGE in GL_TEXTURE_WRAP_{S,T}<br/>
* <br/>
* To enable set it to a value different than 0. Disabled by default. <br/>
* <br/>
* This value governs only the PNG, GIF, BMP, images.<br/>
* This value DOES NOT govern the PVR (PVR.GZ, PVR.CCZ) files. If NPOT PVR is loaded, then it will create an NPOT texture ignoring this value.
* </p>
* @constant
* @type Number
* @deprecated This value will be removed in 1.1 and NPOT textures will be loaded by default if the device supports it.
*/
cc.TEXTURE_NPOT_SUPPORT = 0;
/**
* <p>
* If enabled, cocos2d supports retina display.<br/>
* For performance reasons, it's recommended disable it in games without retina display support, like iPad only games.<br/>
* <br/>
* To enable set it to 1. Use 0 to disable it. Enabled by default.<br/>
* <br/>
* This value governs only the PNG, GIF, BMP, images.<br/>
* This value DOES NOT govern the PVR (PVR.GZ, PVR.CCZ) files. If NPOT PVR is loaded, then it will create an NPOT texture ignoring this value.
* </p>
* @constant
* @type Number
* @deprecated This value will be removed in 1.1 and NPOT textures will be loaded by default if the device supports it.
*/
cc.RETINA_DISPLAY_SUPPORT = 1;
/**
* <p>
* It's the suffix that will be appended to the files in order to load "retina display" images.<br/>
* <br/>
* On an iPhone4 with Retina Display support enabled, the file @"sprite-hd.png" will be loaded instead of @"sprite.png".<br/>
* If the file doesn't exist it will use the non-retina display image.<br/>
* <br/>
* Platforms: Only used on Retina Display devices like iPhone 4.
* </p>
* @constant
* @type String
*/
cc.RETINA_DISPLAY_FILENAME_SUFFIX = "-hd";
/**
* <p>
* If enabled, it will use LA88 (Luminance Alpha 16-bit textures) for CCLabelTTF objects. <br/>
* If it is disabled, it will use A8 (Alpha 8-bit textures). <br/>
* LA88 textures are 6% faster than A8 textures, but they will consume 2x memory. <br/>
* <br/>
* This feature is enabled by default.
* </p>
* @constant
* @type Number
*/
cc.USE_LA88_LABELS = 1;
/**
* <p>
* If enabled, all subclasses of cc.Sprite will draw a bounding box<br/>
* Useful for debugging purposes only. It is recommened to leave it disabled.<br/>
* <br/>
* To enable set it to a value different than 0. Disabled by default:<br/>
* 0 -- disabled<br/>
* 1 -- draw bounding box<br/>
* 2 -- draw texture box
* </p>
* @constant
* @type Number
*/
cc.SPRITE_DEBUG_DRAW = 0;
/**
* <p>
* If enabled, all subclasses of cc.Sprite that are rendered using an cc.SpriteBatchNode draw a bounding box.<br/>
* Useful for debugging purposes only. It is recommened to leave it disabled.<br/>
* <br/>
* To enable set it to a value different than 0. Disabled by default.
* </p>
* @constant
* @type Number
*/
cc.SPRITEBATCHNODE_DEBUG_DRAW = 0;
/**
* <p>
* If enabled, all subclasses of cc.LabelBMFont will draw a bounding box <br/>
* Useful for debugging purposes only. It is recommened to leave it disabled.<br/>
* <br/>
* To enable set it to a value different than 0. Disabled by default.<br/>
* </p>
* @constant
* @type Number
*/
cc.LABELBMFONT_DEBUG_DRAW = 0;
/**
* <p>
* If enabled, all subclasses of cc.LabeltAtlas will draw a bounding box<br/>
* Useful for debugging purposes only. It is recommened to leave it disabled.<br/>
* <br/>
* To enable set it to a value different than 0. Disabled by default.
* </p>
* @constant
* @type Number
*/
cc.LABELATLAS_DEBUG_DRAW = 0;
/**
* whether or not support retina display
* @constant
* @type Number
*/
cc.IS_RETINA_DISPLAY_SUPPORTED = 1;
/**
* default engine
* @constant
* @type String
*/
cc.DEFAULT_ENGINE = cc.ENGINE_VERSION + "-canvas";
/**
* Runtime information
* @deprecated Use "sys" instead.
*/
cc.config = {
'platform' : sys.platform
};
/**
* dump config info, but only in debug mode
*/
cc.dumpConfig = function() {
for(var i in sys )
cc.log( i + " = " + sys[i] );
};
/**
* <p>
* If enabled, actions that alter the position property (eg: CCMoveBy, CCJumpBy, CCBezierBy, etc..) will be stacked. <br/>
* If you run 2 or more 'position' actions at the same time on a node, then end position will be the sum of all the positions. <br/>
* If disabled, only the last run action will take effect.
* </p>
* @constant
* @type {number}
*/
cc.ENABLE_STACKABLE_ACTIONS = 1;
/**
* <p>
* If enabled, cocos2d will maintain an OpenGL state cache internally to avoid unnecessary switches. <br/>
* In order to use them, you have to use the following functions, insead of the the GL ones: <br/>
* - ccGLUseProgram() instead of glUseProgram() <br/>
* - ccGLDeleteProgram() instead of glDeleteProgram() <br/>
* - ccGLBlendFunc() instead of glBlendFunc() <br/>
* <br/>
* If this functionality is disabled, then ccGLUseProgram(), ccGLDeleteProgram(), ccGLBlendFunc() will call the GL ones, without using the cache. <br/>
* It is recommened to enable whenever possible to improve speed. <br/>
* If you are migrating your code from GL ES 1.1, then keep it disabled. Once all your code works as expected, turn it on.
* </p>
* @constant
* @type Number
*/
cc.ENABLE_GL_STATE_CACHE = 1; | ssebastianj/Viradium | src/viradium/libs/cocos2d/platform/CCConfig.js | JavaScript | mit | 11,847 |
module.exports = {
amd: {
src: ['tmp/oasis.amd.js'],
dest: 'dist/oasis.amd.js'
},
test: {
expand: true,
cwd: 'test',
src: [
'**/*',
'!*.js'
],
dest: 'tmp/public/'
},
testVendor: {
expand: true,
cwd: 'bower_components',
src: [
'qunit/qunit/*',
'jquery/jquery.js'
],
flatten: true,
dest: 'tmp/public/vendor/'
},
testOasis: {
expand: true,
cwd: 'dist',
src: ['oasis.js'],
dest: 'tmp/public/'
}
};
| tildeio/oasis.js | configurations/copy.js | JavaScript | mit | 505 |
/**
* Class for secure random number generation.
*
* @example
* random.addEntropy(anything) to add some randomness.
* random.random(max) or random.choice(array) to get some.
*/
export function Random() {
let buffer = '';
let local_storage =
typeof window.localStorage != 'undefined' ? localStorage : {};
function seedOracle(buffer) {
return Crypto.SHA256(buffer + 'seed').toString();
}
function outputOracle(buffer) {
return Crypto.SHA256(buffer + 'output').toString();
}
/**
* Core random generation function.
*
* Returns a cryptographically secure pseudo-random 256-bit hexadecimal
* string. Though, usually just
* '1ec1c26b50d5d3c58d9583181af8076655fe00756bf7285940ba3670f99fcba0'.
*/
function getRandomBuffer() {
const output = outputOracle(buffer);
buffer = seedOracle(buffer);
updateLocalStorage();
return output;
}
function random_2(bits) {
const output = getRandomBuffer();
if (output.length * 4 < bits) {
throw new Error('not enough bits in buffer');
}
const hex = output.slice(0, Math.ceil(bits / 4));
return parseInt(hex, 16);
}
function updateLocalStorage() {
local_storage.random_seed = outputOracle(buffer);
// You must rehash the buffer after (or before) outputting the hash.
// Otherwise you may get the same result again and again.
buffer = seedOracle(buffer);
}
/**
* `random` returns n such that `0 <= n < max`
* `max` must be greater than 0.
*/
this.random = function (max) {
if (max < 1) {
throw new Error('`random()` expects a max greater than 0.');
} else if (max == 1) {
return 0;
}
const bits = Math.ceil(Math.log(max) / Math.log(2));
let n;
do {
n = random_2(bits);
} while (n >= max);
return n;
};
/**
* Returns a random element from an array.
*/
this.choice = function (arr) {
if (arr.length == 0) {
return;
}
const i = this.random(arr.length);
return arr[i];
};
/**
* Add some entropy to the internal buffer.
*/
this.addEntropy = function (entropy) {
buffer = seedOracle(buffer + entropy);
};
if (localStorage.random_seed) {
buffer = seedOracle(localStorage.random_seed + new Date().valueOf());
}
}
| kalpetros/hawkpass | src/random.js | JavaScript | mit | 2,289 |
/*global describe, xdescribe, it, beforeEach, expect, xit, jasmine, Binding */
describe("Axis", function () {
"use strict";
var Point = require('../../src/math/point.js'),
Displacement = require('../../src/math/displacement.js'),
RGBColor = require('../../src/math/rgb_color.js'),
Graph = require('../../src/core/graph.js'),
Insets = require('../../src/math/insets.js'),
Legend = require('../../src/core/legend.js'),
Axis = require('../../src/core/axis.js'),
AxisTitle = require('../../src/core/axis_title.js'),
Labeler = require('../../src/core/labeler.js'),
Grid = require('../../src/core/grid.js'),
Pan = require('../../src/core/pan.js'),
Zoom = require('../../src/core/zoom.js'),
DataValue = require('../../src/core/data_value.js'),
DataMeasure = require('../../src/core/data_measure.js'),
NumberValue = require('../../src/core/number_value.js'),
Text = require('../../src/core/text.js'),
a;
beforeEach(function () {
a = new Axis(Axis.HORIZONTAL);
});
it("should be able to create an Axis", function () {
expect(a instanceof Axis).toBe(true);
});
describe("id attribute", function () {
it("should be able to set/get the id attribute", function () {
a.id("the-id");
expect(a.id()).toBe("the-id");
});
it("should throw an error if the parameter is not a string", function () {
expect(function () {
a.id(5);
}).toThrow(new Error("5 should be a string"));
});
});
describe("type attribute", function () {
it("should be able to set/get the type attribute", function () {
a.type("number");
expect(a.type()).toBe("number");
a.type("datetime");
expect(a.type()).toBe("datetime");
});
it("should throw an error if the parameter is not 'number' or 'datetime'", function () {
expect(function () {
a.type(5);
}).toThrow(); // too hard to check for specific message here
expect(function () {
a.type("numbers");
}).toThrow(); // too hard to check for specific message here
});
});
describe("length attribute", function () {
it("should be able to set/get the length attribute", function () {
a.length(Displacement.parse(".5+2"));
expect(a.length().a()).toEqual(0.5);
expect(a.length().b()).toEqual(2);
a.length(Displacement.parse(".7"));
expect(a.length().a()).toEqual(0.7);
expect(a.length().b()).toEqual(0);
});
});
describe("position attribute", function () {
it("should be able to set/get the position attribute", function () {
a.position(new Point(1,1));
expect(a.position().x()).toEqual(1);
expect(a.position().y()).toEqual(1);
});
it("should throw an error if the parameter is not a point", function () {
expect(function () {
a.position(true);
}).toThrow(new Error("validator failed with parameter true"));
});
});
describe("pregap attribute", function () {
it("should be able to set/get the pregap attribute", function () {
a.pregap(2);
expect(a.pregap()).toBe(2);
});
});
describe("postgap attribute", function () {
it("should be able to set/get the postgap attribute", function () {
a.postgap(7);
expect(a.postgap()).toBe(7);
});
});
describe("anchor attribute", function () {
it("should be able to set/get the anchor attribute", function () {
a.anchor(-0.8);
expect(a.anchor()).toEqual(-0.8);
});
it("should throw an error if the parameter is not a number", function () {
expect(function () {
a.anchor("foo");
}).toThrow(new Error("foo should be a number"));
});
});
describe("base attribute", function () {
it("should be able to set/get the base attribute", function () {
a.base(new Point(-1,0));
expect(a.base().x()).toEqual(-1);
expect(a.base().y()).toEqual(0);
});
it("should throw an error if the parameter is not a string", function () {
expect(function () {
a.base(true);
}).toThrow(new Error("validator failed with parameter true"));
});
});
describe("min attribute", function () {
it("should be able to set/get the min attribute", function () {
a.min("17");
expect(a.min()).toBe("17");
});
it("should throw an error if the parameter is not a string", function () {
expect(function () {
a.min(true);
}).toThrow(new Error("true should be a string"));
});
});
describe("minoffset attribute", function () {
it("should be able to set/get the minoffset attribute", function () {
a.minoffset(9);
expect(a.minoffset()).toBe(9);
});
});
describe("minposition attribute", function () {
it("should be able to set/get the minposition attribute", function () {
a.minposition(new Displacement(-1,1));
expect(a.minposition().a()).toEqual(-1);
expect(a.minposition().b()).toEqual(1);
});
});
describe("max attribute", function () {
it("should be able to set/get the max attribute", function () {
a.max("94");
expect(a.max()).toBe("94");
});
it("should throw an error if the parameter is not a string", function () {
expect(function () {
a.max(4);
}).toThrow(new Error("4 should be a string"));
});
});
describe("maxoffset attribute", function () {
it("should be able to set/get the maxoffset attribute", function () {
a.maxoffset(8);
expect(a.maxoffset()).toBe(8);
});
});
describe("maxposition attribute", function () {
it("should be able to set/get the maxposition attribute", function () {
a.maxposition(new Displacement(-1,1));
expect(a.maxposition().a()).toEqual(-1);
expect(a.maxposition().b()).toEqual(1);
});
});
describe("color attribute", function () {
it("should be able to set/get the color attribute", function () {
a.color(RGBColor.parse("0x757431"));
expect(a.color().getHexString()).toBe("0x757431");
});
});
describe("tickmin attribute", function () {
it("should be able to set/get the tickmin attribute", function () {
a.tickmin(7);
expect(a.tickmin()).toBe(7);
});
});
describe("tickmax attribute", function () {
it("should be able to set/get the tickmax attribute", function () {
a.tickmax(22);
expect(a.tickmax()).toBe(22);
});
});
describe("highlightstyle attribute", function () {
it("should be able to set/get the highlightstyle attribute", function () {
a.highlightstyle("bold");
expect(a.highlightstyle()).toBe("bold");
});
});
describe("linewidth attribute", function () {
it("should be able to set/get the linewidth attribute", function () {
a.linewidth(5);
expect(a.linewidth()).toBe(5);
});
});
describe("orientation attribute", function () {
it("should be able to set/get the orientation attribute", function () {
a.orientation(Axis.HORIZONTAL);
expect(a.orientation()).toBe(Axis.HORIZONTAL);
a.orientation(Axis.VERTICAL);
expect(a.orientation()).toBe(Axis.VERTICAL);
});
it("should throw an error if the setter parameter is not 'horizontal' or 'vertical'", function () {
expect(function () {
a.orientation(true);
}).toThrow(new Error("validator failed with parameter true"));
expect(function () {
a.orientation("blahblahblah");
}).toThrow(new Error("validator failed with parameter blahblahblah"));
});
});
describe("AxisTitle", function () {
var title;
beforeEach(function () {
title = new AxisTitle(a);
});
it("should be able to add a AxisTitle to a Axis", function () {
a.title(title);
expect(a.title()).toBe(title);
});
it("should be able to add a AxisTitle with attributes to a Axis", function () {
title.position(new Point(0, 0));
title.content(new Text("time"));
a.title(title);
expect(a.title()).toBe(title);
});
it("should be able to set/get attributes from a title added to a Axis", function () {
a.title(title);
a.title().content(new Text("Time"));
expect(a.title().content().string()).toEqual("Time");
a.title().content(new Text("money"));
expect(a.title().content().string()).toEqual("money");
});
});
describe("Grid", function () {
var grid;
beforeEach(function () {
grid = new Grid();
});
it("should be able to add a Grid to a Axis", function () {
a.grid(grid);
expect(a.grid()).toBe(grid);
});
it("should be able to add a Grid with attributes to a Axis", function () {
grid.visible(false);
a.grid(grid);
expect(a.grid()).toBe(grid);
});
it("should be able to set/get attributes from a grid added to a Axis", function () {
a.grid(grid);
a.grid().visible(true).color(RGBColor.parse("0x345345"));
expect(a.grid().visible()).toBe(true);
expect(a.grid().color().getHexString()).toBe("0x345345");
});
});
describe("Pan", function () {
var pan;
beforeEach(function () {
pan = new Pan();
});
it("should be able to add a Pan to a Axis", function () {
a.pan(pan);
expect(a.pan()).toBe(pan);
});
it("should be able to add a Pan with attributes to a Axis", function () {
pan.allowed(true).max(DataValue.parse("number", "45"));
a.pan(pan);
expect(a.pan()).toBe(pan);
});
it("should be able to set/get attributes from a pan added to a Axis", function () {
a.pan(pan);
a.pan().allowed(false)
.min(DataValue.parse("number", "30"))
.max(DataValue.parse("number", "45"));
expect(a.pan().allowed()).toBe(false);
expect(a.pan().min().getRealValue()).toBe(30);
expect(a.pan().max().getRealValue()).toBe(45);
});
});
describe("Zoom", function () {
var zoom;
beforeEach(function () {
zoom = new Zoom();
});
it("should be able to add a Zoom to a Axis", function () {
a.zoom(zoom);
expect(a.zoom()).toBe(zoom);
});
it("should be able to add a Zoom with attributes to a Axis", function () {
zoom.allowed(false);
a.zoom(zoom);
expect(a.zoom()).toBe(zoom);
});
it("should be able to set/get attributes from a zoom added to a Axis", function () {
a.zoom(zoom);
a.zoom().allowed(true);
a.zoom().min(DataMeasure.parse("number", "13"));
expect(a.zoom().allowed()).toBe(true);
expect(a.zoom().min().getRealValue()).toBe(13);
});
});
xdescribe("Binding", function () {
var binding;
beforeEach(function () {
binding = new Binding("x", "0", "12");
});
it("should be able to add a Binding to a Axis", function () {
a.binding(binding);
expect(a.binding()).toBe(binding);
});
it("should be able to add a Binding with attributes to a Axis", function () {
binding.id("y");
a.binding(binding);
expect(a.binding()).toBe(binding);
});
it("should be able to set/get attributes from a binding added to a Axis", function () {
a.binding(binding);
expect(a.binding().id()).toBe("x");
expect(a.binding().max()).toBe("12");
});
});
describe("dataMin/dataMax attributes", function () {
it("dataMin should initially be undefined", function () {
expect(a.dataMin()).toBeUndefined();
});
it("dataMax should initially be undefined", function () {
expect(a.dataMax()).toBeUndefined();
});
it("dataMin should not be undefined after being set", function () {
a.dataMin(new NumberValue(0.0));
expect(a.dataMin()).not.toBeUndefined();
});
});
describe("initializeGeometry", function () {
var a,
g;
beforeEach(function () {
g = new Graph();
a = new Axis(Axis.HORIZONTAL);
g.axes().add(a);
g.legend(new Legend());
});
it("should do something good", function () {
g.window().margin(new Insets(5,5,5,5));
g.window().border(3);
g.window().padding(new Insets(7,7,7,7));
g.plotarea().margin(new Insets(6,6,6,6));
a.dataMin(new NumberValue(0));
a.dataMax(new NumberValue(10));
g.initializeGeometry(500,500);
// with a window geom of 500x500, plotBox should now be a square whose side is length 500-2*(5+3+7+6) = 458
expect(g.plotBox().width()).toEqual(458);
// axis should have that same length, since default axis length is Displacement(1,0)
expect(a.pixelLength()).toEqual(458);
// "data" length of axis is 10, so axis-to-data ratio should be 458/10:
expect(a.axisToDataRatio()).toEqual(458/10);
// expect left endpoint of axis to convert to 0
expect(a.dataValueToAxisValue(new NumberValue(0))).toEqual(0);
// expect right endpoint of axis to convert to 458
expect(a.dataValueToAxisValue(new NumberValue(10))).toEqual(458);
});
});
});
| henhouse/js-multigraph | spec/core/axis-spec.js | JavaScript | mit | 14,690 |
import MediaBox from "properjs-mediabox";
/**
*
* @description Single app instanceof [MediaBox]{@link https://github.com/ProperJS/MediaBox} for custom audio/video
* @member mediabox
* @memberof core
*
*/
const mediabox = new MediaBox();
/******************************************************************************
* Export
*******************************************************************************/
export default mediabox; | ProperJS/app | main/source/js/core/mediabox.js | JavaScript | mit | 443 |
/*
itemMirror - Version 2.0
Copyright 2015, Keeping Found Things Found, LLC.
All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to copy,
distribute, run, display, perform, and modify the Software for purposes of
academic, research, and personal use, subject to the following conditions:
1. The above copyright notice and this permission notice shall be included in all copies
or substantial portions of the Software.
2. All advertising materials mentioning features or use of this software
must display the following acknowledgement:
This product includes software developed by Keeping Found Things Found.
3. Neither the name of the Keeping Found Things Found nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Keeping Found Things Found , LLC, ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
. For commercial permissions, contact williampauljones@gmail.com
*/
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
//Allow using this built library as an AMD module
//in another project. That other project will only
//see this AMD call, not the internal modules in
//the closure below.
define([], factory);
} else {
//Browser globals case. Just assign the
//result to a property on the global.
root.ItemMirror = factory();
}
}(this, function () {
/**
* @license almond 0.3.1 Copyright (c) 2011-2014, The Dojo Foundation All Rights Reserved.
* Available via the MIT or new BSD license.
* see: http://github.com/jrburke/almond for details
*/
//Going sloppy to avoid 'use strict' string cost, but strict practices should
//be followed.
/*jslint sloppy: true */
/*global setTimeout: false */
var requirejs, require, define;
(function (undef) {
var main, req, makeMap, handlers,
defined = {},
waiting = {},
config = {},
defining = {},
hasOwn = Object.prototype.hasOwnProperty,
aps = [].slice,
jsSuffixRegExp = /\.js$/;
function hasProp(obj, prop) {
return hasOwn.call(obj, prop);
}
/**
* Given a relative module name, like ./something, normalize it to
* a real name that can be mapped to a path.
* @param {String} name the relative name
* @param {String} baseName a real name that the name arg is relative
* to.
* @returns {String} normalized name
*/
function normalize(name, baseName) {
var nameParts, nameSegment, mapValue, foundMap, lastIndex,
foundI, foundStarMap, starI, i, j, part,
baseParts = baseName && baseName.split("/"),
map = config.map,
starMap = (map && map['*']) || {};
//Adjust any relative paths.
if (name && name.charAt(0) === ".") {
//If have a base name, try to normalize against it,
//otherwise, assume it is a top-level require that will
//be relative to baseUrl in the end.
if (baseName) {
name = name.split('/');
lastIndex = name.length - 1;
// Node .js allowance:
if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) {
name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, '');
}
//Lop off the last part of baseParts, so that . matches the
//"directory" and not name of the baseName's module. For instance,
//baseName of "one/two/three", maps to "one/two/three.js", but we
//want the directory, "one/two" for this normalization.
name = baseParts.slice(0, baseParts.length - 1).concat(name);
//start trimDots
for (i = 0; i < name.length; i += 1) {
part = name[i];
if (part === ".") {
name.splice(i, 1);
i -= 1;
} else if (part === "..") {
if (i === 1 && (name[2] === '..' || name[0] === '..')) {
//End of the line. Keep at least one non-dot
//path segment at the front so it can be mapped
//correctly to disk. Otherwise, there is likely
//no path mapping for a path starting with '..'.
//This can still fail, but catches the most reasonable
//uses of ..
break;
} else if (i > 0) {
name.splice(i - 1, 2);
i -= 2;
}
}
}
//end trimDots
name = name.join("/");
} else if (name.indexOf('./') === 0) {
// No baseName, so this is ID is resolved relative
// to baseUrl, pull off the leading dot.
name = name.substring(2);
}
}
//Apply map config if available.
if ((baseParts || starMap) && map) {
nameParts = name.split('/');
for (i = nameParts.length; i > 0; i -= 1) {
nameSegment = nameParts.slice(0, i).join("/");
if (baseParts) {
//Find the longest baseName segment match in the config.
//So, do joins on the biggest to smallest lengths of baseParts.
for (j = baseParts.length; j > 0; j -= 1) {
mapValue = map[baseParts.slice(0, j).join('/')];
//baseName segment has config, find if it has one for
//this name.
if (mapValue) {
mapValue = mapValue[nameSegment];
if (mapValue) {
//Match, update name to the new value.
foundMap = mapValue;
foundI = i;
break;
}
}
}
}
if (foundMap) {
break;
}
//Check for a star map match, but just hold on to it,
//if there is a shorter segment match later in a matching
//config, then favor over this star map.
if (!foundStarMap && starMap && starMap[nameSegment]) {
foundStarMap = starMap[nameSegment];
starI = i;
}
}
if (!foundMap && foundStarMap) {
foundMap = foundStarMap;
foundI = starI;
}
if (foundMap) {
nameParts.splice(0, foundI, foundMap);
name = nameParts.join('/');
}
}
return name;
}
function makeRequire(relName, forceSync) {
return function () {
//A version of a require function that passes a moduleName
//value for items that may need to
//look up paths relative to the moduleName
var args = aps.call(arguments, 0);
//If first arg is not require('string'), and there is only
//one arg, it is the array form without a callback. Insert
//a null so that the following concat is correct.
if (typeof args[0] !== 'string' && args.length === 1) {
args.push(null);
}
return req.apply(undef, args.concat([relName, forceSync]));
};
}
function makeNormalize(relName) {
return function (name) {
return normalize(name, relName);
};
}
function makeLoad(depName) {
return function (value) {
defined[depName] = value;
};
}
function callDep(name) {
if (hasProp(waiting, name)) {
var args = waiting[name];
delete waiting[name];
defining[name] = true;
main.apply(undef, args);
}
if (!hasProp(defined, name) && !hasProp(defining, name)) {
throw new Error('No ' + name);
}
return defined[name];
}
//Turns a plugin!resource to [plugin, resource]
//with the plugin being undefined if the name
//did not have a plugin prefix.
function splitPrefix(name) {
var prefix,
index = name ? name.indexOf('!') : -1;
if (index > -1) {
prefix = name.substring(0, index);
name = name.substring(index + 1, name.length);
}
return [prefix, name];
}
/**
* Makes a name map, normalizing the name, and using a plugin
* for normalization if necessary. Grabs a ref to plugin
* too, as an optimization.
*/
makeMap = function (name, relName) {
var plugin,
parts = splitPrefix(name),
prefix = parts[0];
name = parts[1];
if (prefix) {
prefix = normalize(prefix, relName);
plugin = callDep(prefix);
}
//Normalize according
if (prefix) {
if (plugin && plugin.normalize) {
name = plugin.normalize(name, makeNormalize(relName));
} else {
name = normalize(name, relName);
}
} else {
name = normalize(name, relName);
parts = splitPrefix(name);
prefix = parts[0];
name = parts[1];
if (prefix) {
plugin = callDep(prefix);
}
}
//Using ridiculous property names for space reasons
return {
f: prefix ? prefix + '!' + name : name, //fullName
n: name,
pr: prefix,
p: plugin
};
};
function makeConfig(name) {
return function () {
return (config && config.config && config.config[name]) || {};
};
}
handlers = {
require: function (name) {
return makeRequire(name);
},
exports: function (name) {
var e = defined[name];
if (typeof e !== 'undefined') {
return e;
} else {
return (defined[name] = {});
}
},
module: function (name) {
return {
id: name,
uri: '',
exports: defined[name],
config: makeConfig(name)
};
}
};
main = function (name, deps, callback, relName) {
var cjsModule, depName, ret, map, i,
args = [],
callbackType = typeof callback,
usingExports;
//Use name if no relName
relName = relName || name;
//Call the callback to define the module, if necessary.
if (callbackType === 'undefined' || callbackType === 'function') {
//Pull out the defined dependencies and pass the ordered
//values to the callback.
//Default to [require, exports, module] if no deps
deps = !deps.length && callback.length ? ['require', 'exports', 'module'] : deps;
for (i = 0; i < deps.length; i += 1) {
map = makeMap(deps[i], relName);
depName = map.f;
//Fast path CommonJS standard dependencies.
if (depName === "require") {
args[i] = handlers.require(name);
} else if (depName === "exports") {
//CommonJS module spec 1.1
args[i] = handlers.exports(name);
usingExports = true;
} else if (depName === "module") {
//CommonJS module spec 1.1
cjsModule = args[i] = handlers.module(name);
} else if (hasProp(defined, depName) ||
hasProp(waiting, depName) ||
hasProp(defining, depName)) {
args[i] = callDep(depName);
} else if (map.p) {
map.p.load(map.n, makeRequire(relName, true), makeLoad(depName), {});
args[i] = defined[depName];
} else {
throw new Error(name + ' missing ' + depName);
}
}
ret = callback ? callback.apply(defined[name], args) : undefined;
if (name) {
//If setting exports via "module" is in play,
//favor that over return value and exports. After that,
//favor a non-undefined return value over exports use.
if (cjsModule && cjsModule.exports !== undef &&
cjsModule.exports !== defined[name]) {
defined[name] = cjsModule.exports;
} else if (ret !== undef || !usingExports) {
//Use the return value from the function.
defined[name] = ret;
}
}
} else if (name) {
//May just be an object definition for the module. Only
//worry about defining if have a module name.
defined[name] = callback;
}
};
requirejs = require = req = function (deps, callback, relName, forceSync, alt) {
if (typeof deps === "string") {
if (handlers[deps]) {
//callback in this case is really relName
return handlers[deps](callback);
}
//Just return the module wanted. In this scenario, the
//deps arg is the module name, and second arg (if passed)
//is just the relName.
//Normalize module name, if it contains . or ..
return callDep(makeMap(deps, callback).f);
} else if (!deps.splice) {
//deps is a config object, not an array.
config = deps;
if (config.deps) {
req(config.deps, config.callback);
}
if (!callback) {
return;
}
if (callback.splice) {
//callback is an array, which means it is a dependency list.
//Adjust args if there are dependencies
deps = callback;
callback = relName;
relName = null;
} else {
deps = undef;
}
}
//Support require(['a'])
callback = callback || function () {};
//If relName is a function, it is an errback handler,
//so remove it.
if (typeof relName === 'function') {
relName = forceSync;
forceSync = alt;
}
//Simulate async callback;
if (forceSync) {
main(undef, deps, callback, relName);
} else {
//Using a non-zero value because of concern for what old browsers
//do, and latest browsers "upgrade" to 4 if lower value is used:
//http://www.whatwg.org/specs/web-apps/current-work/multipage/timers.html#dom-windowtimers-settimeout:
//If want a value immediately, use require('id') instead -- something
//that works in almond on the global level, but not guaranteed and
//unlikely to work in other AMD implementations.
setTimeout(function () {
main(undef, deps, callback, relName);
}, 4);
}
return req;
};
/**
* Just drops the config on the floor, but returns req in case
* the config return value is used.
*/
req.config = function (cfg) {
return req(cfg);
};
/**
* Expose module registry for debugging and tooling
*/
requirejs._defined = defined;
define = function (name, deps, callback) {
if (typeof name !== 'string') {
throw new Error('See almond README: incorrect module build, no module name');
}
//This module may not have dependencies
if (!deps.splice) {
//deps is not an array, so probably means
//an object literal or factory function for
//the value. Adjust args.
callback = deps;
deps = [];
}
if (!hasProp(defined, name) && !hasProp(waiting, name)) {
waiting[name] = [name, deps, callback];
}
};
define.amd = {
jQuery: true
};
}());
define("../node_modules/almond/almond", function(){});
/**
* Collection of exceptions associated with the XooML tools.
*
* For ItemMirror core developers only. Enable protected to see.
*
* @class XooMLExceptions
* @static
*
* @protected
*/
define('XooMLExceptions',{
/**
* Thrown when a method is not yet implemented.
*
* @event NotImplementedException
*
* @protected
*/
notImplemented: "NotImplementedException",
/**
* Thrown when a required property from a method's options is missing.
*
* @event MissingParameterException
*
* @protected
*/
missingParameter: "MissingParameterException",
/**
* Thrown when an argument is given a null value when it does not accept null
* values.
*
* @event NullArgumentException
*
* @protected
*/
nullArgument: "NullArgumentException",
/**
* Thrown when an argument is given a value with a different type from the
* expected type.
*
* @event InvalidTypeException
*
* @protected
*/
invalidType: "InvalidTypeException",
/**
* Thrown when an a method is called when the object is in invalid state
* given what the method expected.
*
* @event InvalidStateArgument
*
* @protected
*/
invalidState: "InvalidStateArgument",
/**
* Thrown after receiving an exception from XooMLU Storage
*
* @event XooMLUException
*
* @protected
*/
xooMLUException: "XooMLUException",
/**
* Thrown after receiving an exception from ItemU Storage
*
* @event ItemUException
*
* @protected
*/
itemUException: "ItemUException",
/**
* Thrown after an association was upgraded that could not be upgraded.
*
* @event NonUpgradeableAssociationException
*
* @protected
*/
nonUpgradeableAssociationException: "NonUpgradeableAssociationException",
/**
* Thrown after an argument was passed in an invalid state than expected.
*
* @event InvalidArgumentException
*
* @protected
*/
invalidArgument: "InvalidOptionsException",
/**
* Thrown after expecting a file or folder not to exist when it does.
*
* @event FileOrFolderAlreadyExistsException
*
* @protected
*/
itemAlreadyExists: "ItemAlreadyExistsException",
/**
* Thrown when expecting the ItemMirror to be current, and it is not.
*
* @event FileOrFolderAlreadyExistsException
*
* @protected
*/
itemMirrorNotCurrent: "ItemMirrorNotCurrent"
});
/**
* Configuration variables for XooML.js
*
* For ItemMirror core developers only. Enable protected to see.
*
* @class XooMLConfig
* @static
*
* @protected
*/
define('XooMLConfig',{
// default schema version
schemaVersion: "0.54",
// default schema location
schemaLocation: "http://kftf.ischool.washington.edu/xmlns/xooml",
// XooMLFragment file name for XooML2.xmlns
xooMLFragmentFileName: "XooML2.xml",
// Maximum file length for upgradeAssociation localItemURI truncation
maxFileLength: 50,
// Case 1
createAssociationSimple: {
"displayText": true
},
// Case 2 and 3
// localItemRequested exists:> case 3
createAssociationLinkNonGrouping: {
"displayText": true, // String
"itemURI": true, // String
"localItemRequested": false // String
},
// Case 4 and 5
// localItemRequested:== true:> Case 5
createAssociationLinkGrouping: { // Case 3
"displayText": true,
"groupingItemURI": true,
"xooMLDriverURI": true
},
// Case 6 and 7
createAssociationCreate: {
"displayText": true,
"itemName": true,
"isGroupingItem": true
}
});
/**
* Collection of type checking, exception throwing, utility methods for the
* XooML tools.
*
* For ItemMirror core developers only. Enable protected to see.
*
* @class XooMLUtil
* @static
*
* @protected
*/
define('XooMLUtil',[
"./XooMLExceptions",
"./XooMLConfig"
], function(XooMLExceptions, XooMLConfig) {
"use strict";
var
_GUIDRegex = /\[([a-z0-9]{8}(?:-[a-z0-9]{4}){3}-[a-z0-9]{12})\]/i,
_TYPES = {
"[object Boolean]": "boolean",
"[object Number]": "number",
"[object String]": "string",
"[object Function]": "function",
"[object Array]": "array",
"[object Date]": "date",
"[object RegExp]": "regexp",
"[object Object]": "object",
"[object Error]": "error"
};
var XooMLUtil = {
/**
* Checks if each option within the given checkedOptions is a property of
* the given options.
*
* @method hasOptions
*
* @param {Object} checkedOptions Array of strings for each expected option.
* @param {Object} options Options given to a function.
*
* @protected
*/
hasOptions: function (checkedOptions, options) {
if (!checkedOptions || !options) {
throw XooMLExceptions.nullArgument;
}
if (!XooMLUtil.isObject(checkedOptions) ||
!XooMLUtil.isObject(options)) {
throw XooMLExceptions.invalidType;
}
var checkedOption, isRequiredOption, missingOptionalParamCount;
missingOptionalParamCount = 0;
if (Object.keys(options).length <= Object.keys(checkedOptions).length) {
for (checkedOption in checkedOptions) {
if (checkedOptions.hasOwnProperty(checkedOption)) {
isRequiredOption = checkedOptions[checkedOption];
if (!options.hasOwnProperty(checkedOption)) {
if (isRequiredOption) {
return false;
} else {
missingOptionalParamCount += 1;
}
}
}
}
} else {
return false;
}
return Object.keys(options).length <=
Object.keys(checkedOptions).length - missingOptionalParamCount;
},
// throws exceptions for callbacks since null callbacks mean the program can't continue
checkCallback: function (callback) {
if (callback) {
if (!XooMLUtil.isFunction(callback)) {
throw XooMLExceptions.invalidType;
}
} else {
throw XooMLExceptions.nullArgument;
}
},
isGUID: function (GUID) {
if (XooMLUtil.getType(GUID) === "string") {
return true; // TODO implement guid checking
} else {
return false;
}
},
/**
* Returns if the given value is an array.
*
* Throws NullArgumentException when value is null. <br/>
*
* @method isArray
*
* @param {Object} value Given object have it's type checked.
*
* @protected
*/
isArray: function (value) {
return XooMLUtil.getType(value) === "array";
},
/**
* Returns if the given value is an object.
*
* Throws NullArgumentException when value is null. <br/>
*
* @method isObject
*
* @param {Object} value Given object have it's type checked.
*
* @return {Boolean} True if the given value is an Object, else false.
*
* @protected
*/
isObject: function (value) {
return XooMLUtil.getType(value) === "object";
},
/**
* Returns if the given value is an function.
*
* Throws NullArgumentException when value is null. <br/>
*
* @method isFunction
*
* @param {Object} value Given object have it's type checked.
*
* @return {Boolean} True if the given value is a Function, else false.
*
* @protected
*/
isFunction: function (value) {
return value !== null;
//return XooMLUtil.getType(value) === "function"; TODO figure out why this doesn't work
},
/**
* Returns if the given value is an string.
*
* Throws NullArgumentException when value is null. <br/>
*
* @method isString
*
* @param {Object} value Given object have it's type checked.
*
* @return {Boolean} True if the given value is a String, else false.
*
* @protected
*/
isString: function (value) {
return XooMLUtil.getType(value) === "string";
},
isBoolean: function (value) {
return XooMLUtil.getType(value) === "boolean";
},
/**
* Generates a GUID.
*
* @method generateGUID
*
* @return {String} Randomly generated GUID.
*
* @protected
*/
generateGUID: function () {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
},
getType: function (obj) {
if (obj === null) {
return String(obj);
}
return typeof obj === "object" ||
typeof obj === "function" ? _TYPES[obj.toString()] || "object" : typeof obj;
},
endsWith: function (string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
},
// http://stackoverflow.com/questions/728360/most-elegant-way-to-clone-a-javascript-object
clone: function (obj) {
var copy;
// Handle the 3 simple types, and null or undefined
if (null === obj || "object" != typeof obj) return obj;
// Handle Date
if (obj instanceof Date) {
copy = new Date();
copy.setTime(obj.getTime());
return copy;
}
// Handle Array
if (obj instanceof Array) {
copy = [];
for (var i = 0, len = obj.length; i < len; i++) {
copy[i] = XooMLUtil.clone(obj[i]);
}
return copy;
}
// Handle Object
if (obj instanceof Object) {
copy = {};
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) copy[attr] = XooMLUtil.clone(obj[attr]);
}
return copy;
}
throw XooMLExceptions.invalidType;
}
};
return XooMLUtil;
});
/**
* A utility library for processing file paths. Handles any type of
* file path so long as the separator is "/"
*
* For ItemMirror core developers only. Enable protected to see.
*
* @class PathDriver
*
* @protected
*/
define('PathDriver',[
"./XooMLExceptions",
"./XooMLConfig",
"./XooMLUtil"
], function (
XooMLExceptions,
XooMLConfig,
XooMLUtil) {
"use strict";
var
_PATH_SEPARATOR = "/",
self;
function PathDriver() {}
self = PathDriver.prototype;
/**
* Takes two paths and joins them together.
*
* @method joinPath
* @return {String} The two joined paths
*
* @param {String} root The root path to join
* @param {String} leaf The leaf path to join
*
* @example
* joinPath('/foo/', '/bar/');
* // returns '/foo/bar/'
*
* @protected
*/
self.joinPath = function (rootPath, leafPath) {
var self = this;
if (rootPath === _PATH_SEPARATOR) {
return leafPath;
}
rootPath = self._stripTrailingSlash(rootPath);
leafPath = self._stripLeadingSlash(leafPath);
return rootPath + _PATH_SEPARATOR + leafPath;
};
/**
* Takes an array of paths and joins them all together.
*
* Currently unimplemented and throws notImplemented exception if
* called.
* @method joinPathArrays
*
* @protected
*/
self.joinPathArray = function (rootPath, leafPath) {
throw XooMLExceptions.notImplemented;
};
/**
* Splits a path into an array of the different folders in that
* path; including the root if present.
*
* @method splitPath
* @return {[String]} An array of split up paths
*
* @param {String} path The path to be split
*
* @example
* joinPath('/foo/bar/baz');
* // returns ['', 'foo', 'bar', 'baz']
*
* @protected
*/
self.splitPath = function (path) {
return path.split(_PATH_SEPARATOR);
};
/**
* Formats a path by removing any trailing slashes.
*
* @method formatPath
* @return {String} The well formatted path
*
* @param {String} path The path to be formatted
*
* @example
* format('/foo/bar/');
* // returns '/foo/bar'
*
* @protected
*/
self.formatPath = function (path) {
return self._stripTrailingSlash(path);
};
/**
* @method isRoot
* @return {Boolean} True if root, false otherwise
*
* @param {String} path Path to test for root
*
* @example
* format('/');
* // returns true, anything else will return false
*
* @protected
*/
self.isRoot = function (path) {
return path === _PATH_SEPARATOR;
};
/**
* @method getPathSeparator
* @return {String} The character that is used as a path separator
*
* @example
* getPathSeparator();
* // returns '/'
*
* @protected
*/
self.getPathSeparator = function () {
return _PATH_SEPARATOR;
};
/**
* @method _stripTrailingSlash
* @return {String} The path without any trailing slash
*
* @param {String} path
*
* @private
*/
self._stripTrailingSlash = function (path) {
var strippedPath;
if (path === _PATH_SEPARATOR) {
return path;
}
strippedPath = path;
if (XooMLUtil.endsWith(strippedPath, _PATH_SEPARATOR)) {
strippedPath = strippedPath.substring(0, strippedPath.length - 1);
}
return strippedPath;
};
/**
* @method _stripLeadingSlash
* @return {String} The path without any leading slash
*
* @param {String} path
*
* @private
*/
self._stripLeadingSlash = function (path) {
var strippedPath;
if (path === _PATH_SEPARATOR) {
return path;
}
strippedPath = path;
if (path.indexOf(_PATH_SEPARATOR) === 0) {
strippedPath = strippedPath.substring(1);
}
return strippedPath;
};
return new PathDriver();
});
/**
* AssociationEditor is a minimal interface to represent a XooML2
* association. This object is used together with FragmentEditor to
* fully reprsent a XooML fragment as javascript object. It can be
* converted seamlessly between an object and XML.
*
* Note that upon construction, this doesn't actually create an
* association, merely a /representation/ of an association.
*
* There are two ways to construct an AssociationEditor:
* 1. Through a valid Association XML Element
* 2. By specifying all data through an object
*
* For ItemMirror core developers only. Enable protected to see.
*
* @class AssociationEditor
* @constructor
*
* @param {Object} options The options specified for the constructor
* @param {Element} options.element A DOM element that correctly
* represents an association as specified by the XooML schema.
* @param {Object} options.commonData An object that specifies the
* data for an association. Look at the private constructor
* `_fromOptions` for more details
*
* @protected
*/
define('AssociationEditor',[
"./XooMLExceptions",
"./XooMLUtil"
], function(XooMLExceptions, XooMLUtil) {
"use strict";
var _ELEMENT_NAME = "association",
_NAMESPACE_ELEMENT_NAME = "associationNamespaceElement",
_ID_ATTR = "ID",
_DISPLAY_TEXT_ATTR = "displayText",
_ASSOCIATED_XOOML_FRAGMENT_ATTR = "associatedXooMLFragment",
_ASSOCIATED_XOOML_DRIVER_ATTR = "associatedXooMLDriver",
_ASSOCIATED_SYNC_DRIVER_ATTR = "associatedSyncDriver",
_ASSOCIATED_ITEM_DRIVER_ATTR = "associatedItemDriver",
_ASSOCIATED_ITEM_ATTR = "associatedItem",
_LOCAL_ITEM_ATTR = "localItem",
_IS_GROUPING_ATTR = "isGrouping";
function AssociationEditor(options) {
var self = this;
if (options.element) {
_fromElement(options.element, self);
} else if (options.commonData) {
_fromOptions(options.commonData, self);
} else {
console.log(XooMLExceptions.missingParameter);
}
}
/**
* Converts the object into an association element, which can then
* be converted to a string or added to the DOM.
*
* @method toElement
*
* @returns {Element} A DOM element that can be further manipulated
* with DOM methods
*
* @protected
*/
AssociationEditor.prototype.toElement = function() {
var self = this,
// The We use a null namespace to leave it blank, otherwise it
// sets it as XHTML and won't serialize attribute names properly.
// The namespace will be inherited by the fragment it resides in.
associationElem = document.createElementNS(null, _ELEMENT_NAME);
// common data
Object.keys(self.commonData).forEach( function(key) {
if ( self.commonData[key] ) {// Don't set null attributes
associationElem.setAttribute(key, self.commonData[key]);
}
});
// namespace data
Object.keys(self.namespace).forEach( function(uri) {
var nsElem = document.createElementNS(uri, _NAMESPACE_ELEMENT_NAME);
// Attributes
Object.keys(self.namespace[uri].attributes).forEach( function(attrName) {
nsElem.setAttributeNS(uri, attrName, self.namespace[ uri ].attributes[ attrName ]);
});
// Data
nsElem.textContent = self.namespace[ uri ].data;
associationElem.appendChild(nsElem);
});
return associationElem;
};
/**
* Takes an association element in XML and then converts that into
* an AssociationEditor object. Intended to be one of the ways the
* object is constructed
*
* @method _fromElement
*
* @param {Element} element The XML element that represents an association.
*/
function _fromElement(element, self) {
var dataElems, i, uri, elem;
// Sets all common data attributes
self.commonData = {
ID: element.getAttribute(_ID_ATTR),
displayText: element.getAttribute(_DISPLAY_TEXT_ATTR),
associatedXooMLFragment: element.getAttribute(_ASSOCIATED_XOOML_FRAGMENT_ATTR),
associatedXooMLDriver: element.getAttribute(_ASSOCIATED_XOOML_DRIVER_ATTR),
associatedSyncDriver: element.getAttribute(_ASSOCIATED_SYNC_DRIVER_ATTR),
associatedItemDriver: element.getAttribute(_ASSOCIATED_ITEM_DRIVER_ATTR),
associatedItem: element.getAttribute(_ASSOCIATED_ITEM_ATTR),
localItem: element.getAttribute(_LOCAL_ITEM_ATTR),
// We use JSON.parse to get the value as a boolean, not as a string
isGrouping: JSON.parse(element.getAttribute(_IS_GROUPING_ATTR))
};
self.namespace = {};
dataElems = element.getElementsByTagName(_NAMESPACE_ELEMENT_NAME);
for (i = 0; i < dataElems.length; i += 1) {
elem = dataElems[i];
uri = elem.namespaceURI;
/**
* The information for a given namespace. Includes both the
* data, and the attributes. Namespaces URIs must be unique or
* they will overwrite data from another namespace
* @property namespace.URI
* @type Object
*/
self.namespace[ uri ] = {};
self.namespace[ uri ].attributes = {};
for (i = 0; i < elem.attributes.length; i += 1) {
// We have to filter out the special namespace attribute We
// let the namespace methods handle the namespace, and we
// don't deal with it
if (elem.attributes[i].name !== "xmlns") {
/**
* The attributes of the current namespace, with each attribute
* having a corresponding value.
* @property namespace.URI.attributes
* @type Object
*/
self.namespace[ uri ].attributes[ elem.attributes[i].localName ] =
elem.getAttributeNS(uri, elem.attributes[i].localName );
}
}
/**
* This is the namespace data stored within the namespace
* element. Anything can be put here, and it will be stored as a
* string. ItemMirror will not do anything with the data here and
* doesn't interact with it at all. It is the responsibility of
* other applications to properly store information here.
* @property namespace.URI.data
* @type String
*/
self.namespace[ uri ].data = elem.textContent;
}
}
/**
* Constructs an association with data from an object
* @method _fromOptions
*
* @param {Object} commonData Common data that is used by the
* itemMirror library, and is app agnostic
* @param {String} commonData.displayText Display text for the
* association
* @param {String} commonData.associatedXooMLFragment URI of the
* associated XooML fragment for the association
* @param {String} commonData.associatedItem URI of the associated item
* @param {String} commonData.associatedXooMLDriver The associated
* XooML driver for the association
* @param {String} commonData.associatedItemDriver The associated
* item driver for the association
* @param {String} commonData.associatedSyncDriver The associated
* sync driver of the association
* @param {String} commonData.localItem The name/id of the
* association
* @param {Boolean} comnmonData.isGrouping Whether or not the
* association is a grouping item
* @param {String} commonData.readOnlyURLtoXooMLfragment Used in
* cases where the owner wishes for the XooML fragment representing
* an item to be public
* @protected
* @private
*/
function _fromOptions(commonData, self) {
if (!commonData) {
throw XooMLExceptions.nullArgument;
}
// Properties from the common data
/**
* Common Data of the association that is accessible to all applications
* @property commonData
* @type Object
*/
self.commonData = {
/**
* Text that describes the association
* @property commonData.displayText
* @type String
*/
displayText: commonData.displayText || null,
/**
* The associated XooML fragment of the association
* @property commonData.associatedXooMLFragment
* @type String
*/
associatedXooMLFragment: commonData.associatedXooMLFragment || null,
/**
* The associated XooML driver of the association
* @property commonData.associatedXooMLDriver
* @type String
*/
associatedXooMLDriver: commonData.associatedXooMLDriver || null,
/**
* The associated sync driver of the association
* @property commonData.associatedSyncDriver
* @type String
*/
associatedSyncDriver: commonData.associatedSyncDriver || null,
/**
* The associated item driver of the association
* @property commonData.associatedItemDriver
* @type String
*/
associatedItemDriver: commonData.associatedItemDriver || null,
/**
* The associated item of the association
* @property commonData.associatedItem
* @type String
*/
associatedItem: commonData.associatedItem || null,
/**
* The local item of the association
* @property commonData.localItem
* @type String
*/
localItem: commonData.localItem || null,
/**
* Whether or not the item is a grouping item
* @property commonData.isGrouping
* @type Boolean
*/
isGrouping: commonData.isGrouping || false,
/**
* The GUID of the association
* @property commonData.ID
* @type String
*/
// GUID is generated upon construction
ID: XooMLUtil.generateGUID()
};
/**
* Data for the namespaces. Stored as a key pair value, with each
* namespace referencing the namespace association element for the
* corresponding namespace.
*
* @property namespace
* @type Object
*/
self.namespace = {};
/**
* The attributes of the current namespace, with each attribute
* having a corresponding value.
* @property namespace.URI.attributes
* @type Object
*/
/**
* This is the namespace data stored within the namespace
* element. Anything can be put here, and it will be stored as a
* string. ItemMirror will not do anything with the data here and
* doesn't interact with it at all. It is the responsibility of
* other applications to properly store information here.
*
* @property namespace.URI.data
* @type String
*/
}
return AssociationEditor;
});
/**
* An item utility interacts with the item storage and is responsible for
* creating and deleting items. This is an implementation of item utility
* using Dropbox as the item storage.
*
* For ItemMirror core developers only. Enable protected to see.
*
* @class ItemDriver
* @constructor
*
* @param {Object} options Data to construct a new ItemU with
* @param {String} options.utilityURI URI of the utility
* @param {Object} options.dropboxClient Authenticated dropbox client
*
* @protected
*/
define('ItemDriver',[
"./XooMLExceptions",
"./XooMLConfig",
"./XooMLUtil",
"./AssociationEditor"
], function(
XooMLExceptions,
XooMLConfig,
XooMLUtil,
AssociationEditor) {
"use strict";
var
// private static variables
_CONSTRUCTOR__OPTIONS = {
driverURI: true,
dropboxClient: true
},
_DIRECTORY_STAT = "inode/directory",
//oop helper
self;
/**
* Constructs a ItemDriver for reading/writing Item Storage
*
* @protected
*/
function ItemDriver(options, callback) {
XooMLUtil.checkCallback(callback);
if (!XooMLUtil.isObject(options)) {
return callback(XooMLExceptions.invalidType);
}
if (!XooMLUtil.isFunction(callback)) {
return callback(XooMLExceptions.invalidType);
}
if (!XooMLUtil.hasOptions(_CONSTRUCTOR__OPTIONS, options)) {
return callback(XooMLExceptions.missingParameter);
}
var self = this;
// private variables
self._dropboxClient = options.dropboxClient;
if (self._checkDropboxAuthenticated(self._dropboxClient)) {
callback(false, self);
} else {
self._dropboxClient.authenticate(function (error) {
if (error) {
return callback(XooMLExceptions.itemUException, null);
}
return callback(false, self);
});
}
}
self = ItemDriver.prototype;
// callback(false) on success
self.moveGroupingItem = function (fromPath, newPath, callback) {
var self = this;
self._dropboxClient.move(fromPath, newPath, function (error, stat) {
if (error) {
return callback(error);
}
return callback(false);
});
};
self.isGroupingItem = function (path, callback) {
var self = this;
self._dropboxClient.stat(path, function (error,stat){
if (error) {
return self._showDropboxError(error, callback);
}
return callback(false, stat.mimeType === _DIRECTORY_STAT);
});
};
/**
* Creates a grouping item at the location
* @method createGroupingItem
* @param {String} path the path to the location that the grouping item will be created
* @param {Function} callback Function to be called when self function is finished with it's operation.
*
* @protected
*/
self.createGroupingItem = function (path, callback) {
var self = this;
self._dropboxClient.mkdir(path, function (error, stat) {
if (error) {
return self._showDropboxError(error, callback);
}
return callback(false, stat);
});
};
/**
* Creates or uploads a non-grouping item at the location
* @method createNonGroupingItem
* @param {String} path the path to the location that the non-grouping item will be created
* @param {String} file the contents to be written to the non-grouping item
* @param {Function} callback Function to be called when self function is finished with it's operation.
*
* @protected
*/
self.createNonGroupingItem = function (path, file, callback) {
var self = this;
self._dropboxClient.writeFile(path, file, function (error, stat) {
if (error) {
return self._showDropboxError(error, callback);
}
return callback(false, stat);
});
};
/**
* Deletes a grouping item at the location
* @method deleteGroupingItem
* @param {String} path the path to the location that the grouping item is located
* @param {Function} callback Function to be called when self function is finished with it's operation.
*
* @protected
*/
self.deleteGroupingItem = function (path, callback) {
var self = this;
self._dropboxClient.remove(path, function (error, stat) {
if (error) {
return self._showDropboxError(error, callback);
}
return callback(false, stat);
});
};
/**
* Deletes a non-grouping item at the location
* @method deleteNonGroupingItem
* @param {String} path the path to the location that the non-grouping item is located
* @param {String} name the name of the non-grouping item
* @param {Function} callback Function to be called when self function is finished with it's operation.
*
* @protected
*/
self.deleteNonGroupingItem = function (path, callback) {
var self = this;
self._dropboxClient.remove(path, function (error, stat) {
if (error) {
return self._showDropboxError(error, callback);
}
return callback(false, stat);
});
};
/**
* Copies an item in the fashion of moveItem
* @method copyItem
* @param {String} fromPath the path to the file you want copied
* @param {String} toPath the GroupingItem path you want the fromPath file copied to
* @param {Function} callback Function to be called when self function is finished with it's operation.
*
* @protected
*/
self.copyItem = function (fromPath, toPath, callback) {
var self = this;
self._dropboxClient.copy(fromPath, toPath, function(error){
if (error) {
return self._showDropboxError(error, callback);
}
return callback(false);
});
};
/**
* Moves an item
* @method moveItem
* @param {String} fromPath the path to the file you want moved
* @param {String} toPath the GroupingItem path you want the fromPath file moved
* @param {Function} callback Function to be called when self function is finished with it's operation.
*
* @protected
*/
self.moveItem = function (fromPath, toPath, callback) {
var self = this;
self._dropboxClient.move(fromPath, toPath, function(error){
if (error) {
return self._showDropboxError(error, callback);
}
return callback(false);
});
};
/**
* Get publicly readable download url for a non-grouping item from Dropbox website.
* @method getURL
* @param {String} path the path to the location that the non-grouping item is located
* @param {Function} callback Function to be called when self function is finished with it's operation.
*
* @protected
*/
self.getURL = function (path, callback){
var self = this;
self._dropboxClient.makeUrl(path, null, function (error, publicURL){
if (error) {
return self._showDropboxError(error, callback);
}
return callback(false, publicURL.url);
});
};
/**
* Lists the items under the grouping item
* @method listItems
* @param {String} path the path to the grouping item
* @param {Function} callback(output) Function to be called when self function is finished with it's operation. Output is an array of AssociationEditors.
*
* @protected
*/
self.listItems = function (path, callback) {
var self = this;
self._dropboxClient.readdir(path, function (error, list, stat, listStat) {
if (error) {
return self._showDropboxError(error, callback);
}
var i, output;
output = [];
for (i = 0; i < listStat.length; i += 1) {
if (listStat[i].name !== XooMLConfig.xooMLFragmentFileName) {
output.push(new AssociationEditor({
commonData: { displayText: listStat[i].name,
isGrouping: listStat[i].isFolder,
localItem: listStat[i].name,
associatedItem: listStat[i].isFolder ? listStat[i].path : null
}
}));
}
}
return callback(false, output);
});
};
/**
* Check if the item is existed
* @method checkExisted
* @param {String} path the path to the location that the item is located
* @param {String} name the name of the item
* @param {Function} callback(result) Function to be called when self function is finished with it's operation. Result is the bollean value for whether existed.
*
* @protected
*/
self.checkExisted = function(path, callback){
var self = this, result;
self._dropboxClient.stat(path, function (error,stat){
if (error) {
return self._showDropboxError(error, callback);
}
result = !(error !== null && error.status === 404) || (error === null && stat.isRemoved);
return callback(false, result);
});
};
self._showDropboxError = function (error, callback) {
return callback(error.status);
};
self._checkDropboxAuthenticated = function (dropboxClient) {
return dropboxClient.authState === 4;
};
return ItemDriver;
});
/**
* An XooML utility interacts with an storage and is responsible for
* reading and writing XooML fragments. This is an implementation of XooML utility
* using Dropbox as the storage.
*
* For ItemMirror core developers only. Enable protected to see.
*
* @class XooMLDriver
* @constructor
*
* @param {Object} options Data to construct a new XooMLU with
* @param {String} options.fragmentURI The URI of fragment
* contains the XooML
* @param {String} options.utilityURI URI of the utility
* @param {Object} options.dropboxClient Authenticated dropbox client
*
* @protected
*/
define('XooMLDriver',[
"./XooMLExceptions",
"./XooMLConfig",
"./XooMLUtil"
], function(
XooMLExceptions,
XooMLConfig,
XooMLUtil) {
"use strict";
var
_CONSTRUCTOR_OPTIONS = {
driverURI: true,
dropboxClient: true,
fragmentURI: true
};
/**
* Constructs a XooMLDriver for reading/writing XooML fragment.
*
* @protected
*/
function XooMLDriver(options, callback) {
XooMLUtil.checkCallback(callback);
if (!XooMLUtil.hasOptions(_CONSTRUCTOR_OPTIONS, options)) {
return callback(XooMLExceptions.missingParameter);
}
if (!XooMLUtil.isObject(options)) {
return callback(XooMLExceptions.invalidType);
}
var self = this;
self._dropboxClient = options.dropboxClient;
self._fragmentURI = options.fragmentURI;
if (self._checkDropboxAuthenticated(self._dropboxClient)) {
return callback(false, self);
} else {
self._dropboxClient.authenticate(function (error, client) {
if (error) {
return callback(XooMLExceptions.xooMLUException, null);
}
return callback(false, self);
});
}
}
/**
* Reads and returns a XooML fragment
* @method getXooMLFragment
* @param {Function} callback(content) Function to be called when self function is finished with it's operation. content is the content of the XooML fragment.
*
* @protected
*/
XooMLDriver.prototype.getXooMLFragment = function (callback) {
var self = this;
self._dropboxClient.readFile(self._fragmentURI, function (error, content) {
if (error) {
return self._showDropboxError(error, callback);
}
callback(false, content);
});
};
/**
* Writes a XooML fragment
* @method setXooMLFragment
* @param {String} uri the location of the XooML fragment
* @param {String} fragment the content of the XooML fragment
* @param {Function} callback(content) Function to be called when self function is finished with it's operation. content is the content of the XooML fragment.
*
* @protected
*/
XooMLDriver.prototype.setXooMLFragment = function (fragment, callback) {
var self = this;
self._dropboxClient.writeFile(self._fragmentURI, fragment, function (error, stat) {
if (error) {
return self._showDropboxError(error, callback);
}
callback(false, stat);
});
};
/**
* Check if the XooML fragment exists
* @method checkExists
* @param {Function} callback Function to be called when
* self function is finished with it's operation.
* @param {String} callback.error Dropbox error if there is one
* @param {Boolean} callback.result True if the fragment exists and
* false otherwis
*
* @protected
*/
XooMLDriver.prototype.checkExists = function (callback) {
var self = this, result;
self._dropboxClient.stat(self._fragmentURI, function (error, stat) {
if (error) {
return self._showDropboxError(error, callback);
}
if ((error !== null && error.status === 404) || (error === null && stat.isRemoved === true)) {
result = false;
} else {
result = true;
}
callback(false, result);
});
};
XooMLDriver.prototype._showDropboxError = function (error, callback) {
return callback(error.status);
};
XooMLDriver.prototype._checkDropboxAuthenticated = function (dropboxClient) {
return dropboxClient.authState === 4;
};
return XooMLDriver;
});
/**
* Constructs a FragmentWrapper for a XooML fragment. In the following cases.
*
* 1. XooMLFragment String is passed in and is used as the XooMLFragment
* 2. XooMLFragment Element is passed in and is used as the XooMLFragment.
* 2. Associations, XooMLDriver, ItemDriver, SyncDriver,
* groupingItemURI are given and used to create a new XooMLFragment with
* the given data.
*
* The FragmentWrapper is merely a representation of a XooML fragment,
* and is used by an itemMirror that actually handles the details of
* creating deleting and modifying associations.
*
* For ItemMirror core developers only. Enable protected to see.
*
* @class FragmentEditor
* @constructor
*
* @param {Object} options Data to construct a new FragmentWrapper with
* @param {String} options.text Unparsed XML directly from a storage
* platform.
* @param {Element} options.element XML Element representing a XooML
* fragment. Required for case 1.
* @param {AssociationEditor[]} options.associations List of associations for
* the newly constructed XooMLFragment in case 2. <br/>__optional__
* @param {Object} options.commonData Common data for the
* fragment. Look at the constructor for more details. Required for case 2
* @param {String} options.groupingItemURI The URI for the grouping
* item of the fragment. Required for case 2.
*
* @protected
**/
define('FragmentEditor',[
"./XooMLExceptions",
"./XooMLConfig",
"./XooMLUtil",
"./PathDriver",
"./AssociationEditor"
], function(
XooMLExceptions,
XooMLConfig,
XooMLUtil,
PathDriver,
AssociationEditor) {
"use strict";
var _ELEMENT_NAME = "fragment",
_ASSOCIATION_ELEMENT_NAME = "association",
_ASSOCIATION_ID_ATTR = "ID",
_NAMESPACE_ELEMENT_NAME = "fragmentNamespaceElement",
_SCHEMA_VERSION_ATTR = "schemaVersion",
_SCHEMA_LOCATION_ATTR = "schemaLocation",
_ITEM_DESCRIBED_ATTR = "itemDescribed",
_DISPLAY_NAME_ATTR = "displayName",
_ITEM_DRIVER_ATTR = "itemDriver",
_SYNC_DRIVER_ATTR = "syncDriver",
_XOOML_DRIVER_ATTR = "xooMLDriver",
_GUID_ATTR = "GUIDGeneratedOnLastWrite",
_ITEM_MIRROR_NS = "http://kftf.ischool.washington.edu/xmlns/xooml";
function FragmentEditor(options) {
var self = this;
if (options.text) {
_fromString(options.text, self);
} else if (options.element) {
_fromElement(options.element, self);
} else if (options.commonData) {
_fromOptions(options.commonData, options.associations, self);
} else {
console.log(XooMLExceptions.missingParameter);
}
}
/**
* Updates the GUID of the Fragment
*
* @method updateID
* @return {String} The new GUID of the fragment
* @private
* @protected
*/
FragmentEditor.prototype.updateID = function() {
var self = this, guid;
guid = XooMLUtil.generateGUID();
this.commonData.GUIDGeneratedOnLastWrite = guid;
return guid;
};
/**
* Converts a FragmentEditor object into an XML element, which can
* then be serialized and saved as a string, or further manipulated
* with DOM methods
* @method toElement
* @return {Element} The XooML fragment as an XML element
* @protected
*/
FragmentEditor.prototype.toElement = function() {
var self = this,
fragmentElem = document.createElementNS(_ITEM_MIRROR_NS, _ELEMENT_NAME);
// common data
Object.keys(self.commonData).forEach( function(attrName) {
var attrValue = self.commonData[attrName];
if (attrValue) { // Don't set null attributes
fragmentElem.setAttribute(attrName, attrValue);
}
});
// namespace data
Object.keys(self.namespace).forEach( function(uri) {
var nsElem = document.createElementNS(uri, _NAMESPACE_ELEMENT_NAME);
// Attributes
Object.keys(self.namespace[uri].attributes).forEach( function(attrName) {
nsElem.setAttributeNS(uri, attrName, self.namespace[ uri ].attributes[ attrName ]);
});
nsElem.textContent = self.namespace[ uri ].data;
fragmentElem.appendChild(nsElem);
});
// associations
Object.keys(self.associations).forEach( function(id) {
fragmentElem.appendChild( self.associations[id].toElement() );
});
return fragmentElem;
};
/**
* Returns the XML of a fragment as a string, _not_ the string
* version of the object. This is used for persisting the fragment
* across multiple platforms
* @method toString
* @return {String} Fragment XML
*/
FragmentEditor.prototype.toString = function() {
var serializer = new XMLSerializer();
return serializer.serializeToString( this.toElement() );
};
/**
* Constructs a fragmentEditor based on data passed into the
* parameters
*
* @method _fromOptions
*
* @param {Object} commonData An object containing common data for the association
* @param {String} commonData.schemaVersion The version of the schema <br/> __required__
* @param {String} commonData.schemaLocation The location of the schema
* @param {String} commonData.itemDescribed URI pointing to item for which the
* XooML fragment is metadata.
* @param {String} commonData.displayName Display name of the fragment
* @param {String} commonData.itemDriver The URI of the item driver for the fragment
* @param {String} commonData.syncDriver The URI of the sync driver for the fragment
* @param {String} commonData.xooMLDriver The URI of the XooML driver for the fragment
* @param {String} commonData.GUIDGeneratedOnLastWrite The GUID generated the last time the fragment was written
* @param {AssociationEditor[]} associations An array of associations that the fragment has
* @param {String} namespace The namespace URI that an app will use for it's own private data
* @param {FragmentEditor} self
*
* @private
*/
function _fromOptions(commonData, associations, self) {
if (!commonData) {
throw XooMLExceptions.nullArgument;
}
// Properties from the common data
/**
* Common Data of the association that is accessible to all applications
* @property commonData
* @type Object
*/
self.commonData = {
/**
* Text that describes the fragment
* @property commonData.displayName
* @type String
*/
displayName: commonData.displayName || null,
/**
* The schema location for the fragment
* @property commonData.schemaLocation
* @type String
*/
schemaLocation: commonData.schemaLocation || null,
/**
* The schema version for the fragment
* @property commonData.schemaVersion
* @type String
*/
schemaVersion: commonData.schemaVersion || null,
/**
* The item driver URI for the fragment
* @property commonData.itemDriver
* @type String
*/
itemDriver: commonData.itemDriver || null,
/**
* The item described for the fragment. This is a URI that
* points to grouping item from wich the itemMirror was created
* @property commonData.
* @type String
*/
itemDescribed: commonData.itemDescribed || null,
/**
* The sync driver URI for the fragment
* @property commonData.syncDriver
* @type String
*/
syncDriver: commonData.syncDriver || null,
/**
* The XooML driver URI for the fragment
* @property commonData.xooMLDriver
* @type String
*/
xooMLDriver: commonData.xooMLDriver || null,
/**
* The unique GUID for the fragment that is updated after every
* write
* @property commonData.GUIDGeneratedOnLastWrite
* @type String
*/
GUIDGeneratedOnLastWrite: XooMLUtil.generateGUID()
};
/**
* The associations of the fragment. Each association is accessed
* by referencing it's ID, which then gives the corresponding
* AssociationEditor object for manipulating that association.
* @property associations
* @type Object
*/
// Takes the association array and turns it into an associative
// array accessed by the GUID of an association
self.associations = {};
associations.forEach( function(assoc) {
var guid = assoc.commonData.ID;
self.associations[guid] = assoc;
});
/**
* The namespace data of the fragment. Holds both the URI as well
* as the namespace specific data for the fragment
* @property namespace
* @type Object
*/
self.namespace = {};
/**
* The namespace URI for the fragment. Used to set namespace data
* for both the fragment and it's associations
* @property namespace.uri
* @type String
*/
/**
* The attributes of the namespace. This is app specific data
* that is set for the fragment. Each key pair in the object
* represents an attribute name and it's corresponding value
* @property namespace.attributes
* @type Object
*/
}
/**
* Takes a fragment in the form of a string and then parses that
* into XML. From there it converts that element into an object
* using the _fromElement method
*
* @param {String} text The text representing the fragment. Should
* be obtained directly from a storage platform like dropbox or a
* local filesystem
* @param {String} namespace The URI of the namespace that will
* initially be used for the fragment when handling any namespace
* data
* @param {FragmentEditor} self
*/
function _fromString(text, namespace, self) {
var parser = new DOMParser();
var doc = parser.parseFromString(text, "application/xml");
_fromElement(doc.children[0], namespace, self);
}
/**
* Takes a fragment element in XML and then converts that into a
* FragmentEditor object. Intended to be one of the ways the object
* is constructed
*
* @method _fromElement
*
* @param {Element} element The XML element that represents an association.
* @param {FragmentEditor} self
* @private
*/
function _fromElement(element, self) {
var dataElems, nsElem, i, associationElems, guid, elem, uri;
// Sets all common data attributes
self.commonData = {
fragmentNamespaceElement: element.getAttribute(_NAMESPACE_ELEMENT_NAME),
schemaVersion: element.getAttribute(_SCHEMA_VERSION_ATTR),
schemaLocation: element.getAttribute(_SCHEMA_LOCATION_ATTR),
itemDescribed: element.getAttribute(_ITEM_DESCRIBED_ATTR),
displayName: element.getAttribute(_DISPLAY_NAME_ATTR),
itemDriver: element.getAttribute(_ITEM_DRIVER_ATTR),
syncDriver: element.getAttribute(_SYNC_DRIVER_ATTR),
xooMLDriver: element.getAttribute(_XOOML_DRIVER_ATTR),
GUIDGeneratedOnLastWrite: element.getAttribute(_GUID_ATTR)
};
/**
* The namespace object is an associated array with each key being
* a namespace URI. These can thene be used to modify fragment
* namespace attributes and data
* @property namespace
* @type Object
*/
self.namespace = {};
dataElems = element.getElementsByTagName(_NAMESPACE_ELEMENT_NAME);
for (i = 0; i < dataElems.length; i += 1) {
elem = dataElems[i];
uri = elem.namespaceURI;
/**
* The information for a given namespace. Includes both the
* data, and the attributes. Namespaces URIs must be unique or
* they will overwrite data from another namespace
* @property namespace.URI
* @type Object
*/
self.namespace[ uri ] = {};
self.namespace[ uri ].attributes = {};
for (i = 0; i < elem.attributes.length; i += 1) {
// We have to filter out the special namespace attribute We
// let the namespace methods handle the namespace, and we
// don't deal with it
if (elem.attributes[i].name !== "xmlns") {
/**
* The attributes of the current namespace, with each attribute
* having a corresponding value.
* @property namespace.URI.attributes
* @type Object
*/
self.namespace[ uri ].attributes[ elem.attributes[i].localName ] =
elem.getAttributeNS(uri, elem.attributes[i].localName);
}
}
/**
* This is the namespace data stored within the namespace
* element. Anything can be put here, and it will be stored as a
* string. ItemMirror will not do anything with the data here and
* doesn't interact with it at all. It is the responsibility of
* other applications to properly store information here.
* @property namespace.URI.data
* @type String
*/
self.namespace[ uri ].data = elem.textContent;
}
// associations
self.associations = {};
associationElems = element.getElementsByTagName(_ASSOCIATION_ELEMENT_NAME);
for (i = 0; i < associationElems.length; i += 1) {
guid = associationElems[i].getAttribute(_ASSOCIATION_ID_ATTR);
self.associations[guid] = new AssociationEditor({
element: associationElems[i]
});
}
}
return FragmentEditor;
});
/**
* An implementation of SyncDriver which syncronizes the XooML so that
* it reflects the storage. This implementation ensures that only the
* XooML is modified, and that the user's storage is never modified,
* safely protecting any data.
*
* For ItemMirror core developers only. Enable protected to see.
*
* @class SyncDriver
*
* @constructor
* @param {Object} itemMirror The itemMirror object which you wish to
* synchronize
*
* @protected
*/
define('SyncDriver',[
"./XooMLDriver",
"./XooMLExceptions",
"./XooMLConfig",
"./XooMLUtil",
"./FragmentEditor",
"./AssociationEditor"
], function(
XooMLDriver,
XooMLExceptions,
XooMLConfig,
XooMLUtil,
FragmentEditor,
AssociationEditor) {
"use strict";
var self;
function SyncDriver(itemMirror) {
var self = this;
self._itemMirror = itemMirror;
self._itemDriver = itemMirror._itemDriver;
self._xooMLDriver = itemMirror._xooMLDriver;
}
/**
* Helper method that allows for sorting of objects by the localItem
*
* @method _nameCompare
* @private
* @protected
*/
function _localItemCompare(a, b) {
if (a.commonData.localItem > b.commonData.localItem) return 1;
else if (a.commonData.localItem < b.commonData.localItem) return -1;
else return 0;
}
/**
* Synchonizes the itemMirror object.
*
* @method sync
*
* @param {Function} callback Function to execute once finished.
* @param {Object} callback.error Null if no error has occurred
* in executing this function, else an contains
* an object with the error that occurred.
*
* @protected
*/
SyncDriver.prototype.sync = function(callback) {
var self = this,
itemAssociations;
self._itemDriver.listItems(self._itemMirror._groupingItemURI,
processItems);
function processItems(error, associations){
if (error) return callback(error);
itemAssociations = associations;
self._xooMLDriver.getXooMLFragment(processXooML);
}
function processXooML(error, xooMLContent) {
// A 404 error is dropbox telling us that the file doesn't
// exist. In that case we just write the file
if (error === 404) {
var fragmentString = self._itemMirror._fragment.toString();
return self._xooMLDriver.setXooMLFragment( fragmentString, function(error) {
if (error) callback(error);
else callback(false);
});
} else if (error) {
return callback(error);
}
// Keeps track of the index in the xooMLassociations so that
// we don't waste time searching from the beginning
var xooMLIdx = 0;
// Keeps track of whether there are any changes that need to be made
var synchronized = true;
var xooMLAssociations;
self._fragmentEditor = new FragmentEditor({text: xooMLContent});
xooMLAssociations = Object.keys(self._fragmentEditor.associations)
// Turns the associative array into a regular array for iteration
.map( function(guid) {
return self._fragmentEditor.associations[guid];
})
// filters out any phantoms
.filter( function(assoc) {
return assoc.commonData.localItem !== null;
});
// No guarantee that the storage API sends results sorted
itemAssociations.sort(_localItemCompare);
xooMLAssociations.sort(_localItemCompare);
// Gets the localItems in a separate array, but in needed sorted order
var itemLocals = itemAssociations.map( function (assoc) {return assoc.commonData.localItem;} );
var xooMLLocals = xooMLAssociations.map( function (assoc) {return assoc.commonData.localItem;} );
itemLocals.forEach( function(localItem, itemIdx) {
var search = xooMLLocals.lastIndexOf(localItem, xooMLIdx);
// Create association
if (search === -1) {
synchronized = false;
// Case 6/7 only, other cases won't be handled
var association = itemAssociations[itemIdx];
self._fragmentEditor.associations[association.commonData.ID] = association;
} else {
// Deletes any extraneous associations
xooMLAssociations
.slice(xooMLIdx, search)
.forEach( function(assoc) {
synchronized = false;
delete self._fragmentEditor.associations[assoc.guid];
});
xooMLIdx = search + 1;
}
});
// Any remaining associations need to be deleted because they don't exist
xooMLAssociations
.slice(xooMLIdx, xooMLLocals.length)
.forEach( function(assoc) {
synchronized = false;
delete self._fragmentEditor.associations[assoc.commonData.ID];
});
// Only save fragment if needed
if (!synchronized) {
self._fragmentEditor.updateID(); // generate a new guid for GUIDGeneratedOnLastWrite;
// Writes out the fragment
self._xooMLDriver.setXooMLFragment(self._fragmentEditor.toString(), function(error) {
if (error) return callback(error);
return callback(false);
});
} else return callback(false);
}
};
return SyncDriver;
});
/**
* ItemMirror represents an Item according to the XooML2 specification.
*
* It can be instantiated using one of the following two cases based on the
* given arguments.
*
* 1. XooMLFragment already exists. Given xooMLFragmentURI and xooMLDriver.
* 2. The XooMLFragment is created from an existing groupingItemURI (e.g., a dropbox folder).
* Given a groupingItemURI, itemDriver, and a xooMLDriver a new itemMirror will be constructed for given groupingItemURI.
*
* Throws NullArgumentException when options is null.
*
* Throws MissingParameterException when options is not null and a required
* argument is missing.
*
* @class ItemMirror
* @constructor
*
* @param {Object} options Data to construct a new ItemMirror with
*
* @param {String} options.groupingItemURI URI to the grouping item. Required
* for all cases.
*
* @param {String} options.itemDriver Data for the ItemDriver to
* construct ItemMirror with. Required for cases 2 & 3
* Can contain any amount of optional key/value pairs for
* the various Driver implementations.
* @param {String} options.itemDriver.driverURI URI of the driver.
*
* @param {String} options.xooMLDriver Data for the XooMLDriver to
* construct ItemMirror with. Required for all cases.
* Can contain any amount of optional key/value pairs for
* the various Driver implementations.
* @param {String} options.xooMLDriver.driverURI URI of the driver.
*
* @param {String} options.syncDriver Data for the SyncDriver to
* construct ItemMirror with. Required Case 2 & 3. Can
* contain any amount of optional key/value pairs for
* the various Driver implementations.
* @param {String} options.syncDriver.driverURI URI of the driver.
*
* @param {Boolean} options.readIfExists True if ItemMirror
* should create an ItemMirror if it does not exist,
* else false. Required for Case 2 & 3.
*
* @param {ItemMirror} options.creator If being created from another
* itemMirror, specifies that itemMirror which it comes from.
*
* @param {Function} callback Function to execute once finished.
* @param {Object} callback.error Null if no error has occurred
* in executing this function, else an contains
* an object with the error that occurred.
* @param {ItemMirror} callback.itemMirror Newly constructed ItemMirror
*/
define('ItemMirror',[
'./XooMLExceptions',
'./XooMLConfig',
'./XooMLUtil',
'./PathDriver',
'./ItemDriver',
'./XooMLDriver',
'./SyncDriver',
'./FragmentEditor',
'./AssociationEditor'
], function(
XooMLExceptions,
XooMLConfig,
XooMLUtil,
PathDriver,
ItemDriver,
XooMLDriver,
SyncDriver,
FragmentEditor,
AssociationEditor) {
"use strict";
var
_CONSTRUCTOR_CASE_1_OPTIONS = {
"groupingItemURI": true,
"xooMLDriver": true,
"parent": false
},
_CONSTRUCTOR_CASE_2_OPTIONS = {
"groupingItemURI": true,
"xooMLDriver": true,
"itemDriver": true,
"syncDriver": true,
"parent": false
},
_UPGRADE_ASSOCIATION_OPTIONS = {
"GUID": true,
"localItemURI": false
};
function ItemMirror(options, callback) {
XooMLUtil.checkCallback(callback);
if (!options) {
return callback(XooMLExceptions.nullArgument);
}
if (!XooMLUtil.isObject(options)) {
return callback(XooMLExceptions.invalidType);
}
var self = this, xooMLFragmentURI, displayName;
// private variables
self._xooMLDriver = null;
self._itemDriver = null;
self._syncDriver = null;
self._creator = options.creator || null;
self._groupingItemURI = PathDriver.formatPath(options.groupingItemURI);
self._newItemMirrorOptions = options;
// displayName for the fragment
if (PathDriver.isRoot(self._groupingItemURI)) {
// This obviously will need to be changed when multiple driver
// support is implemented
displayName = "Dropbox";
} else {
displayName = PathDriver.formatPath(self._groupingItemURI);
displayName = PathDriver.splitPath(displayName);
displayName = displayName[displayName.length - 1];
}
xooMLFragmentURI = PathDriver.joinPath(self._groupingItemURI, XooMLConfig.xooMLFragmentFileName);
options.xooMLDriver.fragmentURI = xooMLFragmentURI;
// First load the XooML Driver
new XooMLDriver(options.xooMLDriver, loadXooMLDriver);
function loadXooMLDriver(error, driver) {
if (error) return callback(error);
self._xooMLDriver = driver; // actually sets the XooMLDriver
self._xooMLDriver.getXooMLFragment(processXooML);
}
function processXooML(error, fragmentString) {
// Case 2: Since the fragment doesn't exist, we need
// to construct it by using the itemDriver
if (error === 404) new ItemDriver(options.itemDriver, createFromItemDriver);
else if (error) return callback(error);
// Case 1: It already exists, and so all of the information
// can be constructed from the saved fragment
else {
createFromXML(fragmentString);
}
}
function createFromXML(fragmentString) {
console.log("Constructing from XML");
self._fragment = new FragmentEditor({text: fragmentString});
// Need to load other stuff from the fragment now
var syncDriverURI = self._fragment.commonData.syncDriver,
itemDriverURI = self._fragment.commonData.itemDriver;
new ItemDriver(options.itemDriver, function(error, driver) {
if (error) return callback(error);
self._itemDriver = driver;
self._syncDriver = new SyncDriver(self);
// Do a refresh in case something has been added or deleted in
// the directory since the last write
self.refresh(function(error) {
return callback(false, self);
});
});
}
function createFromItemDriver(error, driver) {
self._itemDriver = driver;
self._itemDriver.listItems(self._groupingItemURI, buildFragment);
}
function buildFragment(error, associations){
if (error) return callback(error);
self._fragment = new FragmentEditor({
commonData: {
itemDescribed: self._groupingItemURI,
displayName: displayName,
itemDriver: "dropboxItemDriver",
xooMLDriver: "dropboxXooMLDriver",
syncDriver: "itemMirrorSyncUtility"
},
associations: associations
});
self._syncDriver = new SyncDriver(self);
// Because the fragment is being built from scratch, it's safe
// to save it directly via the driver.
self._xooMLDriver.setXooMLFragment(self._fragment.toString(), function(error) {
if (error) console.log(error);
});
return callback(false, self);
}
}
/**
* @method getDisplayName
* @return {String} The display name of the fragment.
*/
ItemMirror.prototype.getDisplayName = function() {
return this._fragment.commonData.displayName;
};
/**
* @method setDisplayName
* @param {String} name The display text to set for the fragment
*/
ItemMirror.prototype.setDisplayName = function(name) {
this._fragment.commonData.displayName = name;
};
/**
*
* @method getSchemaVersion
* @return {String} XooML schema version.
*/
ItemMirror.prototype.getSchemaVersion = function(callback) {
return this._fragment.commonData.schemaVersion;
};
/**
*
* @method getSchemaLocation
* @return {String} XooML schema location.
*/
ItemMirror.prototype.getSchemaLocation = function() {
return this._fragment.commonData.schemaLocation;
};
/**
* Returns URI pointing to item described by the metadata of a fragment. A URI
* might point to just about anything that can be interpreted as a grouping
* item. For example: a conventional file system folder or a “tag as
* supported by any of several applications.
*
* @method getURIforItemDescribed
* @return {String} A URI pointing to item described by the metadata
* of a fragment if it exists, else returns null.
*
*/
ItemMirror.prototype.getURIforItemDescribed = function() {
return this._fragment.commonData.itemDescribed;
};
/**
* Throws NullArgumentException if GUID is null. <br/>
* Throws InvalidTypeException if GUID is not a String. <br/>
* Throws InvalidGUIDException if GUID is not a valid GUID. <br/>
*
*
* @method getAssociationDisplayText
* @return {String} The display text for the association with the given GUID.
*
* @param {String} GUID GUID representing the desired association.
*/
ItemMirror.prototype.getAssociationDisplayText = function(GUID) {
return this._fragment.associations[GUID].commonData.displayText;
};
/**
* Sets the display text for the association with the given GUID.
*
* Throws NullArgumentException if GUID or displayName is null. <br/>
* Throws InvalidTypeException if GUID or displayName is not a String. <br/>
* Throws InvalidGUIDException if GUID is not a valid GUID. <br/>
*
* @method setAssociationDisplayText
*
* @param {String} GUID GUID of the association to set.
* @param {String} displayText Display text to be set.
*/
ItemMirror.prototype.setAssociationDisplayText = function(GUID, displayText) {
this._fragment.associations[GUID].commonData.displayText = displayText;
};
/**
* Throws NullArgumentException if GUID is null. <br/>
* Throws InvalidTypeException if GUID is not a String. <br/>
* Throws InvalidGUIDException if GUID is not a valid GUID. <br/>
*
* @method getAssociationLocalItem
* @return {String} The local item for the association with the given GUID.
*
* @param {String} GUID GUID of the association to get.
*/
ItemMirror.prototype.getAssociationLocalItem = function(GUID) {
return this._fragment.associations[GUID].commonData.localItem;
};
/**
* Throws NullArgumentException if GUID is null. <br/>
* Throws InvalidTypeException if GUID is not a String. <br/>
* Throws InvalidGUIDException if GUID is not a valid GUID. <br/>
*
* @method getAssociationAssociatedItem
* @return {String} The associated item for the association with the given GUID.
* @param {String} GUID GUID of the association to get.
*/
ItemMirror.prototype.getAssociationAssociatedItem = function(GUID) {
return this._fragment.associations[GUID].commonData.associatedItem;
};
/**
* @method getFragmentNamespaceAttribute
* @return {String} Returns the value of the given attributeName for the
* fragmentNamespaceData with the given namespaceURI.
* @param {String} attributeName Name of the attribute to be returned.
* @param {String} uri Namespace URI
*/
ItemMirror.prototype.getFragmentNamespaceAttribute = function(attributeName, uri) {
var ns = this._fragment.namespace;
ns[uri] = ns[uri] || {};
ns[uri].attributes = ns[uri].attributes || {};
return this._fragment.namespace[uri].attributes[attributeName];
};
/**
* Sets the value of the given attributeName with the given attributeValue
* for the fragmentNamespaceData with the given namespaceURI.
*
* Throws NullArgumentException if attributeName, attributeValue, or
* namespaceURI is null. <br/>
* Throws InvalidTypeException if attributeName, attributeValue, or
* namespaceURI is not a String. <br/>
*
* @method setFragmentNamespaceAttribute
* @param {String} attributeName Name of the attribute to be set.
* @param {String} attributeValue Value of the attribute to be set.
* @param {String} uri Namespace URI
*/
ItemMirror.prototype.setFragmentNamespaceAttribute = function(attributeName, attributeValue, uri) {
var ns = this._fragment.namespace;
ns[uri] = ns[uri] || {};
ns[uri].attributes = ns[uri].attributes || {};
this._fragment.namespace[uri].attributes[attributeName] = attributeValue;
};
/**
* Adds the given attributeName to the fragment's current namespace
*
* Throws an InvalidStateException when the attribute already exists
*
* @method addFragmentNamespaceAttribute
*
* @param {String} attributeName Name of the attribute.
* @param {String} uri Namespace URI
*/
// TODO: Possibly remove? Why not just get and set
ItemMirror.prototype.addFragmentNamespaceAttribute = function(attributeName, uri) {
var ns = this._fragment.namespace;
ns[uri] = ns[uri] || {};
ns[uri].attributes = ns[uri].attributes || {};
if (this._fragment.namespace[uri].attributes[attributeName]) {
throw XooMLExceptions.invalidState;
}
this.setFragmentNamespaceAttribute(attributeName, uri);
};
/**
* Removes the fragment namespace attribute with the given namespaceURI.
*
* Throws NullArgumentException if attributeName, or namespaceURI is
* null. <br/>
* Throws InvalidTypeException if attributeName, or namespaceURI is not
* a String. <br/>
* Throws an InvalidStateException when the given attributeName is not an
* attribute. <br/>
*
* @method removeFragmentNamespaceAttribute
* @param {String} attributeName Name of the attribute.
* @param {String} uri Namespace URI
*
*/
ItemMirror.prototype.removeFragmentNamespaceAttribute = function(attributeName, uri) {
delete this._fragment.namespace[uri].attributes[attributeName];
};
/**
* Checks if the fragment has the given namespaceURI.
*
* Currently cannot find a way to list the namespaces (no DOM
* standard method for doing so). So this fuction will ALWAYS RETURN
* FALSE for now.
*
* @method hasFragmentNamespace
* @return {Boolean} True if the fragment has the given
* namespaceURI, otherwise false.
*
* @param {String} uri URI of the namespace for the association.
*
*/
ItemMirror.prototype.hasFragmentNamespace = function (uri) {
var namespace = this._fragment.namespace[uri];
if (namespace) { return true; }
else { return false; }
};
/**
* @method listFragmentNamespaceAttributes
* @return {String[]} An array of the attributes within the
* fragmentNamespaceData with the given namespaceURI.
* @param {String} uri Namespace URI
*
*/
ItemMirror.prototype.listFragmentNamespaceAttributes = function(uri) {
return Object.keys(this._fragment.namespace[uri].attributes);
};
/**
* @method getFragmentNamespaceData
* @return {String} The fragment namespace data with the given namespace URI.
* @param {String} uri Namespace URI
*/
ItemMirror.prototype.getFragmentNamespaceData = function(uri) {
return this._fragment.namespace[uri].data;
};
/**
* Sets the fragment namespace data with the given namespaceURI.
*
* @method setFragmentNamespaceData
*
* @param {String} data Fragment namespace data to be set.
* @param {String} uri Namespace URI
*/
ItemMirror.prototype.setFragmentNamespaceData = function (data, uri) {
var ns = this._fragment.namespace;
ns[uri] = ns[uri] || {};
this._fragment.namespace[uri].data = data;
};
/**
* Creates an ItemMirror from the associated grouping item represented by
* the given GUID.
*
* Throws NullArgumentException if GUID or callback is null. <br/>
* Throws InvalidTypeException if GUID is not a string, and callback is
* not a function. <br/>
* Throws InvalidGUIDException if GUID is not a valid GUID. <br/>
*
* @method createItemMirrorForAssociatedGroupingItem
* @return {ItemMirror} Possibly return an itemMirror if the GUID is a grouping item
*
* @param {String} GUID GUID of the association to create the ItemMirror
* from.
*
*/
ItemMirror.prototype.createItemMirrorForAssociatedGroupingItem = function (GUID, callback) {
var self = this,
isGrouping,
xooMLOptions,
itemOptions,
syncOptions,
uri;
// Need to change this so that it instead points to the fragmentURI field
uri = PathDriver.joinPath(self.getAssociationAssociatedItem(GUID), "XooML2.xml");
itemOptions = {
driverURI: "DropboxItemUtility",
dropboxClient: self._xooMLDriver._dropboxClient
};
xooMLOptions = {
fragmentURI: uri,
driverURI: "DropboxXooMLUtility",
dropboxClient: self._xooMLDriver._dropboxClient
};
syncOptions = {
utilityURI: "MirrorSyncUtility"
};
isGrouping = self.isAssociationAssociatedItemGrouping(GUID);
if (!isGrouping) {
// Need to standardize this error
return callback("Association not grouping, cannot continue");
}
new ItemMirror(
{groupingItemURI: self.getAssociationAssociatedItem(GUID),
xooMLDriver: xooMLOptions,
itemDriver: itemOptions,
syncDriver: syncOptions,
creator: self
},
function (error, itemMirror) {
console.log(error);
return callback(error, itemMirror);
}
);
};
/**
* Creates an association based on the given options and the following
* cases.
*
* Cases 1, 2, 7 implemented. All else are not implemented.
*
* 1. Simple text association declared phantom. <br/>
* 2. Link to existing non-grouping item, phantom. This can be a URL <br/>
* 3. Link to existing non-grouping item, real. <br/>
* 4. Link to existing grouping item, phantom. <br/>
* 5. Link to existing grouping item, real. <br/>
* 6. Create new local non-grouping item. <br/>
* 7. Create new local grouping item. <br/>
*
* Throws NullArgumentException when options, or callback is null. <br/>
* Throws InvalidTypeException when options is not an object and callback
* is not a function. <br/>
* Throws MissingParameterException when an argument is missing for an expected
* case. <br/>
*
* @method createAssociation
*
* @param {Object} options Data to create an new association for.
*
* @param {String} options.displayText Display text for the association.
* Required in all cases.
*
* @param {String} options.itemURI URI of the item. Required for case 2 & 3. Note: Please ensure "http://" prefix exists at the beginning of the string when referencing a Web URL and not an Item.
*
* @param {Boolean} options.localItemRequested True if the local item is
* requested, else false. Required for cases 2 & 3.
*
* @param {String} options.groupingItemURI URI of the grouping item.
* Required for cases 4 & 5.
*
* @param {String} options.xooMLDriverURI URI of the XooML driver for the
* association. Required for cases 4 & 5.
*
* @param {String} options.localItem URI of the new local
* non-grouping/grouping item. Required for cases 6 & 7.
*
* @param {String} options.isGroupingItem True if the item is a grouping
* item, else false. Required for cases 6 & 7.
*
* @param {Function} callback Function to execute once finished.
* @param {Object} callback.error Null if no error has occurred
* in executing this function, else an contains
* an object with the error that occurred.
* @param {String} callback.GUID GUID of the association created.
*/
ItemMirror.prototype.createAssociation = function (options, callback) {
var self = this,
association,
path,
saveOutFragment;
saveOutFragment = function(association){
var guid = association.commonData.ID;
// adds the association to the fragment
self._fragment.associations[guid] = association;
// Save changes out the actual XooML Fragment
self.save( function(error){
return callback(error, guid);
});
};
if (!XooMLUtil.isFunction(callback)) {
throw XooMLExceptions.invalidType;
}
if (!XooMLUtil.isObject(options)) {
return callback(XooMLExceptions.invalidType);
}
// Case 7
if (options.displayText && options.localItem && options.isGroupingItem) {
association = new AssociationEditor({
commonData: {
displayText: options.displayText,
isGrouping: true,
localItem: options.localItem,
associatedItem: PathDriver.joinPath(self.getURIforItemDescribed(), options.localItem)
}
});
// Now we use the itemDriver to actually create the folder
path = PathDriver.joinPath(self._groupingItemURI, association.commonData.localItem);
self._itemDriver.createGroupingItem(path, function(error){
if (error) return callback(error);
return saveOutFragment(association);
});
}
// Synchronous cases
else {
// Case 2
if (options.displayText && options.itemURI) {
association = new AssociationEditor({
commonData: {
displayText: options.displayText,
associatedItem: options.itemURI,
isGrouping: false
}
});
}
// Case 1
else if (options.displayText) {
association = new AssociationEditor({
commonData: {
displayText: options.displayText,
isGrouping: false
}
});
}
return saveOutFragment(association);
}
};
/**
* @method isAssociationPhantom
* @param {String} guid
* @return {Boolean} True if the association of the given GUID is a
* phantom association. False otherwise.
*/
ItemMirror.prototype.isAssociationPhantom = function(guid) {
var data = this._fragment.associations[guid].commonData;
return !(data.isGrouping || data.localItem);
};
/**
* Duplicates (copies) an association to another ItemMirror Object (representing a grouping item)
*
*
* Throws NullArgumentException if GUID is null. <br/>
* Throws InvalidTypeException if GUID is not a String. <br/>
* Throws InvalidGUIDException if GUID is not a valid GUID. <br/>
*
* @method copyAssociation
*
* @param {String} GUID GUID of the association you wish to copy/duplicate
* @param {ItemMirror} ItemMirror ItemMirror representing the grouping item you want to move the GUID object to
*
* @param {Function} callback Function to execute once finished.
* @param {Object} callback.error Null if no error Null if no error has occurred
* in executing this function, else it contains
* an object with the error that occurred.
*/
ItemMirror.prototype.copyAssociation = function (GUID, ItemMirror, callback) {
var self = this;
XooMLUtil.checkCallback(callback);
if (!GUID) {
return callback(XooMLExceptions.nullArgument);
}
if (!XooMLUtil.isGUID(GUID)) {
return callback(XooMLExceptions.invalidType);
}
self.getAssociationLocalItem(GUID, function (error, localItem) {
if (error) {
return callback(error);
}
//phantom case
if (!localItem) {
var options = {};
//getDisplayText and Create new Simple DisplayText Assoc in DestItemMirror
self.getAssociationDisplayText(GUID, function(error, displayText){
if (error) {
return callback(error);
}
options.displayText = displayText;
//check for case 2, phantom NonGrouping Item with ItemURI a.k.a associatedItem
self.getAssociationAssociatedItem(GUID, function(error, associatedItem){
if (error) {
return callback(error);
}
options.itemURI = associatedItem;
});
});
//create a new phantom association in destItemMirror
ItemMirror.createAssociation(options, function(error, GUID) {
if(error) {
return callback(error);
}
});
return ItemMirror._save(callback);
}
self._handleDataWrapperCopyAssociation(GUID, localItem, ItemMirror, error, callback);
});
};
/**
* Moves an association to another ItemMirror Object (representing a grouping item)
*
*
* Throws NullArgumentException if GUID is null. <br/>
* Throws InvalidTypeException if GUID is not a String. <br/>
* Throws InvalidGUIDException if GUID is not a valid GUID. <br/>
*
* @method moveAssociation
*
* @param {String} GUID GUID of the item you want to paste or move
* @param {ItemMirror} ItemMirror ItemMirror representing the grouping item you want to move the GUID object to
*
* @param {Function} callback Function to execute once finished.
* @param {Object} callback.error Null if no error Null if no error has occurred
* in executing this function, else it contains
* an object with the error that occurred.
*/
ItemMirror.prototype.moveAssociation = function (GUID, ItemMirror, callback) {
var self = this;
XooMLUtil.checkCallback(callback);
if (!GUID) {
return callback(XooMLExceptions.nullArgument);
}
if (!XooMLUtil.isGUID(GUID)) {
return callback(XooMLExceptions.invalidType);
}
self.getAssociationLocalItem(GUID, function (error, localItem) {
if (error) {
return callback(error);
}
//phantom case
if (!localItem) {
var options = {};
//getDisplayText and Create new Simple DisplayText Assoc in DestItemMirror
self.getAssociationDisplayText(GUID, function(error, displayText){
if (error) {
return callback(error);
}
options.displayText = displayText;
//check for case 2, phantom NonGrouping Item with ItemURI a.k.a associatedItem
self.getAssociationAssociatedItem(GUID, function(error, associatedItem){
if (error) {
return callback(error);
}
options.itemURI = associatedItem;
});
});
//create a new phantom association in destItemMirror
ItemMirror.createAssociation(options, function(error, newGUID) {
if(error) {
return callback(error);
}
//delete the current phantom association
self._fragmentEditor.deleteAssociation(GUID, function (error) {
if(error) {
return callback(error);
}
return self._save(callback);
});
return ItemMirror._save(callback);
});
}
self._handleDataWrapperMoveAssociation(GUID, localItem, ItemMirror, error, callback);
});
};
/**
* Deletes the association represented by the given GUID.
*
* Throws NullArgumentException if GUID is null. <br/>
* Throws InvalidTypeException if GUID is not a String. <br/>
* Throws InvalidGUIDException if GUID is not a valid GUID. <br/>
*
* @method deleteAssociation
*
* @param GUID {String} GUID of the association to be deleted.
*
* @param {Function} callback Function to execute once finished.
* @param {Object} callback.error Null if no error has occurred
* in executing this function, else an contains
* an object with the error that occurred.
*/
ItemMirror.prototype.deleteAssociation = function (GUID, callback) {
var self = this;
XooMLUtil.checkCallback(callback);
if (!GUID) {
return callback(XooMLExceptions.nullArgument);
}
if (!XooMLUtil.isGUID(GUID)) {
return callback(XooMLExceptions.invalidType);
}
// Save to ensure that the fragment is up to date
self.save(deleteContent);
function deleteContent(error) {
if (error) return callback(error);
var isPhantom = self.isAssociationPhantom(GUID);
if (!isPhantom) {
var isGrouping = self.isAssociationAssociatedItemGrouping(GUID),
localItem = self.getAssociationLocalItem(GUID),
path = PathDriver.joinPath(self._groupingItemURI, localItem);
delete self._fragment.associations[GUID];
if (isGrouping) {
self._itemDriver.deleteGroupingItem(path, postDelete);
} else {
self._itemDriver.deleteNonGroupingItem(path, postDelete);
}
} else {
delete self._fragment.associations[GUID];
return callback(false);
}
}
// Now do a refresh since actual files were removed.
function postDelete(error) {
if (error) return callback(error);
self.refresh(function() {
if (error) return callback(error);
return callback(error);
});
}
};
/**
* Upgrades a given association without a local item. Local item is named
* by a truncated form of the display name of this ItemMirror if the
* localItemURI is not given, else uses given localItemURI. Always
* truncated to 50 characters.
*
* ONLY SUPPORTS SIMPLE PHANTOM ASSOCIATION TO ASSOCIATION WITH GROUPING ITEM
*
* Throws NullArgumentException when options is null. <br/>
* Throws MissingParameterException when options is not null and a required
* argument is missing.<br/>
* Throws InvalidTypeException if GUID is not a string, and if callback
* is not a function. <br/>
* Throws InvalidState if the association with the given GUID cannot be
* upgraded. <br/>
*
* @method upgradeAssociation
*
* @param {Object} options Data to construct a new ItemMirror with
*
* @param {String} options.GUID of the association to be upgraded. Required
*
* @param {String} options.localItemURI URI of the local item to be used if
* a truncated display name is not the intended behavior.
* Optional.
*
* @param {Function} callback Function to execute once finished.
*
* @param {String} callback.error Null if no error has occurred
* in executing this function, else an contains
* an object with the error that occurred.
*/
ItemMirror.prototype.upgradeAssociation = function (options, callback) {
var self = this, localItemURI;
XooMLUtil.checkCallback(callback);
if (!XooMLUtil.hasOptions(_UPGRADE_ASSOCIATION_OPTIONS, options)) {
return callback(XooMLExceptions.missingParameter);
}
if ((options.hasOwnProperty("localItemURI") &&
!XooMLUtil.isString(options.localItemURI)) ||
!XooMLUtil.isGUID(options.GUID)) {
return callback(XooMLExceptions.invalidType);
}
if (options.hasOwnProperty("localItemURI")) {
self._setSubGroupingItemURIFromDisplayText(options.GUID, options.localItemURI, callback);
} else {
self.getAssociationDisplayText(options.GUID, function (error, displayText) {
if (error) {
return callback(error);
}
self._setSubGroupingItemURIFromDisplayText(options.GUID, displayText, callback);
});
}
};
/**
* Renames the local item for the association with the given GUID.
*
* Throws NullArgumentException if GUID, callback is null. <br/>
* Throws InvalidTypeException if GUID is not a String, and if callback
* is not a function. <br/>
*
* @method renameAssocaitionLocalItem
*
* @param {String} GUID GUID of the association.
* @param {String} String String Name you want to rename the file to (including file extension)
* @param {Function} callback Function to execute once finished.
* @param {Object} callback.error Null if no error has occurred
* in executing this function, else an contains
* an object with the error that occurred.
* @param {String} callback.GUID The GUID of the association that was updated.
*/
ItemMirror.prototype.renameAssociationLocalItem = function (GUID, newName, callback) {
var self = this;
XooMLUtil.checkCallback(callback);
if (!GUID) {
return callback(XooMLExceptions.nullArgument);
}
if (!XooMLUtil.isGUID(GUID)) {
return callback(XooMLExceptions.invalidType);
}
self.save(postSave);
function postSave(error) {
if (error) return callback(error);
var localItem = self.getAssociationLocalItem(GUID),
oldPath = PathDriver.joinPath(self._groupingItemURI, localItem),
newPath = PathDriver.joinPath(self._groupingItemURI, newName);
self._itemDriver.moveItem(oldPath, newPath, postMove);
}
function postMove(error) {
self._fragment.associations[GUID].commonData.localItem = newName;
self._unsafeWrite(postWrite);
}
function postWrite(error) {
if (error) return callback(error);
self.refresh(postRefresh);
}
function postRefresh(error) {
return callback(error, self._fragment.associations[GUID].commonData.ID);
}
};
/**
* A special method that is used for certain file operations where
* calling a sync won't work. Essentially it is the save function,
* sans syncing. This should __never__ be called be an application.
* @method _unsafeWrite
* @param callback
* @param calback.error
*/
ItemMirror.prototype._unsafeWrite = function(callback) {
var self = this;
self._xooMLDriver.getXooMLFragment(afterXooML);
function afterXooML(error, content){
if (error) return callback(error);
var tmpFragment = new FragmentEditor({text: content});
self._fragment.updateID();
return self._xooMLDriver.setXooMLFragment(self._fragment.toString(), function(error) {
if (error) return callback(error);
return callback(false);
});
}
};
/**
* Checks if an association's associatedItem is a grouping item
*
* Throws NullArgumentException if GUID, callback is null. <br/>
* Throws InvalidTypeException if GUID is not a String, and if callback
* is not an function. <br/>
*
* @method isAssociationAssociatedItemGrouping
* @return {Boolean} True if the association with the given GUID's associatedItem is a grouping
* item, otherwise false.
*
* @param GUID {String} GUID of the association to be to be checked.
*
*/
ItemMirror.prototype.isAssociationAssociatedItemGrouping = function(GUID) {
return this._fragment.associations[GUID].commonData.isGrouping;
};
/**
* Lists the GUIDs of each association.
*
* @method listAssociations
*
* @return {String[]} Array of the GUIDs of each association
*/
ItemMirror.prototype.listAssociations = function() {
return Object.keys(this._fragment.associations);
};
/**
*
* Throws NullArgumentException if attributeName, GUID, or namespaceURI is
* null. <br/>
* Throws InvalidTypeException if attributeName, GUID, or namespaceURI is not
* a String. <br/>
* Throws InvalidGUIDException if GUID is not a valid GUID. <br/>
*
* @method getAssociationNamespaceAttribute
* @return {String} The association namespace attribute with
* the given attributeName and the given namespaceURI within the
* association with the given GUID.
*
* @param {String} attributeName Name of the attribute to be returned.
* @param {String} GUID GUID of the association to return attribute from.
* @param {String} uri Namspace URI
*
*/
ItemMirror.prototype.getAssociationNamespaceAttribute = function(attributeName, GUID, uri) {
var ns = this._fragment.associations[GUID].namespace;
ns[uri] = ns[uri] || {};
ns[uri].attributes = ns[uri].attributes || {};
return this._fragment.associations[GUID].namespace[uri].attributes[attributeName];
};
/**
* Sets the association namespace attribute with the given attributeName
* and the given namespaceURI within the association with the given GUID.
*
* Throws NullArgumentException if attributeName, attributeValue, GUID, or
* namespaceURI is null. <br/>
* Throws InvalidTypeException if attributeName, attributeValue, GUID, or
* namespaceURI is not a String. <br/>
* Throws InvalidGUIDException if GUID is not a valid GUID. <br/>
*
* @method setAssociationNamespaceAttribute
*
* @param {String} attributeName Name of the attribute to be set.
* @param {String} attributeValue Value of the attribute to be set
* @param {String} GUID GUID of association to set attribute for.
* @param {String} uri Namespace URI
*
*/
ItemMirror.prototype.setAssociationNamespaceAttribute = function(attributeName, attributeValue, GUID, uri) {
var ns = this._fragment.associations[GUID].namespace;
ns[uri] = ns[uri] || {};
ns[uri].attributes = ns[uri].attributes || {};
this._fragment.associations[GUID].namespace[uri].attributes[attributeName] = attributeValue;
};
/**
* Adds the given attributeName to the association with the given GUID and
* namespaceURI.
*
* Throws NullArgumentException if attributeName, GUID, or namespaceURI is
* null. <br/>
* Throws InvalidTypeException if attributeName, GUID, or namespaceURI is not
* a String. <br/>
* Throws InvalidGUIDException if GUID is not a valid GUID. <br/>
* Throws an InvalidStateException when the given attributeName has already
* been added. <br/>
*
* @method addAssociationNamespaceAttribute
*
* @param {String} attributeName Name of the attribute.
* @param {String} attributeValue Value of the attribe to be set
* @param {String} GUID GUID of the association.
* @param {String} uri Namespace URI
*/
ItemMirror.prototype.addAssociationNamespaceAttribute = function(attributeName, attributeValue, GUID, uri) {
var ns = this._fragment.associations[GUID].namespace;
ns[uri] = ns[uri] || {};
ns[uri].attributes = ns[uri].attributes || {};
if (this._fragment.associations[GUID].namespace[uri].attributes[attributeName]) {
throw XooMLExceptions.invalidState;
}
this.setAssociationNamespaceAttribute(attributeName, attributeValue, GUID, uri);
};
/**
* Removes the given attributeName to the association with the given GUID and
* namespaceURI.
*
* Throws NullArgumentException if attributeName, GUID, or namespaceURI is
* null. <br/>
* Throws InvalidTypeException if attributeName, GUID, or namespaceURI is not
* a String. <br/>
* Throws InvalidGUIDException if GUID is not a valid GUID. <br/>
* Throws an InvalidStateException when the given attributeName is not an
* attribute. <br/>
*
* @method removeAssociationNamespaceAttribute
*
* @param {String} attributeName Name of the attribute.
* @param {String} GUID GUID of the association.
* @param {String} uri Namespace URI
*/
ItemMirror.prototype.removeAssociationNamespaceAttribute = function(attributeName, GUID, uri) {
delete this._fragment.associations[GUID].namespace[uri].attributes[attributeName];
};
/**
* @method hasAssociationNamespace
* @return {Boolean} True if the association has the given
* namespaceURI, else false.
*
* @param {String} GUID GUID of the association.
* @param {String} uri Namespace URI
*
*/
ItemMirror.prototype.hasAssociationNamespace = function(GUID, uri) {
var namespace = this._fragment.associations[GUID].namespace[uri];
if (namespace) { return true; }
else { return false; }
};
/**
*
* Throws NullArgumentException if GUID, namespaceURI is null. <br/>
* Throws InvalidTypeException if GUID, namespaceURI is not a String. <br/>
* Throws InvalidGUIDException if GUID is not a valid GUID. <br/>
*
* @method listAssociationNamespaceAttributes
* @return {String[]} An array of the association namespace
* attributes with the given attributeName and the given
* namespaceURI within the association with the given GUID.
*
* @param {String} GUID GUID of association to list attributes for.
* @param {String} uri Namespace URI
*/
ItemMirror.prototype.listAssociationNamespaceAttributes = function (GUID, uri) {
var ns = this._fragment.associations[GUID].namespace;
ns[uri] = ns[uri] || {};
ns[uri].attributes = ns[uri].attributes || {};
return Object.keys(this._fragment.associations[GUID].namespace[uri].attributes);
};
/**
* Throws InvalidGUIDException if GUID is not a valid GUID. <br/>
*
* @method getAssociationNamespaceData
* @return {String} The association namespace data for an
* association with the given GUID and the given namespaceURI.
*
* @param {String} GUID GUID of the association namespace data to
* returned.
* @param {String} uri Namespace URI
*/
self.getAssociationNamespaceData = function (GUID, uri) {
var ns = this._fragment.associations[GUID].namespace;
ns[uri] = ns[uri] || {};
ns[uri].attributes = ns[uri].attributes || {};
return this._fragment.associations[GUID].namespace[uri].data;
};
/**
* Sets the association namespace data for an association with the given GUID
* and given namespaceURI using the given data.
*
* Throws NullArgumentException if data, GUID, or namespaceURI is null. <br/>
* Throws InvalidTypeException if data, GUID, or namespaceURI is not a
* String. <br/>
* Throws InvalidGUIDException if GUID is not a valid GUID. <br/>
*
* @method setAssociationNamespaceData
*
* @param {String} data Association namespace data to set. Must be
* valid fragmentNamespaceData.
* @param {String} GUID GUID of the association namespace data to set.
*/
ItemMirror.prototype.setAssociationNamespaceData = function (data, GUID, uri) {
var ns = this._fragment.associations[GUID].namespace;
ns[uri] = ns[uri] || {};
ns[uri].attributes = ns[uri].attributes || {};
this._fragment.associations[GUID].namespace[uri].data = data;
};
/**
* Uses the specified ItemDriver and SyncDriver to synchronize the
* local ItemMirror object changes. This is an implmentation of Synchronization
* Driver which modifies the XooML Fragment according to the real structure
* under the item described.
*
* @method sync
*
* @param {Function} callback Function to execute once finished.
* @param {Object} callback.error Null if no error has occurred
* in executing this function, else an contains
* an object with the error that occurred.
* @private
*/
ItemMirror.prototype._sync = function (callback) {
var self = this;
self._syncDriver.sync(callback);
};
/**
* Reloads the XooML Fragment
*
* @method refresh
*
* @param {Function} callback Function to execute once finished.
* @param {Object} callback.error Null if no error has occurred
* in executing this function, else an contains
* an object with the error that occurred.
*/
ItemMirror.prototype.refresh = function(callback) {
var self = this;
self._sync( function(error) {
// This error means that sync changed the fragment
// We then will reload the fragment based on the new XooML
if (error === XooMLExceptions.itemMirrorNotCurrent) {
self._xooMLDriver.getXooMLFragment(resetFragment);
} else if (error) {
callback(error);
} else {
self._xooMLDriver.getXooMLFragment(resetFragment);
}
});
function resetFragment(error, content){
if (error) return callback(error);
self._fragment = new FragmentEditor({text: content});
return callback(false);
}
};
/**
* @method getCreator
*
* @return {Object} The itemMirror that created this current
* itemMirror, if it has one. Note that this isn't the same as
* asking for a 'parent,' since multiple itemMirrors can possibly
* link to the same one
*
*/
ItemMirror.prototype.getCreator = function () {
return this._creator;
};
/**
* Saves the itemMirror object, writing it out to the
* fragment. Fails if the GUID generated on last write for the
* itemMirror and the XooML fragment don't match.
*
* @method save
*
* @param callback
* @param callback.error Returns false if everything went ok,
* otherwise returns the error
*/
ItemMirror.prototype.save = function(callback) {
var self = this;
self._sync(postSync);
function postSync(error) {
if (error) return callback(error);
return self._unsafeWrite(postWrite);
}
function postWrite(error) {
return callback(error);
}
};
/**
* Checks if the AssociatedItem String passed into it is a URL or not.
*
* @method _isURL
* @return {Boolean} True if it is an HTTP URL, false otherwise
* (HTTPS will fail)
* @private
* @param {String} URL
*/
self._isURL = function (URL){
return /^http:\/\//.exec(URL);
};
return ItemMirror;
});
return require('ItemMirror');
})); | sun-teng/bcmderFireMirrorHTML | app/bower_components/item-mirror/item-mirror.js | JavaScript | mit | 117,919 |
module.exports = {
target: 'http://localhost:8000',
apiTarget: 'http://localhost:8000/v1',
apiPath: '/v1',
storageKey: 'user_session',
session: {
tokenKey: 'authentication_token',
emailKey: 'email'
}
};
| dmitrymikheev/tests | config/env/test.js | JavaScript | mit | 223 |
(function(d,f,e){var g,h;h=function(){var c,a,b;a=e.createElement("div");a.style.position="absolute";a.style.width="100px";a.style.height="100px";a.style.overflow="scroll";e.body.appendChild(a);c=a.offsetWidth;b=a.scrollWidth;e.body.removeChild(a);return c-b};g=function(){function c(a){this.el=a;this.generate();this.createEvents();this.addEvents();this.reset()}c.prototype.createEvents=function(){var a=this;this.events={down:function(b){a.isDrag=!0;a.offsetY=b.clientY-a.slider.offset().top;a.pane.addClass("active");
d(e).bind("mousemove",a.events.drag);d(e).bind("mouseup",a.events.up);return!1},drag:function(b){a.sliderY=b.clientY-a.el.offset().top-a.offsetY;a.scroll();return!1},up:function(){a.isDrag=!1;a.pane.removeClass("active");d(e).unbind("mousemove",a.events.drag);d(e).unbind("mouseup",a.events.up);return!1},resize:function(){a.reset()},panedown:function(b){a.sliderY=b.clientY-a.el.offset().top-0.5*a.sliderH;a.scroll();a.events.down(b)},scroll:function(){var b;b=a.content[0];!0!==a.isDrag&&a.slider.css({top:b.scrollTop/
(b.scrollHeight-b.clientHeight)*(a.paneH-a.sliderH)+"px"})},wheel:function(b){a.sliderY+=-b.wheelDeltaY||-b.delta;a.scroll();return!1}}};c.prototype.addEvents=function(){var a,b;a=this.events;b=this.pane;d(f).bind("resize",a.resize);this.slider.bind("mousedown",a.down);b.bind("mousedown",a.panedown);this.content.bind("scroll",a.scroll);f.addEventListener&&(b=b[0],b.addEventListener("mousewheel",a.wheel,!1),b.addEventListener("DOMMouseScroll",a.wheel,!1))};c.prototype.removeEvents=function(){var a,
b;a=this.events;b=this.pane;d(f).unbind("resize",a.resize);this.slider.unbind("mousedown",a.down);b.unbind("mousedown",a.panedown);this.content.unbind("scroll",a.scroll);f.addEventListener&&(b=b[0],b.removeEventListener("mousewheel",a.wheel,!1),b.removeEventListener("DOMMouseScroll",a.wheel,!1))};c.prototype.generate=function(){this.el.append('<div class="pane"><div class="slider"></div></div>');this.content=d(this.el.children()[0]);this.slider=this.el.find(".slider");this.pane=this.el.find(".pane");
this.scrollW=h();if(0===this.scrollbarWidth)this.scrollW=0;this.content.css({right:-this.scrollW+"px"})};c.prototype.reset=function(){if(!0===this.isDead)this.isDead=!1,this.pane.show(),this.addEvents();this.contentH=this.content[0].scrollHeight+this.scrollW;this.paneH=this.pane.outerHeight();this.sliderH=this.paneH/this.contentH*this.paneH;this.sliderH=Math.round(this.sliderH);this.scrollH=this.paneH-this.sliderH;this.slider.height(this.sliderH);this.paneH>=this.content[0].scrollHeight?this.pane.hide():
this.pane.show()};c.prototype.scroll=function(){var a;this.sliderY=Math.max(0,this.sliderY);this.sliderY=Math.min(this.scrollH,this.sliderY);a=this.paneH-this.contentH+this.scrollW;a=a*this.sliderY/this.scrollH;this.content.scrollTop(-a);return this.slider.css({top:this.sliderY})};c.prototype.scrollBottom=function(a){this.reset();this.content.scrollTop(this.contentH-this.content.height()-a)};c.prototype.scrollTop=function(a){this.reset();this.content.scrollTop(a+0)};c.prototype.stop=function(){this.isDead=
!0;this.removeEvents();this.pane.hide()};return c}();d.fn.nanoScroller=function(c){var a;c||(c={});if(!(d.browser.msie&&8>parseInt(d.browser.version,10))){a=this.data("scrollbar");void 0===a&&(a=new g(this),this.data("scrollbar",a));if(c.scrollBottom)return a.scrollBottom(c.scrollBottom);if(c.scrollTop)return a.scrollTop(c.scrollTop);if("bottom"===c.scroll)return a.scrollBottom(0);if("top"===c.scroll)return a.scrollTop(0);if(c.stop)return a.stop();a.reset()}}})(jQuery,window,document); | adamayres/stackfiddle | js/libs/jquery.nanoscroller.min.js | JavaScript | mit | 3,563 |
'use strict';
var util = require('../lib/util');
var assert = require('assert');
var getPromise = require('./testutil').getPromise;
var pointer = require('json-pointer');
describe('util', function() {
describe('objectToPromise', function() {
var objectToPromise = util.objectToPromise;
it('should return promise if there are no promises', function() {
var obj = { a: 1, b: 2 };
var result = objectToPromise(obj);
return result.then(function (res) {
assert.deepEqual(res, obj);
});
});
it('should return promise resolving to object without promises (if object has one promise)', function() {
var obj = {
a: 1,
b: Promise.resolve(2),
c: 3
};
var result = objectToPromise(obj);
return result.then(function (res) {
assert.deepEqual(res, { a: 1, b: 2, c: 3 });
});
});
it('should return promise resolving to object without promises (if object has many promises)', function() {
var obj = {
a: 1,
b: Promise.resolve(2),
c: Promise.resolve(3)
};
var result = objectToPromise(obj);
return result.then(function (res) {
assert.deepEqual(res, { a: 1, b: 2, c: 3 });
});
});
});
describe('promiseMapSerial', function() {
var promiseMapSerial = util.promiseMapSerial;
var callsResolutions;
beforeEach(function() {
callsResolutions = getPromise.callsResolutions = [];
});
describe('map function is synchronous', function() {
function syncMapper(data) {
callsResolutions.push({ call: data });
return data * 10;
}
it('should map array without promises synchronously', function() {
var arr = [1, 2, 3];
return promiseMapSerial(arr, syncMapper)
.then(function (result) {
assert.deepEqual(result, [10, 20, 30]);
assert.deepEqual(callsResolutions, [{ call: 1 }, { call: 2 }, { call: 3 }]);
});
});
it('should return promise resolving to array without promises (if array has one promise)', function() {
var arr = [
1,
getPromise(2),
3
];
var result = promiseMapSerial(arr, syncMapper);
return result.then(function (res) {
assert.deepEqual(res, [10, 20, 30]);
assert.deepEqual(callsResolutions, [
{ call: 1 },
{ res: 2 },
{ call: 2 },
{ call: 3 }
]);
});
});
it('should return promise resolving to array without promises (if array has many promises resolving in oorder)', function() {
var arr = [
1,
getPromise(2, 20),
getPromise(3, 40)
];
var result = promiseMapSerial(arr, syncMapper);
return result.then(function (res) {
assert.deepEqual(res, [10, 20, 30]);
assert.deepEqual(callsResolutions, [
{ call: 1 },
{ res: 2 },
{ call: 2},
{ res: 3 },
{ call: 3 }
]);
});
});
it('should return promise resolving to array without promises (if array has many promises NOT resolving in order)', function() {
var arr = [
1,
getPromise(2, 40),
getPromise(3, 20)
];
var result = promiseMapSerial(arr, syncMapper);
return result.then(function (res) {
assert.deepEqual(res, [10, 20, 30]);
assert.deepEqual(callsResolutions, [
{ call: 1 },
{ res: 3 },
{ res: 2 },
{ call: 2},
{ call: 3 }
]);
});
});
it('should return promise resolving to array without promises (if array has many promises NOT resolving in order)', function() {
var arr = [
getPromise(1),
getPromise(2),
getPromise(3)
];
var result = promiseMapSerial(arr, syncMapper);
return result.then(function (res) {
assert.deepEqual(res, [10, 20, 30]);
// assert.deepEqual(callsResolutions, [
// { call: 1 },
// { res: 3 },
// { res: 2 },
// { call: 2},
// { call: 3 }
// ]);
});
});
});
describe('map function returns promise', function() {
function asyncMapper(data) {
callsResolutions.push({ call: data });
return getPromise(data * 10);
}
it('should map array without promises sequentially (waiting for previous result)', function() {
var arr = [1, 2, 3];
var result = promiseMapSerial(arr, asyncMapper);
return result.then(function (res) {
assert.deepEqual(res, [10, 20, 30]);
assert.deepEqual(callsResolutions, [
{ call: 1 },
{ res: 10 },
{ call: 2 },
{ res: 20 },
{ call: 3 },
{ res: 30 }
]);
});
});
it('should return promise resolving to array without promises (if array has one promise)', function() {
var arr = [
1,
getPromise(2),
3
];
var result = promiseMapSerial(arr, asyncMapper);
return result.then(function (res) {
assert.deepEqual(res, [10, 20, 30]);
assert.deepEqual(callsResolutions, [
{ call: 1 },
{ res: 2 },
{ res: 10 },
{ call: 2 },
{ res: 20 },
{ call: 3 },
{ res: 30 }
]);
});
});
it('should return promise resolving to array without promises (if array has one promise)', function() {
var arr = [
1,
getPromise(2, 10),
getPromise(3, 20)
];
var result = promiseMapSerial(arr, asyncMapper);
return result.then(function (res) {
assert.deepEqual(res, [10, 20, 30]);
assert.deepEqual(callsResolutions, [
{ call: 1 },
{ res: 10 },
{ res: 2 },
{ call: 2 },
{ res: 20 },
{ res: 3 },
{ call: 3 },
{ res: 30 }
]);
});
});
});
describe('map function can return promise or value', function() {
function mapper(data) {
callsResolutions.push({ call: data });
if (data <= 2) return getPromise(data * 10, 20);
if (data <= 4) return data * 10;
if (data % 2) return getPromise(data * 10, 10);
return data * 10;
}
it('should call mapper in order regardless of what it returns when array has no promises', function() {
var arr = [ 1, 2, 3, 4, 5, 6, 7 ];
var result = promiseMapSerial(arr, mapper);
return result.then(function (res) {
assert.deepEqual(res, [10, 20, 30, 40, 50, 60, 70]);
assert.deepEqual(callsResolutions, [
{ call: 1 },
{ res: 10 },
{ call: 2 },
{ res: 20 },
{ call: 3 },
{ call: 4 },
{ call: 5 },
{ res: 50 },
{ call: 6 },
{ call: 7 },
{ res: 70 }
]);
});
});
it('should call mapper in order when array has promises', function() {
var arr = [
1,
getPromise(2, 30),
3,
getPromise(4, 50),
5,
getPromise(6, 70),
getPromise(7, 90)
];
var result = promiseMapSerial(arr, mapper);
return result.then(function (res) {
assert.deepEqual(res, [10, 20, 30, 40, 50, 60, 70]);
assert.deepEqual(callsResolutions, [
{ call: 1 },
{ res: 10 },
{ res: 2 },
{ call: 2 },
{ res: 4 },
{ res: 20 },
{ call: 3 },
{ call: 4 },
{ call: 5 },
{ res: 50 },
{ res: 6 },
{ call: 6 },
{ res: 7 },
{ call: 7 },
{ res: 70 }
]);
});
});
});
});
describe('toAbsolutePointer', function() {
var base = pointer.parse('/foo/bar');
it('should return property/index for N# pointer', function() {
var absPntr = util.toAbsolutePointer('0#', base);
assert.equal(absPntr, 'bar');
var absPntr = util.toAbsolutePointer('1#', base);
assert.equal(absPntr, 'foo');
});
it('should throw if N# points outside of the object', function() {
assert.throws(function() {
util.toAbsolutePointer('2#', base);
}, /Cannot access property\/index 2 levels up, current level is 2/);
assert.throws(function() {
util.toAbsolutePointer('3#', base);
}, /Cannot access property\/index 3 levels up, current level is 2/);
});
it('should return absolute parsed pointer', function() {
var absPntr = util.toAbsolutePointer('1/baz', base);
assert.deepEqual(absPntr, ['foo','baz']);
var absPntr = util.toAbsolutePointer('1/baz/~0abc/~1def', base);
assert.deepEqual(absPntr, ['foo','baz', '~abc', '/def']);
var absPntr = util.toAbsolutePointer('2/baz/quux', base);
assert.deepEqual(absPntr, ['baz', 'quux']);
var absPntr = util.toAbsolutePointer('0/baz', base);
assert.deepEqual(absPntr, ['foo', 'bar', 'baz']);
});
it('should trhow if N/... points outside of object', function() {
assert.throws(function() {
util.toAbsolutePointer('3/baz', base);
}, /Cannot reference script 3 levels up, current level is 2/);
});
});
});
| epoberezkin/jsonscript-js | spec/util.spec.js | JavaScript | mit | 9,668 |
import React, { Component } from 'react';
import { Accordion, AccordionItem } from '../../../src/accordion';
export default class AccordionPage extends Component {
state = {
activeKey: '1',
activeKeys: ['1', '3'],
};
handleSingleSelect = (activeKey) => this.setState({ activeKey });
handleMultiSelect = (activeKeys) => this.setState({ activeKeys });
render() {
const { activeKey, activeKeys } = this.state;
return (
<div>
<h4>Controlled Single Select</h4>
<Accordion activeKey={activeKey} onSelect={this.handleSingleSelect}>
<AccordionItem eventKey="1" title="Accordion 1">
Panel 1. Lorem ipsum dolor.
</AccordionItem>
<AccordionItem eventKey="2" title="Accordion 2">
Panel 2. Lorem ipsum dolor.
</AccordionItem>
<AccordionItem eventKey="3" title="Accordion 3">
Panel 3. Lorem ipsum dolor.
</AccordionItem>
<AccordionItem eventKey="4" title="Accordion 4">
Panel 4. Lorem ipsum dolor.
</AccordionItem>
<AccordionItem eventKey="5" title="Accordion 5">
Panel 5. Lorem ipsum dolor.
</AccordionItem>
</Accordion>
<br />
<h4>Controlled Multi Select</h4>
<Accordion activeKey={activeKeys} onSelect={this.handleMultiSelect} multiExpand>
<AccordionItem eventKey="1" title="Accordion 1">
Panel 1. Lorem ipsum dolor.
</AccordionItem>
<AccordionItem eventKey="2" title="Accordion 2">
Panel 2. Lorem ipsum dolor.
</AccordionItem>
<AccordionItem eventKey="3" title="Accordion 3">
Panel 3. Lorem ipsum dolor.
</AccordionItem>
<AccordionItem eventKey="4" title="Accordion 4">
Panel 4. Lorem ipsum dolor.
</AccordionItem>
<AccordionItem eventKey="5" title="Accordion 5">
Panel 5. Lorem ipsum dolor.
</AccordionItem>
</Accordion>
<br />
<h4>Uncontrolled Single Select</h4>
<Accordion>
<AccordionItem eventKey="1" title="Accordion 1">
Panel 1. Lorem ipsum dolor.
</AccordionItem>
<AccordionItem eventKey="2" title="Accordion 2">
Panel 2. Lorem ipsum dolor.
</AccordionItem>
<AccordionItem eventKey="3" title="Accordion 3">
Panel 3. Lorem ipsum dolor.
</AccordionItem>
<AccordionItem eventKey="4" title="Accordion 4">
Panel 4. Lorem ipsum dolor.
</AccordionItem>
<AccordionItem eventKey="5" title="Accordion 5">
Panel 5. Lorem ipsum dolor.
</AccordionItem>
</Accordion>
<br />
<h4>Uncontrolled Single Select With Default 3</h4>
<Accordion defaultActiveKey="3">
<AccordionItem eventKey="1" title="Accordion 1">
Panel 1. Lorem ipsum dolor.
</AccordionItem>
<AccordionItem eventKey="2" title="Accordion 2">
Panel 2. Lorem ipsum dolor.
</AccordionItem>
<AccordionItem eventKey="3" title="Accordion 3">
Panel 3. Lorem ipsum dolor.
</AccordionItem>
<AccordionItem eventKey="4" title="Accordion 4">
Panel 4. Lorem ipsum dolor.
</AccordionItem>
<AccordionItem eventKey="5" title="Accordion 5">
Panel 5. Lorem ipsum dolor.
</AccordionItem>
</Accordion>
<br />
<h4>Uncontrolled Single Select Allowing All Closed</h4>
<Accordion allowAllClosed>
<AccordionItem eventKey="1" title="Accordion 1">
Panel 1. Lorem ipsum dolor.
</AccordionItem>
<AccordionItem eventKey="2" title="Accordion 2">
Panel 2. Lorem ipsum dolor.
</AccordionItem>
<AccordionItem eventKey="3" title="Accordion 3">
Panel 3. Lorem ipsum dolor.
</AccordionItem>
<AccordionItem eventKey="4" title="Accordion 4">
Panel 4. Lorem ipsum dolor.
</AccordionItem>
<AccordionItem eventKey="5" title="Accordion 5">
Panel 5. Lorem ipsum dolor.
</AccordionItem>
</Accordion>
<br />
<h4>Uncontrolled Multi Select</h4>
<Accordion multiExpand>
<AccordionItem eventKey="1" title="Accordion 1">
Panel 1. Lorem ipsum dolor.
</AccordionItem>
<AccordionItem eventKey="2" title="Accordion 2">
Panel 2. Lorem ipsum dolor.
</AccordionItem>
<AccordionItem eventKey="3" title="Accordion 3">
Panel 3. Lorem ipsum dolor.
</AccordionItem>
<AccordionItem eventKey="4" title="Accordion 4">
Panel 4. Lorem ipsum dolor.
</AccordionItem>
<AccordionItem eventKey="5" title="Accordion 5">
Panel 5. Lorem ipsum dolor.
</AccordionItem>
</Accordion>
<br />
<h4>Uncontrolled Multi Select With 2 And 4 Defaults</h4>
<Accordion defaultActiveKey={['2', '4']} multiExpand>
<AccordionItem eventKey="1" title="Accordion 1">
Panel 1. Lorem ipsum dolor.
</AccordionItem>
<AccordionItem eventKey="2" title="Accordion 2">
Panel 2. Lorem ipsum dolor.
</AccordionItem>
<AccordionItem eventKey="3" title="Accordion 3">
Panel 3. Lorem ipsum dolor.
</AccordionItem>
<AccordionItem eventKey="4" title="Accordion 4">
Panel 4. Lorem ipsum dolor.
</AccordionItem>
<AccordionItem eventKey="5" title="Accordion 5">
Panel 5. Lorem ipsum dolor.
</AccordionItem>
</Accordion>
<br />
<h4>Uncontrolled Multi Select Allowing All Closed</h4>
<Accordion allowAllClosed multiExpand>
<AccordionItem eventKey="1" title="Accordion 1">
Panel 1. Lorem ipsum dolor.
</AccordionItem>
<AccordionItem eventKey="2" title="Accordion 2">
Panel 2. Lorem ipsum dolor.
</AccordionItem>
<AccordionItem eventKey="3" title="Accordion 3">
Panel 3. Lorem ipsum dolor.
</AccordionItem>
<AccordionItem eventKey="4" title="Accordion 4">
Panel 4. Lorem ipsum dolor.
</AccordionItem>
<AccordionItem eventKey="5" title="Accordion 5">
Panel 5. Lorem ipsum dolor.
</AccordionItem>
</Accordion>
<br />
</div>
);
}
}
| aruberto/react-foundation-components | docs/containers/accordion/index.js | JavaScript | mit | 6,638 |
import React from 'react';
const Twitter = (props) => {
const { author, meta } = props.quote;
const { encoded, twitter } = meta;
return (
<li>
{(twitter) ?
<a href={`https://twitter.com/intent/tweet?text=${encoded}%20-${author}`} className=''
target="_blank" id="twitter" title={`Share me :) | ${encoded.length}`}>Twitter</a>
:
<a href='' className='disabled'
target="_blank" id="twitter" title={`Too long to share ;( | ${encoded.length}`}>Twitter</a>}
</li>
)
}
export default Twitter; | DaLancelot/tinyQuotes | src/components/Twitter.js | JavaScript | mit | 555 |
module.exports = {
output: {
library: 'RestoreScroll',
libraryTarget: 'umd'
},
externals: [
{
react: {
root: 'React',
commonjs2: 'react',
commonjs: 'react',
amd: 'react'
},
'react-router': {
root: 'ReactRouter',
commonjs2: 'react-router',
commonjs: 'react-router',
amd: 'react-router'
}
}
],
module: {
loaders: [
{ test: /\.js$/, exclude: /node_modules/, loader: 'babel' }
]
},
node: {
Buffer: false
}
}
| jshin49/react-router-restore-scroll | webpack.config.js | JavaScript | mit | 547 |
var searchData=
[
['nearest_5fspd',['nearest_spd',['../namespaceteetool_1_1helpers.html#a644127d95a4ceb9bc2432a1a7800a1c8',1,'teetool::helpers']]],
['normalise_5fdata',['normalise_data',['../namespaceteetool_1_1helpers.html#a6ee2956b143e9f3c976243a007615abf',1,'teetool::helpers']]]
];
| WillemEerland/teetool | docs/search/functions_9.js | JavaScript | mit | 290 |
var test = require('ava');
var OpenT2T = require('opent2t').OpenT2T;
var config = require('./testConfig');
console.log("Config:");
console.log(JSON.stringify(config, null, 2));
var translatorPath = require('path').join(__dirname, '..');
var hubPath = require('path').join(__dirname, '../../../../org.opent2t.sample.hub.superpopular/com.contosothings.hub/js');
var translator = undefined;
function getBinarySwitch(devices) {
for (var i = 0; i < devices.length; i++) {
var d = devices[i];
if (d.opent2t.translator === 'opent2t-translator-com-contosothings-binaryswitch') {
return d;
}
}
return undefined;
}
// setup the translator before all the tests run
test.before(async () => {
var hubTranslator = await OpenT2T.createTranslatorAsync(hubPath, 'thingTranslator', config);
var hubInfo = await OpenT2T.invokeMethodAsync(hubTranslator, 'org.opent2t.sample.hub.superpopular', 'get', []);
var deviceInfo = getBinarySwitch(hubInfo.platforms);
translator = await OpenT2T.createTranslatorAsync(translatorPath, 'thingTranslator', {'deviceInfo': deviceInfo, 'hub': hubTranslator});
});
test.serial("Valid Binary Switch Translator", t => {
t.is(typeof translator, 'object') && t.truthy(translator);
});
///
/// Run a series of tests to validate the translator
///
// Get the entire Lamp schema object unexpanded
test.serial('GetPlatform', t => {
return OpenT2T.invokeMethodAsync(translator, 'org.opent2t.sample.binaryswitch.superpopular', 'get', [])
.then((response) => {
t.is(response.rt[0], 'org.opent2t.sample.binaryswitch.superpopular');
console.log('*** response: \n' + JSON.stringify(response, null, 2));
});
});
// Get the entire Lamp schema object expanded
test.serial('GetPlatformExpanded', t => {
return OpenT2T.invokeMethodAsync(translator, 'org.opent2t.sample.binaryswitch.superpopular', 'get', [true])
.then((response) => {
t.is(response.rt[0], 'org.opent2t.sample.binaryswitch.superpopular');
var resource = response.entities[0].resources[0];
t.is(resource.id, 'power');
t.is(resource.rt[0], 'oic.r.switch.binary');
t.true(resource.value !== undefined);
console.log('*** response: \n' + JSON.stringify(response, null, 2));
});
});
test.serial('GetPower', t => {
return OpenT2T.invokeMethodAsync(translator, 'org.opent2t.sample.binaryswitch.superpopular', 'getDevicesPower', ['F85B0738-6EC0-4A8B-A95A-503B6F2CA0D8'])
.then((response) => {
t.is(response.rt[0], 'oic.r.switch.binary');
console.log('*** response: \n' + JSON.stringify(response, null, 2));
});
});
test.serial('SetPower', t => {
var power = { 'value': true };
return OpenT2T.invokeMethodAsync(translator, 'org.opent2t.sample.binaryswitch.superpopular', 'postDevicesPower', ['F85B0738-6EC0-4A8B-A95A-503B6F2CA0D8', power])
.then((response) => {
t.is(response.rt[0], 'oic.r.switch.binary');
console.log('*** response: \n' + JSON.stringify(response, null, 2));
});
}); | openT2T/translators | org.opent2t.sample.binaryswitch.superpopular/com.contosothings.binaryswitch/js/tests/test.js | JavaScript | mit | 3,158 |
/**
* ownCloud
*
* @author Vincent Petry
* @copyright Copyright (c) 2015 Vincent Petry <pvince81@owncloud.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
describe('OCA.Files.MainFileInfoDetailView tests', function() {
var view, tooltipStub, fileActions, fileList, testFileInfo;
beforeEach(function() {
tooltipStub = sinon.stub($.fn, 'tooltip');
fileActions = new OCA.Files.FileActions();
fileList = new OCA.Files.FileList($('<table></table>'), {
fileActions: fileActions
});
view = new OCA.Files.MainFileInfoDetailView({
fileList: fileList,
fileActions: fileActions
});
testFileInfo = new OCA.Files.FileInfoModel({
id: 5,
name: 'One.txt',
mimetype: 'text/plain',
permissions: 31,
path: '/subdir',
size: 123456789,
etag: 'abcdefg',
mtime: Date.UTC(2015, 6, 17, 1, 2, 0, 0)
});
});
afterEach(function() {
view.remove();
view = undefined;
tooltipStub.restore();
});
describe('rendering', function() {
it('displays basic info', function() {
var clock = sinon.useFakeTimers(Date.UTC(2015, 6, 17, 1, 2, 0, 3));
var dateExpected = OC.Util.formatDate(Date(Date.UTC(2015, 6, 17, 1, 2, 0, 0)));
view.setFileInfo(testFileInfo);
expect(view.$el.find('.fileName h3').text()).toEqual('One.txt');
expect(view.$el.find('.fileName h3').attr('title')).toEqual('One.txt');
expect(view.$el.find('.size').text()).toEqual('117.7 MB');
expect(view.$el.find('.size').attr('title')).toEqual('123456789 bytes');
expect(view.$el.find('.date').text()).toEqual('seconds ago');
expect(view.$el.find('.date').attr('title')).toEqual(dateExpected);
clock.restore();
});
it('displays permalink', function() {
view.setFileInfo(testFileInfo);
expect(view.$el.find('.permalink').attr('href'))
.toEqual(OC.getProtocol() + '://' + OC.getHost() + OC.generateUrl('/f/5'));
});
it('displays favorite icon', function() {
testFileInfo.set('tags', [OC.TAG_FAVORITE]);
view.setFileInfo(testFileInfo);
expect(view.$el.find('.action-favorite > span').hasClass('icon-starred')).toEqual(true);
expect(view.$el.find('.action-favorite > span').hasClass('icon-star')).toEqual(false);
testFileInfo.set('tags', []);
view.setFileInfo(testFileInfo);
expect(view.$el.find('.action-favorite > span').hasClass('icon-starred')).toEqual(false);
expect(view.$el.find('.action-favorite > span').hasClass('icon-star')).toEqual(true);
});
it('displays mime icon', function() {
// File
var lazyLoadPreviewStub = sinon.stub(fileList, 'lazyLoadPreview');
testFileInfo.set('mimetype', 'text/calendar');
view.setFileInfo(testFileInfo);
expect(lazyLoadPreviewStub.calledOnce).toEqual(true);
var previewArgs = lazyLoadPreviewStub.getCall(0).args;
expect(previewArgs[0].mime).toEqual('text/calendar');
expect(previewArgs[0].path).toEqual('/subdir/One.txt');
expect(previewArgs[0].etag).toEqual('abcdefg');
expect(view.$el.find('.thumbnail').hasClass('icon-loading')).toEqual(true);
// returns mime icon first without img parameter
previewArgs[0].callback(
OC.imagePath('core', 'filetypes/text-calendar.svg')
);
// still loading
expect(view.$el.find('.thumbnail').hasClass('icon-loading')).toEqual(true);
// preview loading failed, no prview
previewArgs[0].error();
// loading stopped, the mimetype icon gets displayed
expect(view.$el.find('.thumbnail').hasClass('icon-loading')).toEqual(false);
expect(view.$el.find('.thumbnail').css('background-image'))
.toContain('filetypes/text-calendar.svg');
// Folder
testFileInfo.set('mimetype', 'httpd/unix-directory');
view.setFileInfo(testFileInfo);
expect(view.$el.find('.thumbnail').css('background-image'))
.toContain('filetypes/folder.svg');
lazyLoadPreviewStub.restore();
});
it('uses icon from model if present in model', function() {
var lazyLoadPreviewStub = sinon.stub(fileList, 'lazyLoadPreview');
testFileInfo.set('mimetype', 'httpd/unix-directory');
testFileInfo.set('icon', OC.MimeType.getIconUrl('dir-external'));
view.setFileInfo(testFileInfo);
expect(lazyLoadPreviewStub.notCalled).toEqual(true);
expect(view.$el.find('.thumbnail').hasClass('icon-loading')).toEqual(false);
expect(view.$el.find('.thumbnail').css('background-image'))
.toContain('filetypes/folder-external.svg');
lazyLoadPreviewStub.restore();
});
it('displays thumbnail', function() {
var lazyLoadPreviewStub = sinon.stub(fileList, 'lazyLoadPreview');
testFileInfo.set('mimetype', 'text/plain');
view.setFileInfo(testFileInfo);
expect(lazyLoadPreviewStub.calledOnce).toEqual(true);
var previewArgs = lazyLoadPreviewStub.getCall(0).args;
expect(previewArgs[0].mime).toEqual('text/plain');
expect(previewArgs[0].path).toEqual('/subdir/One.txt');
expect(previewArgs[0].etag).toEqual('abcdefg');
expect(view.$el.find('.thumbnail').hasClass('icon-loading')).toEqual(true);
// returns mime icon first without img parameter
previewArgs[0].callback(
OC.imagePath('core', 'filetypes/text-plain.svg')
);
// still loading
expect(view.$el.find('.thumbnail').hasClass('icon-loading')).toEqual(true);
// return an actual (simulated) image
previewArgs[0].callback(
'testimage', {
width: 100,
height: 200
}
);
// loading stopped, image got displayed
expect(view.$el.find('.thumbnail').css('background-image'))
.toContain('testimage');
expect(view.$el.find('.thumbnail').hasClass('icon-loading')).toEqual(false);
lazyLoadPreviewStub.restore();
});
it('does not show size if no size available', function() {
testFileInfo.unset('size');
view.setFileInfo(testFileInfo);
expect(view.$el.find('.size').length).toEqual(0);
});
it('renders displayName instead of name if available', function() {
testFileInfo.set('displayName', 'hello.txt');
view.setFileInfo(testFileInfo);
expect(view.$el.find('.fileName h3').text()).toEqual('hello.txt');
expect(view.$el.find('.fileName h3').attr('title')).toEqual('hello.txt');
});
it('rerenders when changes are made on the model', function() {
view.setFileInfo(testFileInfo);
testFileInfo.set('tags', [OC.TAG_FAVORITE]);
expect(view.$el.find('.action-favorite > span').hasClass('icon-starred')).toEqual(true);
expect(view.$el.find('.action-favorite > span').hasClass('icon-star')).toEqual(false);
testFileInfo.set('tags', []);
expect(view.$el.find('.action-favorite > span').hasClass('icon-starred')).toEqual(false);
expect(view.$el.find('.action-favorite > span').hasClass('icon-star')).toEqual(true);
});
it('unbinds change listener from model', function() {
view.setFileInfo(testFileInfo);
view.setFileInfo(new OCA.Files.FileInfoModel({
id: 999,
name: 'test.txt',
path: '/'
}));
// set value on old model
testFileInfo.set('tags', [OC.TAG_FAVORITE]);
// no change
expect(view.$el.find('.action-favorite > span').hasClass('icon-starred')).toEqual(false);
expect(view.$el.find('.action-favorite > span').hasClass('icon-star')).toEqual(true);
});
});
describe('events', function() {
it('triggers default action when clicking on the thumbnail', function() {
var actionHandler = sinon.stub();
fileActions.registerAction({
name: 'Something',
mime: 'all',
permissions: OC.PERMISSION_READ,
actionHandler: actionHandler
});
fileActions.setDefault('text/plain', 'Something');
view.setFileInfo(testFileInfo);
view.$el.find('.thumbnail').click();
expect(actionHandler.calledOnce).toEqual(true);
expect(actionHandler.getCall(0).args[0]).toEqual('One.txt');
expect(actionHandler.getCall(0).args[1].fileList).toEqual(fileList);
expect(actionHandler.getCall(0).args[1].fileActions).toEqual(fileActions);
expect(actionHandler.getCall(0).args[1].fileInfoModel).toEqual(testFileInfo);
});
it('triggers "Favorite" action when clicking on the star', function() {
var actionHandler = sinon.stub();
fileActions.registerAction({
name: 'Favorite',
mime: 'all',
permissions: OC.PERMISSION_READ,
actionHandler: actionHandler
});
view.setFileInfo(testFileInfo);
view.$el.find('.action-favorite').click();
expect(actionHandler.calledOnce).toEqual(true);
expect(actionHandler.getCall(0).args[0]).toEqual('One.txt');
expect(actionHandler.getCall(0).args[1].fileList).toEqual(fileList);
expect(actionHandler.getCall(0).args[1].fileActions).toEqual(fileActions);
expect(actionHandler.getCall(0).args[1].fileInfoModel).toEqual(testFileInfo);
});
});
});
| phil-davis/core | apps/files/tests/js/mainfileinfodetailviewSpec.js | JavaScript | mit | 9,194 |
(function($){
$(function(){
var window_width = $(window).width();
// convert rgb to hex value string
function rgb2hex(rgb) {
if (/^#[0-9A-F]{6}$/i.test(rgb)) { return rgb; }
rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
if (rgb === null) { return "N/A"; }
function hex(x) {
return ("0" + parseInt(x).toString(16)).slice(-2);
}
return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}
$('.dynamic-color .col').each(function () {
$(this).children().each(function () {
var color = $(this).css('background-color'),
classes = $(this).attr('class');
$(this).html(rgb2hex(color) + " " + classes);
if (classes.indexOf("darken") >= 0 || $(this).hasClass('black')) {
$(this).css('color', 'rgba(255,255,255,.9');
}
});
});
// Floating-Fixed table of contents
setTimeout(function() {
var tocWrapperHeight = 260; // Max height of ads.
var tocHeight = $('.toc-wrapper .table-of-contents').length ? $('.toc-wrapper .table-of-contents').height() : 0;
var socialHeight = 95; // Height of unloaded social media in footer.
var footerOffset = $('body > footer').first().length ? $('body > footer').first().offset().top : 0;
var bottomOffset = footerOffset - socialHeight - tocHeight - tocWrapperHeight;
if ($('nav').length) {
$('.toc-wrapper').pushpin({
top: $('nav').height(),
bottom: bottomOffset
});
}
else if ($('#index-banner').length) {
$('.toc-wrapper').pushpin({
top: $('#index-banner').height(),
bottom: bottomOffset
});
}
else {
$('.toc-wrapper').pushpin({
top: 0,
bottom: bottomOffset
});
}
}, 100);
// BuySellAds Detection
var $bsa = $(".buysellads"),
$timesToCheck = 3;
function checkForChanges() {
if (!$bsa.find('#carbonads').length) {
$timesToCheck -= 1;
if ($timesToCheck >= 0) {
setTimeout(checkForChanges, 500);
}
else {
var donateAd = $('<div id="carbonads"><span><a class="carbon-text" href="#!" onclick="document.getElementById(\'paypal-donate\').submit();"><img src="images/donate.png" /> Help support us by turning off adblock. If you still prefer to keep adblock on for this page but still want to support us, feel free to donate. Any little bit helps.</a></form></span></div>');
$bsa.append(donateAd);
}
}
}
checkForChanges();
// BuySellAds Demos close button.
$('.buysellads.buysellads-demo .close').on('click', function() {
$(this).parent().remove();
});
// Github Latest Commit
if ($('.github-commit').length) { // Checks if widget div exists (Index only)
$.ajax({
url: "https://api.github.com/repos/dogfalo/materialize/commits/master",
dataType: "json",
success: function (data) {
var sha = data.sha,
date = jQuery.timeago(data.commit.author.date);
if (window_width < 1120) {
sha = sha.substring(0,7);
}
$('.github-commit').find('.date').html(date);
$('.github-commit').find('.sha').html(sha).attr('href', data.html_url);
}
});
}
// Toggle Flow Text
var toggleFlowTextButton = $('#flow-toggle');
toggleFlowTextButton.click( function(){
$('#flow-text-demo').children('p').each(function(){
$(this).toggleClass('flow-text');
});
});
// Toggle Containers on page
var toggleContainersButton = $('#container-toggle-button');
toggleContainersButton.click(function(){
$('body .browser-window .container, .had-container').each(function(){
$(this).toggleClass('had-container');
$(this).toggleClass('container');
if ($(this).hasClass('container')) {
toggleContainersButton.text("Turn off Containers");
}
else {
toggleContainersButton.text("Turn on Containers");
}
});
});
// Detect touch screen and enable scrollbar if necessary
function is_touch_device() {
try {
document.createEvent("TouchEvent");
return true;
} catch (e) {
return false;
}
}
if (is_touch_device()) {
$('#nav-mobile').css({ overflow: 'auto'});
}
// Set checkbox on forms.html to indeterminate
var indeterminateCheckbox = document.getElementById('indeterminate-checkbox');
if (indeterminateCheckbox !== null)
indeterminateCheckbox.indeterminate = true;
// Pushpin Demo Init
if ($('.pushpin-demo-nav').length) {
$('.pushpin-demo-nav').each(function() {
var $this = $(this);
var $target = $('#' + $(this).attr('data-target'));
$this.pushpin({
top: $target.offset().top,
bottom: $target.offset().top + $target.outerHeight() - $this.height()
});
});
}
// Plugin initialization
$('.carousel.carousel-slider').carousel({full_width: true});
$('.carousel').carousel();
$('.slider').slider({full_width: true});
$('.parallax').parallax();
$('.modal').modal();
$('.scrollspy').scrollSpy();
$('.button-collapse').sideNav({'edge': 'left'});
$('.datepicker').pickadate({selectYears: 20});
$('select').not('.disabled').material_select();
$('input.autocomplete').autocomplete({
data: {"Apple": null, "Microsoft": null, "Google": 'http://placehold.it/250x250'}
});
$('.chips').material_chip();
$('.chips-initial').material_chip({
readOnly: true,
data: [{
tag: 'Apple',
}, {
tag: 'Microsoft',
}, {
tag: 'Google',
}]
});
$('.chips-placeholder').material_chip({
placeholder: 'Enter a tag',
secondaryPlaceholder: '+Tag',
});
}); // end of document ready
})(jQuery); // end of jQuery name space
| DonHartman/materialize | js/init.js | JavaScript | mit | 6,018 |
/**
* Created by sercand on 09/06/15.
*/
var DownloadApp = function () {
};
DownloadApp.prototype = {
load: function (uri, folderName, fileName, progress, success, fail) {
var that = this;
that.progress = progress;
that.success = success;
that.fail = fail;
filePath = "";
that.getFilesystem(
function (fileSystem) {
console.log("GotFS");
that.getFolder(fileSystem, folderName, function (folder) {
filePath = folder.toURL() + "/" + fileName;
that.transferFile(uri, filePath, progress, success, fail);
}, function (error) {
console.log("Failed to get folder: " + error.code);
typeof that.fail === 'function' && that.fail(error);
});
},
function (error) {
console.log("Failed to get filesystem: " + error.code);
typeof that.fail === 'function' && that.fail(error);
}
);
},
getFilesystem: function (success, fail) {
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, success, fail);
},
getFolder: function (fileSystem, folderName, success, fail) {
fileSystem.root.getDirectory(folderName, {create: true, exclusive: false}, success, fail)
},
transferFile: function (uri, filePath, progress, success, fail) {
var that = this;
that.progress = progress;
that.success = success;
that.fail = fail;
var transfer = new FileTransfer();
transfer.onprogress = function (progressEvent) {
if (progressEvent.lengthComputable) {
var perc = Math.floor(progressEvent.loaded / progressEvent.total * 100);
typeof that.progress === 'function' && that.progress(perc); // progression on scale 0..100 (percentage) as number
} else {
}
};
transfer.download(
encodeURI(uri),
filePath,
function (entry) {
console.log("File saved to: " + entry.toURL());
typeof that.success === 'function' && that.success(entry);
},
function (error) {
console.log("An error has occurred: Code = " + error.code);
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("download error code " + error.code);
typeof that.fail === 'function' && that.fail(error);
}
);
},
unzip: function (folderName, fileName, success, fail) {
var that = this;
that.success = success;
that.fail = fail;
zip.unzip("cdvfile://localhost/persistent/" + folderName + "/" + fileName,
"cdvfile://localhost/persistent/" + folderName,
function (code) {
console.log("result: " + code);
that.getFilesystem(
function (fileSystem) {
console.log("gotFS");
that.getFolder(fileSystem, folderName + "/ftpack", function (folder) {
document.getElementById("imgPlace").src = folder.nativeURL + "/img.jpg";
folder.getFile("text.html", {create: false}, function (fileEntry) {
fileEntry.file(function (file) {
var reader = new FileReader();
reader.onloadend = function (evt) {
console.log("Read as text");
console.log(evt.target.result);
document.getElementById("txtPlace").innerHTML = evt.target.result;
typeof that.success === 'function' && that.success();
};
reader.readAsText(file);
}, function (error) {
console.log("Failed to get file");
typeof that.fail === 'function' && that.fail(error);
});
}, function (error) {
console.log("failed to get file: " + error.code);
typeof that.fail === 'function' && that.fail(error);
});
}, function (error) {
console.log("failed to get folder: " + error.code);
typeof that.fail === 'function' && that.fail(error);
});
}, function (error) {
console.log("failed to get filesystem: " + error.code);
typeof that.fail === 'function' && that.fail(error);
});
}
);
}
} | Otsimo/Child | www/js/download.js | JavaScript | mit | 5,166 |
export default {
LIST_ERROR_ADD: 'LIST_ERROR_ADD',
LIST_ERROR_REMOVE: 'LIST_ERROR_REMOVE',
}; | RyanNoelk/OpenEats | frontend/modules/list/constants/ErrorConstants.js | JavaScript | mit | 97 |
'use strict';
//model
var model = [
{id: '1', name: 'Jack'},
{id: '2', name: 'Jill'},
{id: '3', name: 'Peter'},
{id: '4', name: 'Petra'},
{id: '5', name: 'Billy'},
{id: '6', name: 'Tracy'},
{id: '7', name: 'Terry'},
];
var Thing = {};
Thing.list = function() {
// return m.request({method: 'GET', url: '/api/things'});
return function(){return model;};
};
//filter
var filter = {};
filter.controller = function(options) {
this.searchTerm = m.prop('');
};
filter.view = function(ctrl) {
return m('input', {oninput: m.withAttr('value', ctrl.searchTerm)});
};
//list
var list = {};
list.controller = function(options) {
this.items = Thing.list();
this.visible = options.visible;
};
list.view = function(ctrl) {
return m('table', [
ctrl.items().filter(ctrl.visible).map(function(item) {
return m('tr', [
m('td', item.id),
m('td', item.name)
]);
})
]);
};
//top level component
var things = {};
things.controller = function() {
var ctrl = this;
ctrl.list = new list.controller({
visible: function(item) {
return item.name.toLowerCase().indexOf(ctrl.filter.searchTerm().toLowerCase()) > -1;
}
});
ctrl.filter = new filter.controller();
};
things.view = function(ctrl) {
return m('.search', [
m('.row', [
m('.col-md-2', [
filter.view(ctrl.filter)
]),
m('.col-md-10', [
list.view(ctrl.list)
])
])
]);
};
module.exports = things;
//run
// m.module(document.body, things)
| pelonpelon/mithril-palantir | src/components/components_organization.js | JavaScript | mit | 1,572 |
import React from 'react'
class Cunting extends React.Component {
render() {
return (
<div>Cunting</div>
)
}
}
export default Cunting | hyy1115/react-redux-webpack3 | src/pages/sorting/Cunting/Cunting.js | JavaScript | mit | 143 |
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M4 5v13h17V5H4zm2 11V7h3v9H6zm5 0v-3.5h3V16h-3zm8 0h-3v-3.5h3V16zm-8-5.5V7h8v3.5h-8z" /></g></React.Fragment>
, 'ViewQuiltOutlined');
| Kagami/material-ui | packages/material-ui-icons/src/ViewQuiltOutlined.js | JavaScript | mit | 313 |
'use strict';
/**
* @file streams.js
* @author Adam Saxén
*
* Implements /vX/streams/ api calls
*/
var Promise = require('bluebird');
var Loader = require("ioant-loader");
var Logger = require("ioant-logger");
var protoio = require('ioant-proto');
var moment = require('moment');
protoio.setup("proto/messages.proto");
class StreamsModel {
/**
* Constructor - inject the database connection into the service.
*
* @param {object} db - A db connection
*/
constructor(db, schema) {
this.db = db;
this.schema = schema;
this.getLatestData.bind(this);
}
/**
* @desc recursive method for retrieving latest received message of a stream.
*/
getLatestData(row){
var column_sid_name = this.schema.database.tables[0].columns[0].name;
var column_message_type = this.schema.database.tables[0].columns[5].name;
var column_message_name = this.schema.database.tables[0].columns[6].name;
var column_timestamp_name = this.schema.database.tables[0].columns[7].name;
var table_prefix = this.schema.database.messageTablePrefix;
return protoio.getProtoMessage(row[column_message_type])
.then((message) => {
var fields = Object.keys(message.fields);
Logger.log('debug', 'Message fields:', {fields:fields});
var latest_value_field = protoio.underScore(fields[0]);
return new Promise((resolve, reject) =>{
resolve(latest_value_field);
});
}).catch((error) => {
Logger.log('error', 'Failed to retreive proto definition for message_type:', {msg_type:row[column_message_type]});
throw error;
}).then(latest_value_field => {
let query = `SELECT ts, ${latest_value_field} AS latestvalue from ${table_prefix}${row[column_sid_name]}_${row[column_message_name]} ORDER BY ts DESC LIMIT 1`;
Logger.log('debug', 'Latest value query:', {query:query});
return this.db.queryAsync(query)
.then(function(result){
return new Promise(function (resolve, reject){
if (result.length > 0){
row.latest_value = result[0].latestvalue;
row.update_ts = result[0].ts;
}
else {
// No latest value found, but stream exists
row.latest_value = "N/D";
row.update_ts = moment().format("YYYY-MM-DD");
}
resolve(row);
})
}).catch((error) => {
Logger.log('error', 'Failed to get stream list latest values.', {query:query});
row.latest_value = "N/D";
row.update_ts = moment().format("YYYY-MM-DD");
return new Promise(function (resolve, reject){
resolve(row);
});
});
});
};
/**
* @desc getStreamList method, for retrieving stream list
* @return {Promise} - resolves list of streams
*/
getStreamList() {
Logger.log('debug', 'Get stream list');
var stream_table = this.schema.database.tables[0].name;
var query = `SELECT * from ${stream_table}`;
Logger.log('debug', 'Stream list query:', {query:query});
return this.db.queryAsync(query).then((rows) =>{
var actions = rows.map((row) => {
return this.getLatestData(row)
});
return Promise.all(actions);
}).catch(function(error){
Logger.log('error', 'Failed to get stream list.', {error:error});
throw error;
});
};
/**
* @desc getStreamInfo method, for retrieving meta info of a stream
*
* @param {Integer} streamid - the stream id
* @return {Promise} - resolves rows array
*/
getStreamInfo(streamid) {
Logger.log('debug', 'Get stream meta info', {streamid:streamid});
var stream_table = this.schema.database.tables[0].name;
var primary_key_field = this.schema.database.tables[0].primaryKey;
var query = `SELECT * from ${stream_table} WHERE ${primary_key_field}=${streamid}`;
return this.db.queryAsync(query)
.catch(function(error){
Logger.log('error', 'Failed to get stream meta info.', {streamid:streamid});
throw error;
});
};
/**
* @desc getStreamData method, for retrieving data of a stream
*
* @param {Integer} streamid - the stream id
* @param {String} startdate - Start date [moment]
* @param {String} enddate - End date [moment]
* @param {Integer} filter - Filter. Select every [filter]:e row
*
* @return {Promise} - resolves rows of stream data
*/
getStreamData(streamid, startdate, enddate, filter) {
Logger.log('debug', 'Get stream data', {streamid:streamid});
var stream_table = this.schema.database.tables[0].name;
var query = `SELECT * from ${stream_table}`;
return this.getStreamInfo(streamid).then((metainfo) =>{
var message_name = metainfo[0].message_name;
var stream_table_prefix = this.schema.database.messageTablePrefix;
var start_unix_timestamp = startdate.unix();
var end_unix_timestamp = enddate.unix();
var query = `SELECT * from ${stream_table_prefix}${streamid}_${message_name} WHERE ts BETWEEN FROM_UNIXTIME(${start_unix_timestamp}) AND FROM_UNIXTIME(${end_unix_timestamp}) AND (id % ${filter}) = 0 ORDER BY ts DESC`;
return this.db.queryAsync(query).then((rows) => {
if (rows.length > 0){
return new Promise((resolve, reject) =>{
resolve(rows);
});
}
else {
// Attempt to get data again, but where filter is not applied
var query_unfiltered = `SELECT * from ${stream_table_prefix}${streamid}_${message_name} WHERE ts BETWEEN FROM_UNIXTIME(${start_unix_timestamp}) AND FROM_UNIXTIME(${end_unix_timestamp}) ORDER BY ts DESC`;
return this.db.queryAsync(query_unfiltered);
}
})
.catch(function(error){
Logger.log('error', 'Failed to get stream data.', {query:query});
throw error;
});
}).catch(function(error){
Logger.log('error', 'Failed to get stream data.', {streamid:streamid});
throw error;
});
};
/**
* @desc getStreamDates method, for retrieving unique dates of a stream
*
* @param {Integer} streamid - the stream id
* @return {Promise} - resolves rows array
*/
getStreamDates(streamid) {
Logger.log('debug', 'Get unique dates from a stream', {streamid:streamid});
var stream_table = this.schema.database.tables[0].name;
var primary_key_field = this.schema.database.tables[0].primaryKey;
var query = `SELECT * from ${stream_table} WHERE ${primary_key_field}=${streamid}`;
Logger.log('debug', 'query_dates', {query:query});
return this.db.queryAsync(query).then((rows) => {
let message_name = rows[0].message_name;
let stream_table_prefix = this.schema.database.messageTablePrefix;
let query_distinct = `SELECT DISTINCT(DATE(ts)) AS date FROM ${stream_table_prefix}${streamid}_${message_name}`;
Logger.log('debug', 'query_distinct', {query_distinct:query_distinct});
return this.db.queryAsync(query_distinct);
}).catch(function(error){
Logger.log('error', 'Failed to get unique dates from stream.', {streamid:streamid});
throw error;
});
};
}
module.exports = StreamsModel;
| ioants/ioant | storage/rest-server-nodejs/models/streams.js | JavaScript | mit | 8,497 |
Clazz.declarePackage ("JM");
Clazz.load (["J.api.MinimizerInterface"], "JM.Minimizer", ["java.lang.Float", "java.util.Hashtable", "JU.AU", "$.BS", "$.Lst", "J.i18n.GT", "JM.MinAngle", "$.MinAtom", "$.MinBond", "$.MinTorsion", "$.MinimizationThread", "JM.FF.ForceFieldMMFF", "$.ForceFieldUFF", "JU.BSUtil", "$.Escape", "$.Logger"], function () {
c$ = Clazz.decorateAsClass (function () {
this.vwr = null;
this.atoms = null;
this.bonds = null;
this.rawBondCount = 0;
this.minAtoms = null;
this.minBonds = null;
this.minAngles = null;
this.minTorsions = null;
this.minPositions = null;
this.bsMinFixed = null;
this.ac = 0;
this.bondCount = 0;
this.atomMap = null;
this.partialCharges = null;
this.steps = 50;
this.crit = 1e-3;
this.units = "kJ/mol";
this.pFF = null;
this.ff = "UFF";
this.bsTaint = null;
this.bsSelected = null;
this.bsAtoms = null;
this.bsFixedDefault = null;
this.bsFixed = null;
this.constraints = null;
this.isSilent = false;
this.constraintMap = null;
this.elemnoMax = 0;
this.$minimizationOn = false;
this.minimizationThread = null;
this.coordSaved = null;
Clazz.instantialize (this, arguments);
}, JM, "Minimizer", null, J.api.MinimizerInterface);
Clazz.makeConstructor (c$,
function () {
});
Clazz.overrideMethod (c$, "setProperty",
function (propertyName, value) {
switch (("ff cancel clear constraintfixed stop vwr ").indexOf (propertyName)) {
case 0:
if (!this.ff.equals (value)) {
this.setProperty ("clear", null);
this.ff = value;
}break;
case 10:
this.stopMinimization (false);
break;
case 20:
if (this.minAtoms != null) {
this.stopMinimization (false);
this.clear ();
}break;
case 30:
this.addConstraint (value);
break;
case 40:
this.bsFixedDefault = value;
break;
case 50:
this.stopMinimization (true);
break;
case 60:
this.vwr = value;
break;
}
return this;
}, "~S,~O");
Clazz.overrideMethod (c$, "getProperty",
function (propertyName, param) {
if (propertyName.equals ("log")) {
return (this.pFF == null ? "" : this.pFF.getLogData ());
}return null;
}, "~S,~N");
Clazz.defineMethod (c$, "addConstraint",
function (c) {
if (c == null) return;
var atoms = c[0];
var nAtoms = atoms[0];
if (nAtoms == 0) {
this.constraints = null;
return;
}if (this.constraints == null) {
this.constraints = new JU.Lst ();
this.constraintMap = new java.util.Hashtable ();
}if (atoms[1] > atoms[nAtoms]) {
JU.AU.swapInt (atoms, 1, nAtoms);
if (nAtoms == 4) JU.AU.swapInt (atoms, 2, 3);
}var id = JU.Escape.eAI (atoms);
var c1 = this.constraintMap.get (id);
if (c1 != null) {
c1[2] = c[2];
return;
}this.constraintMap.put (id, c);
this.constraints.addLast (c);
}, "~A");
Clazz.defineMethod (c$, "clear",
function () {
this.setMinimizationOn (false);
this.ac = 0;
this.bondCount = 0;
this.atoms = null;
this.bonds = null;
this.rawBondCount = 0;
this.minAtoms = null;
this.minBonds = null;
this.minAngles = null;
this.minTorsions = null;
this.partialCharges = null;
this.coordSaved = null;
this.atomMap = null;
this.bsTaint = null;
this.bsAtoms = null;
this.bsFixed = null;
this.bsFixedDefault = null;
this.bsMinFixed = null;
this.bsSelected = null;
this.constraints = null;
this.constraintMap = null;
this.pFF = null;
});
Clazz.overrideMethod (c$, "minimize",
function (steps, crit, bsSelected, bsFixed, haveFixed, forceSilent, ff) {
this.isSilent = (forceSilent || this.vwr.getBooleanProperty ("minimizationSilent"));
var val;
this.setEnergyUnits ();
if (steps == 2147483647) {
val = this.vwr.getP ("minimizationSteps");
if (val != null && Clazz.instanceOf (val, Integer)) steps = (val).intValue ();
}this.steps = steps;
if (!haveFixed && this.bsFixedDefault != null) bsFixed.and (this.bsFixedDefault);
if (crit <= 0) {
val = this.vwr.getP ("minimizationCriterion");
if (val != null && Clazz.instanceOf (val, Float)) crit = (val).floatValue ();
}this.crit = Math.max (crit, 0.0001);
if (this.$minimizationOn) return false;
var pFF0 = this.pFF;
this.getForceField (ff);
if (this.pFF == null) {
JU.Logger.error (J.i18n.GT.o (J.i18n.GT._ ("Could not get class for force field {0}"), ff));
return false;
}JU.Logger.info ("minimize: initializing " + this.pFF.name + " (steps = " + steps + " criterion = " + crit + ") ...");
if (bsSelected.cardinality () == 0) {
JU.Logger.error (J.i18n.GT._ ("No atoms selected -- nothing to do!"));
return false;
}this.atoms = this.vwr.ms.at;
this.bsAtoms = JU.BSUtil.copy (bsSelected);
for (var i = this.bsAtoms.nextSetBit (0); i >= 0; i = this.bsAtoms.nextSetBit (i + 1)) if (this.atoms[i].getElementNumber () == 0) this.bsAtoms.clear (i);
if (bsFixed != null) this.bsAtoms.or (bsFixed);
this.ac = this.bsAtoms.cardinality ();
var sameAtoms = JU.BSUtil.areEqual (bsSelected, this.bsSelected);
this.bsSelected = bsSelected;
if (pFF0 != null && this.pFF !== pFF0) sameAtoms = false;
if (!sameAtoms) this.pFF.clear ();
if ((!sameAtoms || !JU.BSUtil.areEqual (bsFixed, this.bsFixed)) && !this.setupMinimization ()) {
this.clear ();
return false;
}if (steps > 0) {
this.bsTaint = JU.BSUtil.copy (this.bsAtoms);
JU.BSUtil.andNot (this.bsTaint, bsFixed);
this.vwr.ms.setTaintedAtoms (this.bsTaint, 2);
}if (bsFixed != null) this.bsFixed = bsFixed;
this.setAtomPositions ();
if (this.constraints != null) {
for (var i = this.constraints.size (); --i >= 0; ) {
var constraint = this.constraints.get (i);
var aList = constraint[0];
var minList = constraint[1];
var nAtoms = aList[0] = Math.abs (aList[0]);
for (var j = 1; j <= nAtoms; j++) {
if (steps <= 0 || !this.bsAtoms.get (aList[j])) {
aList[0] = -nAtoms;
break;
}minList[j - 1] = this.atomMap[aList[j]];
}
}
}this.pFF.setConstraints (this);
if (steps <= 0) this.getEnergyOnly ();
else if (this.isSilent || !this.vwr.useMinimizationThread ()) this.minimizeWithoutThread ();
else this.setMinimizationOn (true);
return true;
}, "~N,~N,JU.BS,JU.BS,~B,~B,~S");
Clazz.defineMethod (c$, "setEnergyUnits",
function () {
var s = this.vwr.g.energyUnits;
this.units = (s.equalsIgnoreCase ("kcal") ? "kcal" : "kJ");
});
Clazz.defineMethod (c$, "setupMinimization",
function () {
this.coordSaved = null;
this.atomMap = Clazz.newIntArray (this.atoms.length, 0);
this.minAtoms = new Array (this.ac);
this.elemnoMax = 0;
var bsElements = new JU.BS ();
for (var i = this.bsAtoms.nextSetBit (0), pt = 0; i >= 0; i = this.bsAtoms.nextSetBit (i + 1), pt++) {
var atom = this.atoms[i];
this.atomMap[i] = pt;
var atomicNo = this.atoms[i].getElementNumber ();
this.elemnoMax = Math.max (this.elemnoMax, atomicNo);
bsElements.set (atomicNo);
this.minAtoms[pt] = new JM.MinAtom (pt, atom, [atom.x, atom.y, atom.z], this.ac);
this.minAtoms[pt].sType = atom.getAtomName ();
}
JU.Logger.info (J.i18n.GT.i (J.i18n.GT._ ("{0} atoms will be minimized."), this.ac));
JU.Logger.info ("minimize: getting bonds...");
this.bonds = this.vwr.ms.bo;
this.rawBondCount = this.vwr.ms.bondCount;
this.getBonds ();
JU.Logger.info ("minimize: getting angles...");
this.getAngles ();
JU.Logger.info ("minimize: getting torsions...");
this.getTorsions ();
return this.setModel (bsElements);
});
Clazz.defineMethod (c$, "setModel",
function (bsElements) {
if (!this.pFF.setModel (bsElements, this.elemnoMax)) {
JU.Logger.error (J.i18n.GT.o (J.i18n.GT._ ("could not setup force field {0}"), this.ff));
if (this.ff.equals ("MMFF")) {
this.getForceField ("UFF");
return this.setModel (bsElements);
}return false;
}return true;
}, "JU.BS");
Clazz.defineMethod (c$, "setAtomPositions",
function () {
for (var i = 0; i < this.ac; i++) this.minAtoms[i].set ();
this.bsMinFixed = null;
if (this.bsFixed != null) {
this.bsMinFixed = new JU.BS ();
for (var i = this.bsAtoms.nextSetBit (0), pt = 0; i >= 0; i = this.bsAtoms.nextSetBit (i + 1), pt++) if (this.bsFixed.get (i)) this.bsMinFixed.set (pt);
}});
Clazz.defineMethod (c$, "getBonds",
function () {
var bondInfo = new JU.Lst ();
this.bondCount = 0;
var i1;
var i2;
for (var i = 0; i < this.rawBondCount; i++) {
var bond = this.bonds[i];
if (!this.bsAtoms.get (i1 = bond.getAtomIndex1 ()) || !this.bsAtoms.get (i2 = bond.getAtomIndex2 ())) continue;
if (i2 < i1) {
var ii = i1;
i1 = i2;
i2 = ii;
}var bondOrder = bond.getCovalentOrder ();
switch (bondOrder) {
case 1:
case 2:
case 3:
break;
case 515:
bondOrder = 5;
break;
default:
bondOrder = 1;
}
bondInfo.addLast ( new JM.MinBond (i, this.bondCount++, this.atomMap[i1], this.atomMap[i2], bondOrder, 0, null));
}
this.minBonds = new Array (this.bondCount);
for (var i = 0; i < this.bondCount; i++) {
var bond = this.minBonds[i] = bondInfo.get (i);
var atom1 = bond.data[0];
var atom2 = bond.data[1];
this.minAtoms[atom1].addBond (bond, atom2);
this.minAtoms[atom2].addBond (bond, atom1);
}
for (var i = 0; i < this.ac; i++) this.minAtoms[i].getBondedAtomIndexes ();
});
Clazz.defineMethod (c$, "getAngles",
function () {
var vAngles = new JU.Lst ();
var atomList;
var ic;
for (var i = 0; i < this.bondCount; i++) {
var bond = this.minBonds[i];
var ia = bond.data[0];
var ib = bond.data[1];
if (this.minAtoms[ib].nBonds > 1) {
atomList = this.minAtoms[ib].getBondedAtomIndexes ();
for (var j = atomList.length; --j >= 0; ) if ((ic = atomList[j]) > ia) {
vAngles.addLast ( new JM.MinAngle ([ia, ib, ic, i, this.minAtoms[ib].getBondIndex (j)]));
this.minAtoms[ia].bsVdw.clear (ic);
}
}if (this.minAtoms[ia].nBonds > 1) {
atomList = this.minAtoms[ia].getBondedAtomIndexes ();
for (var j = atomList.length; --j >= 0; ) if ((ic = atomList[j]) < ib && ic > ia) {
vAngles.addLast ( new JM.MinAngle ([ic, ia, ib, this.minAtoms[ia].getBondIndex (j), i]));
this.minAtoms[ic].bsVdw.clear (ib);
}
}}
this.minAngles = vAngles.toArray ( new Array (vAngles.size ()));
JU.Logger.info (this.minAngles.length + " angles");
});
Clazz.defineMethod (c$, "getTorsions",
function () {
var vTorsions = new JU.Lst ();
var id;
for (var i = this.minAngles.length; --i >= 0; ) {
var angle = this.minAngles[i].data;
var ia = angle[0];
var ib = angle[1];
var ic = angle[2];
var atomList;
if (ic > ib && this.minAtoms[ic].nBonds > 1) {
atomList = this.minAtoms[ic].getBondedAtomIndexes ();
for (var j = 0; j < atomList.length; j++) {
id = atomList[j];
if (id != ia && id != ib) {
vTorsions.addLast ( new JM.MinTorsion ([ia, ib, ic, id, angle[3], angle[4], this.minAtoms[ic].getBondIndex (j)]));
this.minAtoms[Math.min (ia, id)].bs14.set (Math.max (ia, id));
}}
}if (ia > ib && this.minAtoms[ia].nBonds != 1) {
atomList = this.minAtoms[ia].getBondedAtomIndexes ();
for (var j = 0; j < atomList.length; j++) {
id = atomList[j];
if (id != ic && id != ib) {
vTorsions.addLast ( new JM.MinTorsion ([ic, ib, ia, id, angle[4], angle[3], this.minAtoms[ia].getBondIndex (j)]));
this.minAtoms[Math.min (ic, id)].bs14.set (Math.max (ic, id));
}}
}}
this.minTorsions = vTorsions.toArray ( new Array (vTorsions.size ()));
JU.Logger.info (this.minTorsions.length + " torsions");
});
Clazz.defineMethod (c$, "getForceField",
function (ff) {
if (ff.startsWith ("MMFF")) ff = "MMFF";
if (this.pFF == null || !ff.equals (this.ff)) {
if (ff.equals ("UFF")) {
this.pFF = new JM.FF.ForceFieldUFF (this);
} else if (ff.equals ("MMFF")) {
this.pFF = new JM.FF.ForceFieldMMFF (this);
} else {
this.pFF = new JM.FF.ForceFieldUFF (this);
ff = "UFF";
}this.ff = ff;
this.vwr.setStringProperty ("_minimizationForceField", ff);
}return this.pFF;
}, "~S");
Clazz.overrideMethod (c$, "minimizationOn",
function () {
return this.$minimizationOn;
});
Clazz.overrideMethod (c$, "getThread",
function () {
return this.minimizationThread;
});
Clazz.defineMethod (c$, "setMinimizationOn",
function (minimizationOn) {
this.$minimizationOn = minimizationOn;
if (!minimizationOn) {
if (this.minimizationThread != null) {
this.minimizationThread = null;
}return;
}if (this.minimizationThread == null) {
this.minimizationThread = new JM.MinimizationThread ();
this.minimizationThread.setManager (this, this.vwr, null);
this.minimizationThread.start ();
}}, "~B");
Clazz.defineMethod (c$, "getEnergyOnly",
function () {
if (this.pFF == null || this.vwr == null) return;
this.pFF.steepestDescentInitialize (this.steps, this.crit);
this.vwr.setFloatProperty ("_minimizationEnergyDiff", 0);
this.reportEnergy ();
this.vwr.setStringProperty ("_minimizationStatus", "calculate");
this.vwr.notifyMinimizationStatus ();
});
Clazz.defineMethod (c$, "reportEnergy",
function () {
this.vwr.setFloatProperty ("_minimizationEnergy", this.pFF.toUserUnits (this.pFF.getEnergy ()));
});
Clazz.overrideMethod (c$, "startMinimization",
function () {
try {
JU.Logger.info ("minimizer: startMinimization");
this.vwr.setIntProperty ("_minimizationStep", 0);
this.vwr.setStringProperty ("_minimizationStatus", "starting");
this.vwr.setFloatProperty ("_minimizationEnergy", 0);
this.vwr.setFloatProperty ("_minimizationEnergyDiff", 0);
this.vwr.notifyMinimizationStatus ();
this.vwr.stm.saveCoordinates ("minimize", this.bsTaint);
this.pFF.steepestDescentInitialize (this.steps, this.crit);
this.reportEnergy ();
this.saveCoordinates ();
} catch (e) {
if (Clazz.exceptionOf (e, Exception)) {
JU.Logger.error ("minimization error vwr=" + this.vwr + " pFF = " + this.pFF);
return false;
} else {
throw e;
}
}
this.$minimizationOn = true;
return true;
});
Clazz.overrideMethod (c$, "stepMinimization",
function () {
if (!this.$minimizationOn) return false;
var doRefresh = (!this.isSilent && this.vwr.getBooleanProperty ("minimizationRefresh"));
this.vwr.setStringProperty ("_minimizationStatus", "running");
var going = this.pFF.steepestDescentTakeNSteps (1);
var currentStep = this.pFF.getCurrentStep ();
this.vwr.setIntProperty ("_minimizationStep", currentStep);
this.reportEnergy ();
this.vwr.setFloatProperty ("_minimizationEnergyDiff", this.pFF.toUserUnits (this.pFF.getEnergyDiff ()));
this.vwr.notifyMinimizationStatus ();
if (doRefresh) {
this.updateAtomXYZ ();
this.vwr.refresh (3, "minimization step " + currentStep);
}return going;
});
Clazz.overrideMethod (c$, "endMinimization",
function () {
this.updateAtomXYZ ();
this.setMinimizationOn (false);
var failed = this.pFF.detectExplosion ();
if (failed) this.restoreCoordinates ();
this.vwr.setIntProperty ("_minimizationStep", this.pFF.getCurrentStep ());
this.reportEnergy ();
this.vwr.setStringProperty ("_minimizationStatus", (failed ? "failed" : "done"));
this.vwr.notifyMinimizationStatus ();
this.vwr.refresh (3, "Minimizer:done" + (failed ? " EXPLODED" : "OK"));
JU.Logger.info ("minimizer: endMinimization");
});
Clazz.defineMethod (c$, "saveCoordinates",
function () {
if (this.coordSaved == null) this.coordSaved = Clazz.newDoubleArray (this.ac, 3, 0);
for (var i = 0; i < this.ac; i++) for (var j = 0; j < 3; j++) this.coordSaved[i][j] = this.minAtoms[i].coord[j];
});
Clazz.defineMethod (c$, "restoreCoordinates",
function () {
if (this.coordSaved == null) return;
for (var i = 0; i < this.ac; i++) for (var j = 0; j < 3; j++) this.minAtoms[i].coord[j] = this.coordSaved[i][j];
this.updateAtomXYZ ();
});
Clazz.defineMethod (c$, "stopMinimization",
function (coordAreOK) {
if (!this.$minimizationOn) return;
this.setMinimizationOn (false);
if (coordAreOK) this.endMinimization ();
else this.restoreCoordinates ();
}, "~B");
Clazz.defineMethod (c$, "updateAtomXYZ",
function () {
if (this.steps <= 0) return;
for (var i = 0; i < this.ac; i++) {
var minAtom = this.minAtoms[i];
var atom = minAtom.atom;
atom.x = minAtom.coord[0];
atom.y = minAtom.coord[1];
atom.z = minAtom.coord[2];
}
this.vwr.refreshMeasures (false);
});
Clazz.defineMethod (c$, "minimizeWithoutThread",
function () {
if (!this.startMinimization ()) return;
while (this.stepMinimization ()) {
}
this.endMinimization ();
});
Clazz.defineMethod (c$, "report",
function (msg, isEcho) {
if (this.isSilent) JU.Logger.info (msg);
else if (isEcho) this.vwr.showString (msg, false);
else this.vwr.scriptEcho (msg);
}, "~S,~B");
Clazz.overrideMethod (c$, "calculatePartialCharges",
function (bonds, bondCount, atoms, bsAtoms) {
var ff = new JM.FF.ForceFieldMMFF (this);
ff.setArrays (atoms, bsAtoms, bonds, bondCount, true, true);
this.vwr.setAtomProperty (bsAtoms, 1087375361, 0, 0, null, null, ff.getAtomTypeDescriptions ());
this.vwr.setAtomProperty (bsAtoms, 1112541195, 0, 0, null, ff.getPartialCharges (), null);
}, "~A,~N,~A,JU.BS");
});
| mausdin/MOFsite | jsmol/j2s/JM/Minimizer.js | JavaScript | mit | 16,601 |
var isElement = require('./isElement');
describe('is/isElement', function () {
it('checks if a value is DOM element', function () {
expect(isElement(document.getElementsByTagName('head')[0])).toBe(true);
expect(isElement('Lorem')).toBe(false);
});
});
| georapbox/smallsJS | packages/is/isElement/test.js | JavaScript | mit | 266 |
/*
RequireJS i18n 2.0.2 Copyright (c) 2010-2012, The Dojo Foundation All Rights Reserved.
Available via the MIT or new BSD license.
see: http://github.com/requirejs/i18n for details
*/
(function(){function s(a,b,d,h,g,e){b[a]||(a=a.replace(/^zh-(Hans|Hant)-([^-]+)$/,"zh-$2"));return b[a]?(d.push(a),!0!==b[a]&&1!==b[a]||h.push(g+a+"/"+e),!0):!1}function B(a){var b=a.toLowerCase().split(/-|_/);a=[b[0]];var d=1,h;for(h=1;h<b.length;h++){var g=b[h],e=g.length;if(1==e)break;switch(d){case 1:if(d=2,4==e){a.push(g.charAt(0).toUpperCase()+g.slice(1));break}case 2:d=3;a.push(g.toUpperCase());break;default:a.push(g)}}if(!("zh"!=a[0]||1<a.length&&4==a[1].length)){b="Hans";d=1<a.length?a[1]:
null;if("TW"===d||"MO"===d||"HK"===d)b="Hant";a.splice(1,0,b)}return a}function w(a,b){for(var d in b)b.hasOwnProperty(d)&&(null==a[d]?a[d]=b[d]:"object"===typeof b[d]&&"object"===typeof a[d]&&w(a[d],b[d]))}var x=/(^.*(^|\/)nls(\/|$))([^\/]*)\/?([^\/]*)/;define(["module"],function(a){var b=a.config?a.config():{};return{version:"2.0.1+",load:function(a,h,g,e){e=e||{};e.locale&&(b.locale=e.locale);var c=x.exec(a),n=c[1],f,p=c[5],q,k=[],t={},y,r="",z,A,l,u,v,m;c[5]?(n=c[1],a=n+p,f=c[4]):(p=c[4],f=b.locale,
"undefined"!==typeof document?(f||(f=e.isBuild?"root":document.documentElement.lang)||(f=void 0===navigator?"root":navigator.language||navigator.userLanguage||"root"),b.locale=f):f="root");q=B(f);z=b.noOverlay;A=b.defaultNoOverlayLocale;if(c=b.merge)if(l=c[n+p])c=x.exec(l),u=c[1],v=c[4];m=[];for(c=0;c<q.length;c++)y=q[c],r+=(r?"-":"")+y,m.push(r);e.isBuild?(k.push(a),l&&k.push(l),h(k,function(){g()})):("query"==b.includeLocale&&(a=h.toUrl(a+".js"),a+=(-1===a.indexOf("?")?"?":"&")+"loc="+f),e=[a],
l&&e.push(l),h(e,function(a,b){var d=[],c=function(a,b,c){for(var e=z||!0===a.__noOverlay,h=A||a.__defaultNoOverlayLocale,g=!1,f=m.length-1;0<=f&&(!g||!e);f--)g=s(m[f],a,d,k,b,c);f=1===m.length&&"root"===m[0];e&&(f||!g)&&h&&s(h,a,d,k,b,c);f||s("root",a,d,k,b,c)};c(a,n,p);var e=d.length;b&&c(b,u,v);h(k,function(){var c=function(a,b,c,e,f){for(;b<c&&d[b];b++){var g=d[b],k=a[g];if(!0===k||1===k)k=h(e+g+"/"+f);w(t,k)}};c(b,e,d.length,u,v);c(a,0,e,n,p);t._ojLocale_=q.join("-");g(t)})}))}}})})();
| crmouli/crmouli.github.io | js/libs/oj/v3.0.0/ojL10n.js | JavaScript | mit | 2,199 |
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
var graphql_1 = require("graphql");
var AddArgumentsAsVariablesTransform = /** @class */ (function () {
function AddArgumentsAsVariablesTransform(schema, args) {
this.schema = schema;
this.args = args;
}
AddArgumentsAsVariablesTransform.prototype.transformRequest = function (originalRequest) {
var _a = addVariablesToRootField(this.schema, originalRequest.document, this.args), document = _a.document, newVariables = _a.newVariables;
var variables = __assign({}, originalRequest.variables, newVariables);
return {
document: document,
variables: variables,
};
};
return AddArgumentsAsVariablesTransform;
}());
exports.default = AddArgumentsAsVariablesTransform;
function addVariablesToRootField(targetSchema, document, args) {
var operations = document.definitions.filter(function (def) { return def.kind === graphql_1.Kind.OPERATION_DEFINITION; });
var fragments = document.definitions.filter(function (def) { return def.kind === graphql_1.Kind.FRAGMENT_DEFINITION; });
var variableNames = {};
var newOperations = operations.map(function (operation) {
var existingVariables = operation.variableDefinitions.map(function (variableDefinition) {
return variableDefinition.variable.name.value;
});
var variableCounter = 0;
var variables = {};
var generateVariableName = function (argName) {
var varName;
do {
varName = "_v" + variableCounter + "_" + argName;
variableCounter++;
} while (existingVariables.indexOf(varName) !== -1);
return varName;
};
var type;
if (operation.operation === 'subscription') {
type = targetSchema.getSubscriptionType();
}
else if (operation.operation === 'mutation') {
type = targetSchema.getMutationType();
}
else {
type = targetSchema.getQueryType();
}
var newSelectionSet = [];
operation.selectionSet.selections.forEach(function (selection) {
if (selection.kind === graphql_1.Kind.FIELD) {
var newArgs_1 = {};
selection.arguments.forEach(function (argument) {
newArgs_1[argument.name.value] = argument;
});
var name_1 = selection.name.value;
var field = type.getFields()[name_1];
field.args.forEach(function (argument) {
if (argument.name in args) {
var variableName = generateVariableName(argument.name);
variableNames[argument.name] = variableName;
newArgs_1[argument.name] = {
kind: graphql_1.Kind.ARGUMENT,
name: {
kind: graphql_1.Kind.NAME,
value: argument.name,
},
value: {
kind: graphql_1.Kind.VARIABLE,
name: {
kind: graphql_1.Kind.NAME,
value: variableName,
},
},
};
existingVariables.push(variableName);
variables[variableName] = {
kind: graphql_1.Kind.VARIABLE_DEFINITION,
variable: {
kind: graphql_1.Kind.VARIABLE,
name: {
kind: graphql_1.Kind.NAME,
value: variableName,
},
},
type: typeToAst(argument.type),
};
}
});
newSelectionSet.push(__assign({}, selection, { arguments: Object.keys(newArgs_1).map(function (argName) { return newArgs_1[argName]; }) }));
}
else {
newSelectionSet.push(selection);
}
});
return __assign({}, operation, { variableDefinitions: operation.variableDefinitions.concat(Object.keys(variables).map(function (varName) { return variables[varName]; })), selectionSet: {
kind: graphql_1.Kind.SELECTION_SET,
selections: newSelectionSet,
} });
});
var newVariables = {};
Object.keys(variableNames).forEach(function (name) {
newVariables[variableNames[name]] = args[name];
});
return {
document: __assign({}, document, { definitions: newOperations.concat(fragments) }),
newVariables: newVariables,
};
}
function typeToAst(type) {
if (type instanceof graphql_1.GraphQLNonNull) {
var innerType = typeToAst(type.ofType);
if (innerType.kind === graphql_1.Kind.LIST_TYPE ||
innerType.kind === graphql_1.Kind.NAMED_TYPE) {
return {
kind: graphql_1.Kind.NON_NULL_TYPE,
type: innerType,
};
}
else {
throw new Error('Incorrent inner non-null type');
}
}
else if (type instanceof graphql_1.GraphQLList) {
return {
kind: graphql_1.Kind.LIST_TYPE,
type: typeToAst(type.ofType),
};
}
else {
return {
kind: graphql_1.Kind.NAMED_TYPE,
name: {
kind: graphql_1.Kind.NAME,
value: type.toString(),
},
};
}
}
//# sourceMappingURL=AddArgumentsAsVariables.js.map | AntonyThorpe/knockout-apollo | tests/node_modules/graphql-tools/dist/transforms/AddArgumentsAsVariables.js | JavaScript | mit | 6,250 |
/*!
* Bootstrap v4.0.0-alpha (http://getbootstrap.com)
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
*/
if (typeof jQuery === 'undefined') {
throw new Error('Bootstrap\'s JavaScript requires jQuery')
}
+function ($) {
var version = $.fn.jquery.split(' ')[0].split('.')
if (version[0] !== '2') {
throw new Error('Bootstrap\'s JavaScript requires jQuery version 2.x.x')
}
}(jQuery);
+function ($) {
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.0.0): util.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
'use strict';
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var Util = (function ($) {
/**
* ------------------------------------------------------------------------
* Private TransitionEnd Helpers
* ------------------------------------------------------------------------
*/
var transition = false;
var TransitionEndEvent = {
WebkitTransition: 'webkitTransitionEnd',
MozTransition: 'transitionend',
OTransition: 'oTransitionEnd otransitionend',
transition: 'transitionend'
};
// shoutout AngusCroll (https://goo.gl/pxwQGp)
function toType(obj) {
return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase();
}
function isElement(obj) {
return (obj[0] || obj).nodeType;
}
function getSpecialTransitionEndEvent() {
return {
bindType: transition.end,
delegateType: transition.end,
handle: function handle(event) {
if ($(event.target).is(this)) {
return event.handleObj.handler.apply(this, arguments);
}
}
};
}
function transitionEndTest() {
if (window.QUnit) {
return false;
}
var el = document.createElement('bootstrap');
for (var _name in TransitionEndEvent) {
if (el.style[_name] !== undefined) {
return { end: TransitionEndEvent[_name] };
}
}
return false;
}
function transitionEndEmulator(duration) {
var _this = this;
var called = false;
$(this).one(Util.TRANSITION_END, function () {
called = true;
});
setTimeout(function () {
if (!called) {
Util.triggerTransitionEnd(_this);
}
}, duration);
return this;
}
function setTransitionEndSupport() {
transition = transitionEndTest();
$.fn.emulateTransitionEnd = transitionEndEmulator;
if (Util.supportsTransitionEnd()) {
$.event.special[Util.TRANSITION_END] = getSpecialTransitionEndEvent();
}
}
/**
* --------------------------------------------------------------------------
* Public Util Api
* --------------------------------------------------------------------------
*/
var Util = {
TRANSITION_END: 'bsTransitionEnd',
getUID: function getUID(prefix) {
do {
prefix += ~ ~(Math.random() * 1000000);
} while (document.getElementById(prefix));
return prefix;
},
getSelectorFromElement: function getSelectorFromElement(element) {
var selector = element.getAttribute('data-target');
if (!selector) {
selector = element.getAttribute('href') || '';
selector = /^#[a-z]/i.test(selector) ? selector : null;
}
return selector;
},
reflow: function reflow(element) {
new Function('bs', 'return bs')(element.offsetHeight);
},
triggerTransitionEnd: function triggerTransitionEnd(element) {
$(element).trigger(transition.end);
},
supportsTransitionEnd: function supportsTransitionEnd() {
return Boolean(transition);
},
typeCheckConfig: function typeCheckConfig(componentName, config, configTypes) {
for (var property in configTypes) {
if (configTypes.hasOwnProperty(property)) {
var expectedTypes = configTypes[property];
var value = config[property];
var valueType = undefined;
if (value && isElement(value)) {
valueType = 'element';
} else {
valueType = toType(value);
}
if (!new RegExp(expectedTypes).test(valueType)) {
throw new Error(componentName.toUpperCase() + ': ' + ('Option "' + property + '" provided type "' + valueType + '" ') + ('but expected type "' + expectedTypes + '".'));
}
}
}
}
};
setTransitionEndSupport();
return Util;
})(jQuery);
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.0.0): alert.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
var Alert = (function ($) {
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
var NAME = 'alert';
var VERSION = '4.0.0';
var DATA_KEY = 'bs.alert';
var EVENT_KEY = '.' + DATA_KEY;
var DATA_API_KEY = '.data-api';
var JQUERY_NO_CONFLICT = $.fn[NAME];
var TRANSITION_DURATION = 150;
var Selector = {
DISMISS: '[data-dismiss="alert"]'
};
var Event = {
CLOSE: 'close' + EVENT_KEY,
CLOSED: 'closed' + EVENT_KEY,
CLICK_DATA_API: 'click' + EVENT_KEY + DATA_API_KEY
};
var ClassName = {
ALERT: 'alert',
FADE: 'fade',
IN: 'in'
};
/**
* ------------------------------------------------------------------------
* Class Definition
* ------------------------------------------------------------------------
*/
var Alert = (function () {
function Alert(element) {
_classCallCheck(this, Alert);
this._element = element;
}
/**
* ------------------------------------------------------------------------
* Data Api implementation
* ------------------------------------------------------------------------
*/
// getters
_createClass(Alert, [{
key: 'close',
// public
value: function close(element) {
element = element || this._element;
var rootElement = this._getRootElement(element);
var customEvent = this._triggerCloseEvent(rootElement);
if (customEvent.isDefaultPrevented()) {
return;
}
this._removeElement(rootElement);
}
}, {
key: 'dispose',
value: function dispose() {
$.removeData(this._element, DATA_KEY);
this._element = null;
}
// private
}, {
key: '_getRootElement',
value: function _getRootElement(element) {
var selector = Util.getSelectorFromElement(element);
var parent = false;
if (selector) {
parent = $(selector)[0];
}
if (!parent) {
parent = $(element).closest('.' + ClassName.ALERT)[0];
}
return parent;
}
}, {
key: '_triggerCloseEvent',
value: function _triggerCloseEvent(element) {
var closeEvent = $.Event(Event.CLOSE);
$(element).trigger(closeEvent);
return closeEvent;
}
}, {
key: '_removeElement',
value: function _removeElement(element) {
$(element).removeClass(ClassName.IN);
if (!Util.supportsTransitionEnd() || !$(element).hasClass(ClassName.FADE)) {
this._destroyElement(element);
return;
}
$(element).one(Util.TRANSITION_END, $.proxy(this._destroyElement, this, element)).emulateTransitionEnd(TRANSITION_DURATION);
}
}, {
key: '_destroyElement',
value: function _destroyElement(element) {
$(element).detach().trigger(Event.CLOSED).remove();
}
// static
}], [{
key: '_jQueryInterface',
value: function _jQueryInterface(config) {
return this.each(function () {
var $element = $(this);
var data = $element.data(DATA_KEY);
if (!data) {
data = new Alert(this);
$element.data(DATA_KEY, data);
}
if (config === 'close') {
data[config](this);
}
});
}
}, {
key: '_handleDismiss',
value: function _handleDismiss(alertInstance) {
return function (event) {
if (event) {
event.preventDefault();
}
alertInstance.close(this);
};
}
}, {
key: 'VERSION',
get: function get() {
return VERSION;
}
}]);
return Alert;
})();
$(document).on(Event.CLICK_DATA_API, Selector.DISMISS, Alert._handleDismiss(new Alert()));
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
$.fn[NAME] = Alert._jQueryInterface;
$.fn[NAME].Constructor = Alert;
$.fn[NAME].noConflict = function () {
$.fn[NAME] = JQUERY_NO_CONFLICT;
return Alert._jQueryInterface;
};
return Alert;
})(jQuery);
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.0.0): button.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
var Button = (function ($) {
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
var NAME = 'button';
var VERSION = '4.0.0';
var DATA_KEY = 'bs.button';
var EVENT_KEY = '.' + DATA_KEY;
var DATA_API_KEY = '.data-api';
var JQUERY_NO_CONFLICT = $.fn[NAME];
var ClassName = {
ACTIVE: 'active',
BUTTON: 'btn',
FOCUS: 'focus'
};
var Selector = {
DATA_TOGGLE_CARROT: '[data-toggle^="button"]',
DATA_TOGGLE: '[data-toggle="buttons"]',
INPUT: 'input',
ACTIVE: '.active',
BUTTON: '.btn'
};
var Event = {
CLICK_DATA_API: 'click' + EVENT_KEY + DATA_API_KEY,
FOCUS_BLUR_DATA_API: 'focus' + EVENT_KEY + DATA_API_KEY + ' ' + ('blur' + EVENT_KEY + DATA_API_KEY)
};
/**
* ------------------------------------------------------------------------
* Class Definition
* ------------------------------------------------------------------------
*/
var Button = (function () {
function Button(element) {
_classCallCheck(this, Button);
this._element = element;
}
/**
* ------------------------------------------------------------------------
* Data Api implementation
* ------------------------------------------------------------------------
*/
// getters
_createClass(Button, [{
key: 'toggle',
// public
value: function toggle() {
var triggerChangeEvent = true;
var rootElement = $(this._element).closest(Selector.DATA_TOGGLE)[0];
if (rootElement) {
var input = $(this._element).find(Selector.INPUT)[0];
if (input) {
if (input.type === 'radio') {
if (input.checked && $(this._element).hasClass(ClassName.ACTIVE)) {
triggerChangeEvent = false;
} else {
var activeElement = $(rootElement).find(Selector.ACTIVE)[0];
if (activeElement) {
$(activeElement).removeClass(ClassName.ACTIVE);
}
}
}
if (triggerChangeEvent) {
input.checked = !$(this._element).hasClass(ClassName.ACTIVE);
$(this._element).trigger('change');
}
}
} else {
this._element.setAttribute('aria-pressed', !$(this._element).hasClass(ClassName.ACTIVE));
}
if (triggerChangeEvent) {
$(this._element).toggleClass(ClassName.ACTIVE);
}
}
}, {
key: 'dispose',
value: function dispose() {
$.removeData(this._element, DATA_KEY);
this._element = null;
}
// static
}], [{
key: '_jQueryInterface',
value: function _jQueryInterface(config) {
return this.each(function () {
var data = $(this).data(DATA_KEY);
if (!data) {
data = new Button(this);
$(this).data(DATA_KEY, data);
}
if (config === 'toggle') {
data[config]();
}
});
}
}, {
key: 'VERSION',
get: function get() {
return VERSION;
}
}]);
return Button;
})();
$(document).on(Event.CLICK_DATA_API, Selector.DATA_TOGGLE_CARROT, function (event) {
event.preventDefault();
var button = event.target;
if (!$(button).hasClass(ClassName.BUTTON)) {
button = $(button).closest(Selector.BUTTON);
}
Button._jQueryInterface.call($(button), 'toggle');
}).on(Event.FOCUS_BLUR_DATA_API, Selector.DATA_TOGGLE_CARROT, function (event) {
var button = $(event.target).closest(Selector.BUTTON)[0];
$(button).toggleClass(ClassName.FOCUS, /^focus(in)?$/.test(event.type));
});
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
$.fn[NAME] = Button._jQueryInterface;
$.fn[NAME].Constructor = Button;
$.fn[NAME].noConflict = function () {
$.fn[NAME] = JQUERY_NO_CONFLICT;
return Button._jQueryInterface;
};
return Button;
})(jQuery);
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.0.0): carousel.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
var Carousel = (function ($) {
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
var NAME = 'carousel';
var VERSION = '4.0.0';
var DATA_KEY = 'bs.carousel';
var EVENT_KEY = '.' + DATA_KEY;
var DATA_API_KEY = '.data-api';
var JQUERY_NO_CONFLICT = $.fn[NAME];
var TRANSITION_DURATION = 600;
var Default = {
interval: 5000,
keyboard: true,
slide: false,
pause: 'hover',
wrap: true
};
var DefaultType = {
interval: '(number|boolean)',
keyboard: 'boolean',
slide: '(boolean|string)',
pause: '(string|boolean)',
wrap: 'boolean'
};
var Direction = {
NEXT: 'next',
PREVIOUS: 'prev'
};
var Event = {
SLIDE: 'slide' + EVENT_KEY,
SLID: 'slid' + EVENT_KEY,
KEYDOWN: 'keydown' + EVENT_KEY,
MOUSEENTER: 'mouseenter' + EVENT_KEY,
MOUSELEAVE: 'mouseleave' + EVENT_KEY,
LOAD_DATA_API: 'load' + EVENT_KEY + DATA_API_KEY,
CLICK_DATA_API: 'click' + EVENT_KEY + DATA_API_KEY
};
var ClassName = {
CAROUSEL: 'carousel',
ACTIVE: 'active',
SLIDE: 'slide',
RIGHT: 'right',
LEFT: 'left',
ITEM: 'carousel-item'
};
var Selector = {
ACTIVE: '.active',
ACTIVE_ITEM: '.active.carousel-item',
ITEM: '.carousel-item',
NEXT_PREV: '.next, .prev',
INDICATORS: '.carousel-indicators',
DATA_SLIDE: '[data-slide], [data-slide-to]',
DATA_RIDE: '[data-ride="carousel"]'
};
/**
* ------------------------------------------------------------------------
* Class Definition
* ------------------------------------------------------------------------
*/
var Carousel = (function () {
function Carousel(element, config) {
_classCallCheck(this, Carousel);
this._items = null;
this._interval = null;
this._activeElement = null;
this._isPaused = false;
this._isSliding = false;
this._config = this._getConfig(config);
this._element = $(element)[0];
this._indicatorsElement = $(this._element).find(Selector.INDICATORS)[0];
this._addEventListeners();
}
/**
* ------------------------------------------------------------------------
* Data Api implementation
* ------------------------------------------------------------------------
*/
// getters
_createClass(Carousel, [{
key: 'next',
// public
value: function next() {
if (!this._isSliding) {
this._slide(Direction.NEXT);
}
}
}, {
key: 'nextWhenVisible',
value: function nextWhenVisible() {
// Don't call next when the page isn't visible
if (!document.hidden) {
this.next();
}
}
}, {
key: 'prev',
value: function prev() {
if (!this._isSliding) {
this._slide(Direction.PREVIOUS);
}
}
}, {
key: 'pause',
value: function pause(event) {
if (!event) {
this._isPaused = true;
}
if ($(this._element).find(Selector.NEXT_PREV)[0] && Util.supportsTransitionEnd()) {
Util.triggerTransitionEnd(this._element);
this.cycle(true);
}
clearInterval(this._interval);
this._interval = null;
}
}, {
key: 'cycle',
value: function cycle(event) {
if (!event) {
this._isPaused = false;
}
if (this._interval) {
clearInterval(this._interval);
this._interval = null;
}
if (this._config.interval && !this._isPaused) {
this._interval = setInterval($.proxy(document.visibilityState ? this.nextWhenVisible : this.next, this), this._config.interval);
}
}
}, {
key: 'to',
value: function to(index) {
var _this2 = this;
this._activeElement = $(this._element).find(Selector.ACTIVE_ITEM)[0];
var activeIndex = this._getItemIndex(this._activeElement);
if (index > this._items.length - 1 || index < 0) {
return;
}
if (this._isSliding) {
$(this._element).one(Event.SLID, function () {
return _this2.to(index);
});
return;
}
if (activeIndex === index) {
this.pause();
this.cycle();
return;
}
var direction = index > activeIndex ? Direction.NEXT : Direction.PREVIOUS;
this._slide(direction, this._items[index]);
}
}, {
key: 'dispose',
value: function dispose() {
$(this._element).off(EVENT_KEY);
$.removeData(this._element, DATA_KEY);
this._items = null;
this._config = null;
this._element = null;
this._interval = null;
this._isPaused = null;
this._isSliding = null;
this._activeElement = null;
this._indicatorsElement = null;
}
// private
}, {
key: '_getConfig',
value: function _getConfig(config) {
config = $.extend({}, Default, config);
Util.typeCheckConfig(NAME, config, DefaultType);
return config;
}
}, {
key: '_addEventListeners',
value: function _addEventListeners() {
if (this._config.keyboard) {
$(this._element).on(Event.KEYDOWN, $.proxy(this._keydown, this));
}
if (this._config.pause === 'hover' && !('ontouchstart' in document.documentElement)) {
$(this._element).on(Event.MOUSEENTER, $.proxy(this.pause, this)).on(Event.MOUSELEAVE, $.proxy(this.cycle, this));
}
}
}, {
key: '_keydown',
value: function _keydown(event) {
event.preventDefault();
if (/input|textarea/i.test(event.target.tagName)) {
return;
}
switch (event.which) {
case 37:
this.prev();break;
case 39:
this.next();break;
default:
return;
}
}
}, {
key: '_getItemIndex',
value: function _getItemIndex(element) {
this._items = $.makeArray($(element).parent().find(Selector.ITEM));
return this._items.indexOf(element);
}
}, {
key: '_getItemByDirection',
value: function _getItemByDirection(direction, activeElement) {
var isNextDirection = direction === Direction.NEXT;
var isPrevDirection = direction === Direction.PREVIOUS;
var activeIndex = this._getItemIndex(activeElement);
var lastItemIndex = this._items.length - 1;
var isGoingToWrap = isPrevDirection && activeIndex === 0 || isNextDirection && activeIndex === lastItemIndex;
if (isGoingToWrap && !this._config.wrap) {
return activeElement;
}
var delta = direction === Direction.PREVIOUS ? -1 : 1;
var itemIndex = (activeIndex + delta) % this._items.length;
return itemIndex === -1 ? this._items[this._items.length - 1] : this._items[itemIndex];
}
}, {
key: '_triggerSlideEvent',
value: function _triggerSlideEvent(relatedTarget, directionalClassname) {
var slideEvent = $.Event(Event.SLIDE, {
relatedTarget: relatedTarget,
direction: directionalClassname
});
$(this._element).trigger(slideEvent);
return slideEvent;
}
}, {
key: '_setActiveIndicatorElement',
value: function _setActiveIndicatorElement(element) {
if (this._indicatorsElement) {
$(this._indicatorsElement).find(Selector.ACTIVE).removeClass(ClassName.ACTIVE);
var nextIndicator = this._indicatorsElement.children[this._getItemIndex(element)];
if (nextIndicator) {
$(nextIndicator).addClass(ClassName.ACTIVE);
}
}
}
}, {
key: '_slide',
value: function _slide(direction, element) {
var _this3 = this;
var activeElement = $(this._element).find(Selector.ACTIVE_ITEM)[0];
var nextElement = element || activeElement && this._getItemByDirection(direction, activeElement);
var isCycling = Boolean(this._interval);
var directionalClassName = direction === Direction.NEXT ? ClassName.LEFT : ClassName.RIGHT;
if (nextElement && $(nextElement).hasClass(ClassName.ACTIVE)) {
this._isSliding = false;
return;
}
var slideEvent = this._triggerSlideEvent(nextElement, directionalClassName);
if (slideEvent.isDefaultPrevented()) {
return;
}
if (!activeElement || !nextElement) {
// some weirdness is happening, so we bail
return;
}
this._isSliding = true;
if (isCycling) {
this.pause();
}
this._setActiveIndicatorElement(nextElement);
var slidEvent = $.Event(Event.SLID, {
relatedTarget: nextElement,
direction: directionalClassName
});
if (Util.supportsTransitionEnd() && $(this._element).hasClass(ClassName.SLIDE)) {
$(nextElement).addClass(direction);
Util.reflow(nextElement);
$(activeElement).addClass(directionalClassName);
$(nextElement).addClass(directionalClassName);
$(activeElement).one(Util.TRANSITION_END, function () {
$(nextElement).removeClass(directionalClassName).removeClass(direction);
$(nextElement).addClass(ClassName.ACTIVE);
$(activeElement).removeClass(ClassName.ACTIVE).removeClass(direction).removeClass(directionalClassName);
_this3._isSliding = false;
setTimeout(function () {
return $(_this3._element).trigger(slidEvent);
}, 0);
}).emulateTransitionEnd(TRANSITION_DURATION);
} else {
$(activeElement).removeClass(ClassName.ACTIVE);
$(nextElement).addClass(ClassName.ACTIVE);
this._isSliding = false;
$(this._element).trigger(slidEvent);
}
if (isCycling) {
this.cycle();
}
}
// static
}], [{
key: '_jQueryInterface',
value: function _jQueryInterface(config) {
return this.each(function () {
var data = $(this).data(DATA_KEY);
var _config = $.extend({}, Default, $(this).data());
if (typeof config === 'object') {
$.extend(_config, config);
}
var action = typeof config === 'string' ? config : _config.slide;
if (!data) {
data = new Carousel(this, _config);
$(this).data(DATA_KEY, data);
}
if (typeof config === 'number') {
data.to(config);
} else if (typeof action === 'string') {
if (data[action] === undefined) {
throw new Error('No method named "' + action + '"');
}
data[action]();
} else if (_config.interval) {
data.pause();
data.cycle();
}
});
}
}, {
key: '_dataApiClickHandler',
value: function _dataApiClickHandler(event) {
var selector = Util.getSelectorFromElement(this);
if (!selector) {
return;
}
var target = $(selector)[0];
if (!target || !$(target).hasClass(ClassName.CAROUSEL)) {
return;
}
var config = $.extend({}, $(target).data(), $(this).data());
var slideIndex = this.getAttribute('data-slide-to');
if (slideIndex) {
config.interval = false;
}
Carousel._jQueryInterface.call($(target), config);
if (slideIndex) {
$(target).data(DATA_KEY).to(slideIndex);
}
event.preventDefault();
}
}, {
key: 'VERSION',
get: function get() {
return VERSION;
}
}, {
key: 'Default',
get: function get() {
return Default;
}
}]);
return Carousel;
})();
$(document).on(Event.CLICK_DATA_API, Selector.DATA_SLIDE, Carousel._dataApiClickHandler);
$(window).on(Event.LOAD_DATA_API, function () {
$(Selector.DATA_RIDE).each(function () {
var $carousel = $(this);
Carousel._jQueryInterface.call($carousel, $carousel.data());
});
});
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
$.fn[NAME] = Carousel._jQueryInterface;
$.fn[NAME].Constructor = Carousel;
$.fn[NAME].noConflict = function () {
$.fn[NAME] = JQUERY_NO_CONFLICT;
return Carousel._jQueryInterface;
};
return Carousel;
})(jQuery);
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.0.0): collapse.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
var Collapse = (function ($) {
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
var NAME = 'collapse';
var VERSION = '4.0.0';
var DATA_KEY = 'bs.collapse';
var EVENT_KEY = '.' + DATA_KEY;
var DATA_API_KEY = '.data-api';
var JQUERY_NO_CONFLICT = $.fn[NAME];
var TRANSITION_DURATION = 600;
var Default = {
toggle: true,
parent: ''
};
var DefaultType = {
toggle: 'boolean',
parent: 'string'
};
var Event = {
SHOW: 'show' + EVENT_KEY,
SHOWN: 'shown' + EVENT_KEY,
HIDE: 'hide' + EVENT_KEY,
HIDDEN: 'hidden' + EVENT_KEY,
CLICK_DATA_API: 'click' + EVENT_KEY + DATA_API_KEY
};
var ClassName = {
IN: 'in',
COLLAPSE: 'collapse',
COLLAPSING: 'collapsing',
COLLAPSED: 'collapsed'
};
var Dimension = {
WIDTH: 'width',
HEIGHT: 'height'
};
var Selector = {
ACTIVES: '.panel > .in, .panel > .collapsing',
DATA_TOGGLE: '[data-toggle="collapse"]'
};
/**
* ------------------------------------------------------------------------
* Class Definition
* ------------------------------------------------------------------------
*/
var Collapse = (function () {
function Collapse(element, config) {
_classCallCheck(this, Collapse);
this._isTransitioning = false;
this._element = element;
this._config = this._getConfig(config);
this._triggerArray = $.makeArray($('[data-toggle="collapse"][href="#' + element.id + '"],' + ('[data-toggle="collapse"][data-target="#' + element.id + '"]')));
this._parent = this._config.parent ? this._getParent() : null;
if (!this._config.parent) {
this._addAriaAndCollapsedClass(this._element, this._triggerArray);
}
if (this._config.toggle) {
this.toggle();
}
}
/**
* ------------------------------------------------------------------------
* Data Api implementation
* ------------------------------------------------------------------------
*/
// getters
_createClass(Collapse, [{
key: 'toggle',
// public
value: function toggle() {
if ($(this._element).hasClass(ClassName.IN)) {
this.hide();
} else {
this.show();
}
}
}, {
key: 'show',
value: function show() {
var _this4 = this;
if (this._isTransitioning || $(this._element).hasClass(ClassName.IN)) {
return;
}
var actives = undefined;
var activesData = undefined;
if (this._parent) {
actives = $.makeArray($(Selector.ACTIVES));
if (!actives.length) {
actives = null;
}
}
if (actives) {
activesData = $(actives).data(DATA_KEY);
if (activesData && activesData._isTransitioning) {
return;
}
}
var startEvent = $.Event(Event.SHOW);
$(this._element).trigger(startEvent);
if (startEvent.isDefaultPrevented()) {
return;
}
if (actives) {
Collapse._jQueryInterface.call($(actives), 'hide');
if (!activesData) {
$(actives).data(DATA_KEY, null);
}
}
var dimension = this._getDimension();
$(this._element).removeClass(ClassName.COLLAPSE).addClass(ClassName.COLLAPSING);
this._element.style[dimension] = 0;
this._element.setAttribute('aria-expanded', true);
if (this._triggerArray.length) {
$(this._triggerArray).removeClass(ClassName.COLLAPSED).attr('aria-expanded', true);
}
this.setTransitioning(true);
var complete = function complete() {
$(_this4._element).removeClass(ClassName.COLLAPSING).addClass(ClassName.COLLAPSE).addClass(ClassName.IN);
_this4._element.style[dimension] = '';
_this4.setTransitioning(false);
$(_this4._element).trigger(Event.SHOWN);
};
if (!Util.supportsTransitionEnd()) {
complete();
return;
}
var capitalizedDimension = dimension[0].toUpperCase() + dimension.slice(1);
var scrollSize = 'scroll' + capitalizedDimension;
$(this._element).one(Util.TRANSITION_END, complete).emulateTransitionEnd(TRANSITION_DURATION);
this._element.style[dimension] = this._element[scrollSize] + 'px';
}
}, {
key: 'hide',
value: function hide() {
var _this5 = this;
if (this._isTransitioning || !$(this._element).hasClass(ClassName.IN)) {
return;
}
var startEvent = $.Event(Event.HIDE);
$(this._element).trigger(startEvent);
if (startEvent.isDefaultPrevented()) {
return;
}
var dimension = this._getDimension();
var offsetDimension = dimension === Dimension.WIDTH ? 'offsetWidth' : 'offsetHeight';
this._element.style[dimension] = this._element[offsetDimension] + 'px';
Util.reflow(this._element);
$(this._element).addClass(ClassName.COLLAPSING).removeClass(ClassName.COLLAPSE).removeClass(ClassName.IN);
this._element.setAttribute('aria-expanded', false);
if (this._triggerArray.length) {
$(this._triggerArray).addClass(ClassName.COLLAPSED).attr('aria-expanded', false);
}
this.setTransitioning(true);
var complete = function complete() {
_this5.setTransitioning(false);
$(_this5._element).removeClass(ClassName.COLLAPSING).addClass(ClassName.COLLAPSE).trigger(Event.HIDDEN);
};
this._element.style[dimension] = 0;
if (!Util.supportsTransitionEnd()) {
complete();
return;
}
$(this._element).one(Util.TRANSITION_END, complete).emulateTransitionEnd(TRANSITION_DURATION);
}
}, {
key: 'setTransitioning',
value: function setTransitioning(isTransitioning) {
this._isTransitioning = isTransitioning;
}
}, {
key: 'dispose',
value: function dispose() {
$.removeData(this._element, DATA_KEY);
this._config = null;
this._parent = null;
this._element = null;
this._triggerArray = null;
this._isTransitioning = null;
}
// private
}, {
key: '_getConfig',
value: function _getConfig(config) {
config = $.extend({}, Default, config);
config.toggle = Boolean(config.toggle); // coerce string values
Util.typeCheckConfig(NAME, config, DefaultType);
return config;
}
}, {
key: '_getDimension',
value: function _getDimension() {
var hasWidth = $(this._element).hasClass(Dimension.WIDTH);
return hasWidth ? Dimension.WIDTH : Dimension.HEIGHT;
}
}, {
key: '_getParent',
value: function _getParent() {
var _this6 = this;
var parent = $(this._config.parent)[0];
var selector = '[data-toggle="collapse"][data-parent="' + this._config.parent + '"]';
$(parent).find(selector).each(function (i, element) {
_this6._addAriaAndCollapsedClass(Collapse._getTargetFromElement(element), [element]);
});
return parent;
}
}, {
key: '_addAriaAndCollapsedClass',
value: function _addAriaAndCollapsedClass(element, triggerArray) {
if (element) {
var isOpen = $(element).hasClass(ClassName.IN);
element.setAttribute('aria-expanded', isOpen);
if (triggerArray.length) {
$(triggerArray).toggleClass(ClassName.COLLAPSED, !isOpen).attr('aria-expanded', isOpen);
}
}
}
// static
}], [{
key: '_getTargetFromElement',
value: function _getTargetFromElement(element) {
var selector = Util.getSelectorFromElement(element);
return selector ? $(selector)[0] : null;
}
}, {
key: '_jQueryInterface',
value: function _jQueryInterface(config) {
return this.each(function () {
var $this = $(this);
var data = $this.data(DATA_KEY);
var _config = $.extend({}, Default, $this.data(), typeof config === 'object' && config);
if (!data && _config.toggle && /show|hide/.test(config)) {
_config.toggle = false;
}
if (!data) {
data = new Collapse(this, _config);
$this.data(DATA_KEY, data);
}
if (typeof config === 'string') {
if (data[config] === undefined) {
throw new Error('No method named "' + config + '"');
}
data[config]();
}
});
}
}, {
key: 'VERSION',
get: function get() {
return VERSION;
}
}, {
key: 'Default',
get: function get() {
return Default;
}
}]);
return Collapse;
})();
$(document).on(Event.CLICK_DATA_API, Selector.DATA_TOGGLE, function (event) {
event.preventDefault();
var target = Collapse._getTargetFromElement(this);
var data = $(target).data(DATA_KEY);
var config = data ? 'toggle' : $(this).data();
Collapse._jQueryInterface.call($(target), config);
});
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
$.fn[NAME] = Collapse._jQueryInterface;
$.fn[NAME].Constructor = Collapse;
$.fn[NAME].noConflict = function () {
$.fn[NAME] = JQUERY_NO_CONFLICT;
return Collapse._jQueryInterface;
};
return Collapse;
})(jQuery);
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.0.0): dropdown.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
var Dropdown = (function ($) {
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
var NAME = 'dropdown';
var VERSION = '4.0.0';
var DATA_KEY = 'bs.dropdown';
var EVENT_KEY = '.' + DATA_KEY;
var DATA_API_KEY = '.data-api';
var JQUERY_NO_CONFLICT = $.fn[NAME];
var Event = {
HIDE: 'hide' + EVENT_KEY,
HIDDEN: 'hidden' + EVENT_KEY,
SHOW: 'show' + EVENT_KEY,
SHOWN: 'shown' + EVENT_KEY,
CLICK: 'click' + EVENT_KEY,
CLICK_DATA_API: 'click' + EVENT_KEY + DATA_API_KEY,
KEYDOWN_DATA_API: 'keydown' + EVENT_KEY + DATA_API_KEY
};
var ClassName = {
BACKDROP: 'dropdown-backdrop',
DISABLED: 'disabled',
OPEN: 'open'
};
var Selector = {
BACKDROP: '.dropdown-backdrop',
DATA_TOGGLE: '[data-toggle="dropdown"]',
FORM_CHILD: '.dropdown form',
ROLE_MENU: '[role="menu"]',
ROLE_LISTBOX: '[role="listbox"]',
NAVBAR_NAV: '.navbar-nav',
VISIBLE_ITEMS: '[role="menu"] li:not(.disabled) a, ' + '[role="listbox"] li:not(.disabled) a'
};
/**
* ------------------------------------------------------------------------
* Class Definition
* ------------------------------------------------------------------------
*/
var Dropdown = (function () {
function Dropdown(element) {
_classCallCheck(this, Dropdown);
this._element = element;
this._addEventListeners();
}
/**
* ------------------------------------------------------------------------
* Data Api implementation
* ------------------------------------------------------------------------
*/
// getters
_createClass(Dropdown, [{
key: 'toggle',
// public
value: function toggle() {
if (this.disabled || $(this).hasClass(ClassName.DISABLED)) {
return false;
}
var parent = Dropdown._getParentFromElement(this);
var isActive = $(parent).hasClass(ClassName.OPEN);
Dropdown._clearMenus();
if (isActive) {
return false;
}
if ('ontouchstart' in document.documentElement && !$(parent).closest(Selector.NAVBAR_NAV).length) {
// if mobile we use a backdrop because click events don't delegate
var dropdown = document.createElement('div');
dropdown.className = ClassName.BACKDROP;
$(dropdown).insertBefore(this);
$(dropdown).on('click', Dropdown._clearMenus);
}
var relatedTarget = { relatedTarget: this };
var showEvent = $.Event(Event.SHOW, relatedTarget);
$(parent).trigger(showEvent);
if (showEvent.isDefaultPrevented()) {
return false;
}
this.focus();
this.setAttribute('aria-expanded', 'true');
$(parent).toggleClass(ClassName.OPEN);
$(parent).trigger($.Event(Event.SHOWN, relatedTarget));
return false;
}
}, {
key: 'dispose',
value: function dispose() {
$.removeData(this._element, DATA_KEY);
$(this._element).off(EVENT_KEY);
this._element = null;
}
// private
}, {
key: '_addEventListeners',
value: function _addEventListeners() {
$(this._element).on(Event.CLICK, this.toggle);
}
// static
}], [{
key: '_jQueryInterface',
value: function _jQueryInterface(config) {
return this.each(function () {
var data = $(this).data(DATA_KEY);
if (!data) {
$(this).data(DATA_KEY, data = new Dropdown(this));
}
if (typeof config === 'string') {
if (data[config] === undefined) {
throw new Error('No method named "' + config + '"');
}
data[config].call(this);
}
});
}
}, {
key: '_clearMenus',
value: function _clearMenus(event) {
if (event && event.which === 3) {
return;
}
var backdrop = $(Selector.BACKDROP)[0];
if (backdrop) {
backdrop.parentNode.removeChild(backdrop);
}
var toggles = $.makeArray($(Selector.DATA_TOGGLE));
for (var i = 0; i < toggles.length; i++) {
var _parent = Dropdown._getParentFromElement(toggles[i]);
var relatedTarget = { relatedTarget: toggles[i] };
if (!$(_parent).hasClass(ClassName.OPEN)) {
continue;
}
if (event && event.type === 'click' && /input|textarea/i.test(event.target.tagName) && $.contains(_parent, event.target)) {
continue;
}
var hideEvent = $.Event(Event.HIDE, relatedTarget);
$(_parent).trigger(hideEvent);
if (hideEvent.isDefaultPrevented()) {
continue;
}
toggles[i].setAttribute('aria-expanded', 'false');
$(_parent).removeClass(ClassName.OPEN).trigger($.Event(Event.HIDDEN, relatedTarget));
}
}
}, {
key: '_getParentFromElement',
value: function _getParentFromElement(element) {
var parent = undefined;
var selector = Util.getSelectorFromElement(element);
if (selector) {
parent = $(selector)[0];
}
return parent || element.parentNode;
}
}, {
key: '_dataApiKeydownHandler',
value: function _dataApiKeydownHandler(event) {
if (!/(38|40|27|32)/.test(event.which) || /input|textarea/i.test(event.target.tagName)) {
return;
}
event.preventDefault();
event.stopPropagation();
if (this.disabled || $(this).hasClass(ClassName.DISABLED)) {
return;
}
var parent = Dropdown._getParentFromElement(this);
var isActive = $(parent).hasClass(ClassName.OPEN);
if (!isActive && event.which !== 27 || isActive && event.which === 27) {
if (event.which === 27) {
var toggle = $(parent).find(Selector.DATA_TOGGLE)[0];
$(toggle).trigger('focus');
}
$(this).trigger('click');
return;
}
var items = $.makeArray($(Selector.VISIBLE_ITEMS));
items = items.filter(function (item) {
return item.offsetWidth || item.offsetHeight;
});
if (!items.length) {
return;
}
var index = items.indexOf(event.target);
if (event.which === 38 && index > 0) {
// up
index--;
}
if (event.which === 40 && index < items.length - 1) {
// down
index++;
}
if (! ~index) {
index = 0;
}
items[index].focus();
}
}, {
key: 'VERSION',
get: function get() {
return VERSION;
}
}]);
return Dropdown;
})();
$(document).on(Event.KEYDOWN_DATA_API, Selector.DATA_TOGGLE, Dropdown._dataApiKeydownHandler).on(Event.KEYDOWN_DATA_API, Selector.ROLE_MENU, Dropdown._dataApiKeydownHandler).on(Event.KEYDOWN_DATA_API, Selector.ROLE_LISTBOX, Dropdown._dataApiKeydownHandler).on(Event.CLICK_DATA_API, Dropdown._clearMenus).on(Event.CLICK_DATA_API, Selector.DATA_TOGGLE, Dropdown.prototype.toggle).on(Event.CLICK_DATA_API, Selector.FORM_CHILD, function (e) {
e.stopPropagation();
});
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
$.fn[NAME] = Dropdown._jQueryInterface;
$.fn[NAME].Constructor = Dropdown;
$.fn[NAME].noConflict = function () {
$.fn[NAME] = JQUERY_NO_CONFLICT;
return Dropdown._jQueryInterface;
};
return Dropdown;
})(jQuery);
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.0.0): modal.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
var Modal = (function ($) {
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
var NAME = 'modal';
var VERSION = '4.0.0';
var DATA_KEY = 'bs.modal';
var EVENT_KEY = '.' + DATA_KEY;
var DATA_API_KEY = '.data-api';
var JQUERY_NO_CONFLICT = $.fn[NAME];
var TRANSITION_DURATION = 300;
var BACKDROP_TRANSITION_DURATION = 150;
var Default = {
backdrop: true,
keyboard: true,
focus: true,
show: true
};
var DefaultType = {
backdrop: '(boolean|string)',
keyboard: 'boolean',
focus: 'boolean',
show: 'boolean'
};
var Event = {
HIDE: 'hide' + EVENT_KEY,
HIDDEN: 'hidden' + EVENT_KEY,
SHOW: 'show' + EVENT_KEY,
SHOWN: 'shown' + EVENT_KEY,
FOCUSIN: 'focusin' + EVENT_KEY,
RESIZE: 'resize' + EVENT_KEY,
CLICK_DISMISS: 'click.dismiss' + EVENT_KEY,
KEYDOWN_DISMISS: 'keydown.dismiss' + EVENT_KEY,
MOUSEUP_DISMISS: 'mouseup.dismiss' + EVENT_KEY,
MOUSEDOWN_DISMISS: 'mousedown.dismiss' + EVENT_KEY,
CLICK_DATA_API: 'click' + EVENT_KEY + DATA_API_KEY
};
var ClassName = {
SCROLLBAR_MEASURER: 'modal-scrollbar-measure',
BACKDROP: 'modal-backdrop',
OPEN: 'modal-open',
FADE: 'fade',
IN: 'in'
};
var Selector = {
DIALOG: '.modal-dialog',
DATA_TOGGLE: '[data-toggle="modal"]',
DATA_DISMISS: '[data-dismiss="modal"]',
FIXED_CONTENT: '.navbar-fixed-top, .navbar-fixed-bottom, .is-fixed'
};
/**
* ------------------------------------------------------------------------
* Class Definition
* ------------------------------------------------------------------------
*/
var Modal = (function () {
function Modal(element, config) {
_classCallCheck(this, Modal);
this._config = this._getConfig(config);
this._element = element;
this._dialog = $(element).find(Selector.DIALOG)[0];
this._backdrop = null;
this._isShown = false;
this._isBodyOverflowing = false;
this._ignoreBackdropClick = false;
this._originalBodyPadding = 0;
this._scrollbarWidth = 0;
}
/**
* ------------------------------------------------------------------------
* Data Api implementation
* ------------------------------------------------------------------------
*/
// getters
_createClass(Modal, [{
key: 'toggle',
// public
value: function toggle(relatedTarget) {
return this._isShown ? this.hide() : this.show(relatedTarget);
}
}, {
key: 'show',
value: function show(relatedTarget) {
var _this7 = this;
var showEvent = $.Event(Event.SHOW, {
relatedTarget: relatedTarget
});
$(this._element).trigger(showEvent);
if (this._isShown || showEvent.isDefaultPrevented()) {
return;
}
this._isShown = true;
this._checkScrollbar();
this._setScrollbar();
$(document.body).addClass(ClassName.OPEN);
this._setEscapeEvent();
this._setResizeEvent();
$(this._element).on(Event.CLICK_DISMISS, Selector.DATA_DISMISS, $.proxy(this.hide, this));
$(this._dialog).on(Event.MOUSEDOWN_DISMISS, function () {
$(_this7._element).one(Event.MOUSEUP_DISMISS, function (event) {
if ($(event.target).is(_this7._element)) {
that._ignoreBackdropClick = true;
}
});
});
this._showBackdrop($.proxy(this._showElement, this, relatedTarget));
}
}, {
key: 'hide',
value: function hide(event) {
if (event) {
event.preventDefault();
}
var hideEvent = $.Event(Event.HIDE);
$(this._element).trigger(hideEvent);
if (!this._isShown || hideEvent.isDefaultPrevented()) {
return;
}
this._isShown = false;
this._setEscapeEvent();
this._setResizeEvent();
$(document).off(Event.FOCUSIN);
$(this._element).removeClass(ClassName.IN);
$(this._element).off(Event.CLICK_DISMISS);
$(this._dialog).off(Event.MOUSEDOWN_DISMISS);
if (Util.supportsTransitionEnd() && $(this._element).hasClass(ClassName.FADE)) {
$(this._element).one(Util.TRANSITION_END, $.proxy(this._hideModal, this)).emulateTransitionEnd(TRANSITION_DURATION);
} else {
this._hideModal();
}
}
}, {
key: 'dispose',
value: function dispose() {
$.removeData(this._element, DATA_KEY);
$(window).off(EVENT_KEY);
$(document).off(EVENT_KEY);
$(this._element).off(EVENT_KEY);
$(this._backdrop).off(EVENT_KEY);
this._config = null;
this._element = null;
this._dialog = null;
this._backdrop = null;
this._isShown = null;
this._isBodyOverflowing = null;
this._ignoreBackdropClick = null;
this._originalBodyPadding = null;
this._scrollbarWidth = null;
}
// private
}, {
key: '_getConfig',
value: function _getConfig(config) {
config = $.extend({}, Default, config);
Util.typeCheckConfig(NAME, config, DefaultType);
return config;
}
}, {
key: '_showElement',
value: function _showElement(relatedTarget) {
var _this8 = this;
var transition = Util.supportsTransitionEnd() && $(this._element).hasClass(ClassName.FADE);
if (!this._element.parentNode || this._element.parentNode.nodeType !== Node.ELEMENT_NODE) {
// don't move modals dom position
document.body.appendChild(this._element);
}
this._element.style.display = 'block';
this._element.scrollTop = 0;
if (transition) {
Util.reflow(this._element);
}
$(this._element).addClass(ClassName.IN);
if (this._config.focus) {
this._enforceFocus();
}
var shownEvent = $.Event(Event.SHOWN, {
relatedTarget: relatedTarget
});
var transitionComplete = function transitionComplete() {
if (_this8._config.focus) {
_this8._element.focus();
}
$(_this8._element).trigger(shownEvent);
};
if (transition) {
$(this._dialog).one(Util.TRANSITION_END, transitionComplete).emulateTransitionEnd(TRANSITION_DURATION);
} else {
transitionComplete();
}
}
}, {
key: '_enforceFocus',
value: function _enforceFocus() {
var _this9 = this;
$(document).off(Event.FOCUSIN) // guard against infinite focus loop
.on(Event.FOCUSIN, function (event) {
if (_this9._element !== event.target && !$(_this9._element).has(event.target).length) {
_this9._element.focus();
}
});
}
}, {
key: '_setEscapeEvent',
value: function _setEscapeEvent() {
var _this10 = this;
if (this._isShown && this._config.keyboard) {
$(this._element).on(Event.KEYDOWN_DISMISS, function (event) {
if (event.which === 27) {
_this10.hide();
}
});
} else if (!this._isShown) {
$(this._element).off(Event.KEYDOWN_DISMISS);
}
}
}, {
key: '_setResizeEvent',
value: function _setResizeEvent() {
if (this._isShown) {
$(window).on(Event.RESIZE, $.proxy(this._handleUpdate, this));
} else {
$(window).off(Event.RESIZE);
}
}
}, {
key: '_hideModal',
value: function _hideModal() {
var _this11 = this;
this._element.style.display = 'none';
this._showBackdrop(function () {
$(document.body).removeClass(ClassName.OPEN);
_this11._resetAdjustments();
_this11._resetScrollbar();
$(_this11._element).trigger(Event.HIDDEN);
});
}
}, {
key: '_removeBackdrop',
value: function _removeBackdrop() {
if (this._backdrop) {
$(this._backdrop).remove();
this._backdrop = null;
}
}
}, {
key: '_showBackdrop',
value: function _showBackdrop(callback) {
var _this12 = this;
var animate = $(this._element).hasClass(ClassName.FADE) ? ClassName.FADE : '';
if (this._isShown && this._config.backdrop) {
var doAnimate = Util.supportsTransitionEnd() && animate;
this._backdrop = document.createElement('div');
this._backdrop.className = ClassName.BACKDROP;
if (animate) {
$(this._backdrop).addClass(animate);
}
$(this._backdrop).appendTo(document.body);
$(this._element).on(Event.CLICK_DISMISS, function (event) {
if (_this12._ignoreBackdropClick) {
_this12._ignoreBackdropClick = false;
return;
}
if (event.target !== event.currentTarget) {
return;
}
if (_this12._config.backdrop === 'static') {
_this12._element.focus();
} else {
_this12.hide();
}
});
if (doAnimate) {
Util.reflow(this._backdrop);
}
$(this._backdrop).addClass(ClassName.IN);
if (!callback) {
return;
}
if (!doAnimate) {
callback();
return;
}
$(this._backdrop).one(Util.TRANSITION_END, callback).emulateTransitionEnd(BACKDROP_TRANSITION_DURATION);
} else if (!this._isShown && this._backdrop) {
$(this._backdrop).removeClass(ClassName.IN);
var callbackRemove = function callbackRemove() {
_this12._removeBackdrop();
if (callback) {
callback();
}
};
if (Util.supportsTransitionEnd() && $(this._element).hasClass(ClassName.FADE)) {
$(this._backdrop).one(Util.TRANSITION_END, callbackRemove).emulateTransitionEnd(BACKDROP_TRANSITION_DURATION);
} else {
callbackRemove();
}
} else if (callback) {
callback();
}
}
// ----------------------------------------------------------------------
// the following methods are used to handle overflowing modals
// todo (fat): these should probably be refactored out of modal.js
// ----------------------------------------------------------------------
}, {
key: '_handleUpdate',
value: function _handleUpdate() {
this._adjustDialog();
}
}, {
key: '_adjustDialog',
value: function _adjustDialog() {
var isModalOverflowing = this._element.scrollHeight > document.documentElement.clientHeight;
if (!this._isBodyOverflowing && isModalOverflowing) {
this._element.style.paddingLeft = this._scrollbarWidth + 'px';
}
if (this._isBodyOverflowing && !isModalOverflowing) {
this._element.style.paddingRight = this._scrollbarWidth + 'px~';
}
}
}, {
key: '_resetAdjustments',
value: function _resetAdjustments() {
this._element.style.paddingLeft = '';
this._element.style.paddingRight = '';
}
}, {
key: '_checkScrollbar',
value: function _checkScrollbar() {
var fullWindowWidth = window.innerWidth;
if (!fullWindowWidth) {
// workaround for missing window.innerWidth in IE8
var documentElementRect = document.documentElement.getBoundingClientRect();
fullWindowWidth = documentElementRect.right - Math.abs(documentElementRect.left);
}
this._isBodyOverflowing = document.body.clientWidth < fullWindowWidth;
this._scrollbarWidth = this._getScrollbarWidth();
}
}, {
key: '_setScrollbar',
value: function _setScrollbar() {
var bodyPadding = parseInt($(Selector.FIXED_CONTENT).css('padding-right') || 0, 10);
this._originalBodyPadding = document.body.style.paddingRight || '';
if (this._isBodyOverflowing) {
document.body.style.paddingRight = bodyPadding + this._scrollbarWidth + 'px';
}
}
}, {
key: '_resetScrollbar',
value: function _resetScrollbar() {
document.body.style.paddingRight = this._originalBodyPadding;
}
}, {
key: '_getScrollbarWidth',
value: function _getScrollbarWidth() {
// thx d.walsh
var scrollDiv = document.createElement('div');
scrollDiv.className = ClassName.SCROLLBAR_MEASURER;
document.body.appendChild(scrollDiv);
var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;
document.body.removeChild(scrollDiv);
return scrollbarWidth;
}
// static
}], [{
key: '_jQueryInterface',
value: function _jQueryInterface(config, relatedTarget) {
return this.each(function () {
var data = $(this).data(DATA_KEY);
var _config = $.extend({}, Modal.Default, $(this).data(), typeof config === 'object' && config);
if (!data) {
data = new Modal(this, _config);
$(this).data(DATA_KEY, data);
}
if (typeof config === 'string') {
if (data[config] === undefined) {
throw new Error('No method named "' + config + '"');
}
data[config](relatedTarget);
} else if (_config.show) {
data.show(relatedTarget);
}
});
}
}, {
key: 'VERSION',
get: function get() {
return VERSION;
}
}, {
key: 'Default',
get: function get() {
return Default;
}
}]);
return Modal;
})();
$(document).on(Event.CLICK_DATA_API, Selector.DATA_TOGGLE, function (event) {
var _this13 = this;
var target = undefined;
var selector = Util.getSelectorFromElement(this);
if (selector) {
target = $(selector)[0];
}
var config = $(target).data(DATA_KEY) ? 'toggle' : $.extend({}, $(target).data(), $(this).data());
if (this.tagName === 'A') {
event.preventDefault();
}
var $target = $(target).one(Event.SHOW, function (showEvent) {
if (showEvent.isDefaultPrevented()) {
// only register focus restorer if modal will actually get shown
return;
}
$target.one(Event.HIDDEN, function () {
if ($(_this13).is(':visible')) {
_this13.focus();
}
});
});
Modal._jQueryInterface.call($(target), config, this);
});
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
$.fn[NAME] = Modal._jQueryInterface;
$.fn[NAME].Constructor = Modal;
$.fn[NAME].noConflict = function () {
$.fn[NAME] = JQUERY_NO_CONFLICT;
return Modal._jQueryInterface;
};
return Modal;
})(jQuery);
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.0.0): scrollspy.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
var ScrollSpy = (function ($) {
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
var NAME = 'scrollspy';
var VERSION = '4.0.0';
var DATA_KEY = 'bs.scrollspy';
var EVENT_KEY = '.' + DATA_KEY;
var DATA_API_KEY = '.data-api';
var JQUERY_NO_CONFLICT = $.fn[NAME];
var Default = {
offset: 10,
method: 'auto',
target: ''
};
var DefaultType = {
offset: 'number',
method: 'string',
target: '(string|element)'
};
var Event = {
ACTIVATE: 'activate' + EVENT_KEY,
SCROLL: 'scroll' + EVENT_KEY,
LOAD_DATA_API: 'load' + EVENT_KEY + DATA_API_KEY
};
var ClassName = {
DROPDOWN_ITEM: 'dropdown-item',
DROPDOWN_MENU: 'dropdown-menu',
NAV_LINK: 'nav-link',
NAV: 'nav',
ACTIVE: 'active'
};
var Selector = {
DATA_SPY: '[data-spy="scroll"]',
ACTIVE: '.active',
LIST_ITEM: '.list-item',
LI: 'li',
LI_DROPDOWN: 'li.dropdown',
NAV_LINKS: '.nav-link',
DROPDOWN: '.dropdown',
DROPDOWN_ITEMS: '.dropdown-item',
DROPDOWN_TOGGLE: '.dropdown-toggle'
};
var OffsetMethod = {
OFFSET: 'offset',
POSITION: 'position'
};
/**
* ------------------------------------------------------------------------
* Class Definition
* ------------------------------------------------------------------------
*/
var ScrollSpy = (function () {
function ScrollSpy(element, config) {
_classCallCheck(this, ScrollSpy);
this._element = element;
this._scrollElement = element.tagName === 'BODY' ? window : element;
this._config = this._getConfig(config);
this._selector = this._config.target + ' ' + Selector.NAV_LINKS + ',' + (this._config.target + ' ' + Selector.DROPDOWN_ITEMS);
this._offsets = [];
this._targets = [];
this._activeTarget = null;
this._scrollHeight = 0;
$(this._scrollElement).on(Event.SCROLL, $.proxy(this._process, this));
this.refresh();
this._process();
}
/**
* ------------------------------------------------------------------------
* Data Api implementation
* ------------------------------------------------------------------------
*/
// getters
_createClass(ScrollSpy, [{
key: 'refresh',
// public
value: function refresh() {
var _this14 = this;
var autoMethod = this._scrollElement !== this._scrollElement.window ? OffsetMethod.POSITION : OffsetMethod.OFFSET;
var offsetMethod = this._config.method === 'auto' ? autoMethod : this._config.method;
var offsetBase = offsetMethod === OffsetMethod.POSITION ? this._getScrollTop() : 0;
this._offsets = [];
this._targets = [];
this._scrollHeight = this._getScrollHeight();
var targets = $.makeArray($(this._selector));
targets.map(function (element) {
var target = undefined;
var targetSelector = Util.getSelectorFromElement(element);
if (targetSelector) {
target = $(targetSelector)[0];
}
if (target && (target.offsetWidth || target.offsetHeight)) {
// todo (fat): remove sketch reliance on jQuery position/offset
return [$(target)[offsetMethod]().top + offsetBase, targetSelector];
}
}).filter(function (item) {
return item;
}).sort(function (a, b) {
return a[0] - b[0];
}).forEach(function (item) {
_this14._offsets.push(item[0]);
_this14._targets.push(item[1]);
});
}
}, {
key: 'dispose',
value: function dispose() {
$.removeData(this._element, DATA_KEY);
$(this._scrollElement).off(EVENT_KEY);
this._element = null;
this._scrollElement = null;
this._config = null;
this._selector = null;
this._offsets = null;
this._targets = null;
this._activeTarget = null;
this._scrollHeight = null;
}
// private
}, {
key: '_getConfig',
value: function _getConfig(config) {
config = $.extend({}, Default, config);
if (typeof config.target !== 'string') {
var id = $(config.target).attr('id');
if (!id) {
id = Util.getUID(NAME);
$(config.target).attr('id', id);
}
config.target = '#' + id;
}
Util.typeCheckConfig(NAME, config, DefaultType);
return config;
}
}, {
key: '_getScrollTop',
value: function _getScrollTop() {
return this._scrollElement === window ? this._scrollElement.scrollY : this._scrollElement.scrollTop;
}
}, {
key: '_getScrollHeight',
value: function _getScrollHeight() {
return this._scrollElement.scrollHeight || Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);
}
}, {
key: '_process',
value: function _process() {
var scrollTop = this._getScrollTop() + this._config.offset;
var scrollHeight = this._getScrollHeight();
var maxScroll = this._config.offset + scrollHeight - this._scrollElement.offsetHeight;
if (this._scrollHeight !== scrollHeight) {
this.refresh();
}
if (scrollTop >= maxScroll) {
var target = this._targets[this._targets.length - 1];
if (this._activeTarget !== target) {
this._activate(target);
}
}
if (this._activeTarget && scrollTop < this._offsets[0]) {
this._activeTarget = null;
this._clear();
return;
}
for (var i = this._offsets.length; i--;) {
var isActiveTarget = this._activeTarget !== this._targets[i] && scrollTop >= this._offsets[i] && (this._offsets[i + 1] === undefined || scrollTop < this._offsets[i + 1]);
if (isActiveTarget) {
this._activate(this._targets[i]);
}
}
}
}, {
key: '_activate',
value: function _activate(target) {
this._activeTarget = target;
this._clear();
var queries = this._selector.split(',');
queries = queries.map(function (selector) {
return selector + '[data-target="' + target + '"],' + (selector + '[href="' + target + '"]');
});
var $link = $(queries.join(','));
if ($link.hasClass(ClassName.DROPDOWN_ITEM)) {
$link.closest(Selector.DROPDOWN).find(Selector.DROPDOWN_TOGGLE).addClass(ClassName.ACTIVE);
$link.addClass(ClassName.ACTIVE);
} else {
// todo (fat) this is kinda sus…
// recursively add actives to tested nav-links
$link.parents(Selector.LI).find(Selector.NAV_LINKS).addClass(ClassName.ACTIVE);
}
$(this._scrollElement).trigger(Event.ACTIVATE, {
relatedTarget: target
});
}
}, {
key: '_clear',
value: function _clear() {
$(this._selector).filter(Selector.ACTIVE).removeClass(ClassName.ACTIVE);
}
// static
}], [{
key: '_jQueryInterface',
value: function _jQueryInterface(config) {
return this.each(function () {
var data = $(this).data(DATA_KEY);
var _config = typeof config === 'object' && config || null;
if (!data) {
data = new ScrollSpy(this, _config);
$(this).data(DATA_KEY, data);
}
if (typeof config === 'string') {
if (data[config] === undefined) {
throw new Error('No method named "' + config + '"');
}
data[config]();
}
});
}
}, {
key: 'VERSION',
get: function get() {
return VERSION;
}
}, {
key: 'Default',
get: function get() {
return Default;
}
}]);
return ScrollSpy;
})();
$(window).on(Event.LOAD_DATA_API, function () {
var scrollSpys = $.makeArray($(Selector.DATA_SPY));
for (var i = scrollSpys.length; i--;) {
var $spy = $(scrollSpys[i]);
ScrollSpy._jQueryInterface.call($spy, $spy.data());
}
});
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
$.fn[NAME] = ScrollSpy._jQueryInterface;
$.fn[NAME].Constructor = ScrollSpy;
$.fn[NAME].noConflict = function () {
$.fn[NAME] = JQUERY_NO_CONFLICT;
return ScrollSpy._jQueryInterface;
};
return ScrollSpy;
})(jQuery);
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.0.0): tab.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
var Tab = (function ($) {
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
var NAME = 'tab';
var VERSION = '4.0.0';
var DATA_KEY = 'bs.tab';
var EVENT_KEY = '.' + DATA_KEY;
var DATA_API_KEY = '.data-api';
var JQUERY_NO_CONFLICT = $.fn[NAME];
var TRANSITION_DURATION = 150;
var Event = {
HIDE: 'hide' + EVENT_KEY,
HIDDEN: 'hidden' + EVENT_KEY,
SHOW: 'show' + EVENT_KEY,
SHOWN: 'shown' + EVENT_KEY,
CLICK_DATA_API: 'click' + EVENT_KEY + DATA_API_KEY
};
var ClassName = {
DROPDOWN_MENU: 'dropdown-menu',
ACTIVE: 'active',
FADE: 'fade',
IN: 'in'
};
var Selector = {
A: 'a',
LI: 'li',
DROPDOWN: '.dropdown',
UL: 'ul:not(.dropdown-menu)',
FADE_CHILD: '> .nav-item .fade, > .fade',
ACTIVE: '.active',
ACTIVE_CHILD: '> .nav-item > .active, > .active',
DATA_TOGGLE: '[data-toggle="tab"], [data-toggle="pill"]',
DROPDOWN_TOGGLE: '.dropdown-toggle',
DROPDOWN_ACTIVE_CHILD: '> .dropdown-menu .active'
};
/**
* ------------------------------------------------------------------------
* Class Definition
* ------------------------------------------------------------------------
*/
var Tab = (function () {
function Tab(element) {
_classCallCheck(this, Tab);
this._element = element;
}
/**
* ------------------------------------------------------------------------
* Data Api implementation
* ------------------------------------------------------------------------
*/
// getters
_createClass(Tab, [{
key: 'show',
// public
value: function show() {
var _this15 = this;
if (this._element.parentNode && this._element.parentNode.nodeType === Node.ELEMENT_NODE && $(this._element).hasClass(ClassName.ACTIVE)) {
return;
}
var target = undefined;
var previous = undefined;
var ulElement = $(this._element).closest(Selector.UL)[0];
var selector = Util.getSelectorFromElement(this._element);
if (ulElement) {
previous = $.makeArray($(ulElement).find(Selector.ACTIVE));
previous = previous[previous.length - 1];
}
var hideEvent = $.Event(Event.HIDE, {
relatedTarget: this._element
});
var showEvent = $.Event(Event.SHOW, {
relatedTarget: previous
});
if (previous) {
$(previous).trigger(hideEvent);
}
$(this._element).trigger(showEvent);
if (showEvent.isDefaultPrevented() || hideEvent.isDefaultPrevented()) {
return;
}
if (selector) {
target = $(selector)[0];
}
this._activate(this._element, ulElement);
var complete = function complete() {
var hiddenEvent = $.Event(Event.HIDDEN, {
relatedTarget: _this15._element
});
var shownEvent = $.Event(Event.SHOWN, {
relatedTarget: previous
});
$(previous).trigger(hiddenEvent);
$(_this15._element).trigger(shownEvent);
};
if (target) {
this._activate(target, target.parentNode, complete);
} else {
complete();
}
}
}, {
key: 'dispose',
value: function dispose() {
$.removeClass(this._element, DATA_KEY);
this._element = null;
}
// private
}, {
key: '_activate',
value: function _activate(element, container, callback) {
var active = $(container).find(Selector.ACTIVE_CHILD)[0];
var isTransitioning = callback && Util.supportsTransitionEnd() && (active && $(active).hasClass(ClassName.FADE) || Boolean($(container).find(Selector.FADE_CHILD)[0]));
var complete = $.proxy(this._transitionComplete, this, element, active, isTransitioning, callback);
if (active && isTransitioning) {
$(active).one(Util.TRANSITION_END, complete).emulateTransitionEnd(TRANSITION_DURATION);
} else {
complete();
}
if (active) {
$(active).removeClass(ClassName.IN);
}
}
}, {
key: '_transitionComplete',
value: function _transitionComplete(element, active, isTransitioning, callback) {
if (active) {
$(active).removeClass(ClassName.ACTIVE);
var dropdownChild = $(active).find(Selector.DROPDOWN_ACTIVE_CHILD)[0];
if (dropdownChild) {
$(dropdownChild).removeClass(ClassName.ACTIVE);
}
active.setAttribute('aria-expanded', false);
}
$(element).addClass(ClassName.ACTIVE);
element.setAttribute('aria-expanded', true);
if (isTransitioning) {
Util.reflow(element);
$(element).addClass(ClassName.IN);
} else {
$(element).removeClass(ClassName.FADE);
}
if (element.parentNode && $(element.parentNode).hasClass(ClassName.DROPDOWN_MENU)) {
var dropdownElement = $(element).closest(Selector.DROPDOWN)[0];
if (dropdownElement) {
$(dropdownElement).find(Selector.DROPDOWN_TOGGLE).addClass(ClassName.ACTIVE);
}
element.setAttribute('aria-expanded', true);
}
if (callback) {
callback();
}
}
// static
}], [{
key: '_jQueryInterface',
value: function _jQueryInterface(config) {
return this.each(function () {
var $this = $(this);
var data = $this.data(DATA_KEY);
if (!data) {
data = data = new Tab(this);
$this.data(DATA_KEY, data);
}
if (typeof config === 'string') {
if (data[config] === undefined) {
throw new Error('No method named "' + config + '"');
}
data[config]();
}
});
}
}, {
key: 'VERSION',
get: function get() {
return VERSION;
}
}]);
return Tab;
})();
$(document).on(Event.CLICK_DATA_API, Selector.DATA_TOGGLE, function (event) {
event.preventDefault();
Tab._jQueryInterface.call($(this), 'show');
});
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
$.fn[NAME] = Tab._jQueryInterface;
$.fn[NAME].Constructor = Tab;
$.fn[NAME].noConflict = function () {
$.fn[NAME] = JQUERY_NO_CONFLICT;
return Tab._jQueryInterface;
};
return Tab;
})(jQuery);
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.0.0): tooltip.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
var Tooltip = (function ($) {
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
var NAME = 'tooltip';
var VERSION = '4.0.0';
var DATA_KEY = 'bs.tooltip';
var EVENT_KEY = '.' + DATA_KEY;
var JQUERY_NO_CONFLICT = $.fn[NAME];
var TRANSITION_DURATION = 150;
var CLASS_PREFIX = 'bs-tether';
var Default = {
animation: true,
template: '<div class="tooltip" role="tooltip">' + '<div class="tooltip-arrow"></div>' + '<div class="tooltip-inner"></div></div>',
trigger: 'hover focus',
title: '',
delay: 0,
html: false,
selector: false,
placement: 'top',
offset: '0 0',
constraints: []
};
var DefaultType = {
animation: 'boolean',
template: 'string',
title: '(string|element|function)',
trigger: 'string',
delay: '(number|object)',
html: 'boolean',
selector: '(string|boolean)',
placement: '(string|function)',
offset: 'string',
constraints: 'array'
};
var AttachmentMap = {
TOP: 'bottom center',
RIGHT: 'middle left',
BOTTOM: 'top center',
LEFT: 'middle right'
};
var HoverState = {
IN: 'in',
OUT: 'out'
};
var Event = {
HIDE: 'hide' + EVENT_KEY,
HIDDEN: 'hidden' + EVENT_KEY,
SHOW: 'show' + EVENT_KEY,
SHOWN: 'shown' + EVENT_KEY,
INSERTED: 'inserted' + EVENT_KEY,
CLICK: 'click' + EVENT_KEY,
FOCUSIN: 'focusin' + EVENT_KEY,
FOCUSOUT: 'focusout' + EVENT_KEY,
MOUSEENTER: 'mouseenter' + EVENT_KEY,
MOUSELEAVE: 'mouseleave' + EVENT_KEY
};
var ClassName = {
FADE: 'fade',
IN: 'in'
};
var Selector = {
TOOLTIP: '.tooltip',
TOOLTIP_INNER: '.tooltip-inner'
};
var TetherClass = {
element: false,
enabled: false
};
var Trigger = {
HOVER: 'hover',
FOCUS: 'focus',
CLICK: 'click',
MANUAL: 'manual'
};
/**
* ------------------------------------------------------------------------
* Class Definition
* ------------------------------------------------------------------------
*/
var Tooltip = (function () {
function Tooltip(element, config) {
_classCallCheck(this, Tooltip);
// private
this._isEnabled = true;
this._timeout = 0;
this._hoverState = '';
this._activeTrigger = {};
this._tether = null;
// protected
this.element = element;
this.config = this._getConfig(config);
this.tip = null;
this._setListeners();
}
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
// getters
_createClass(Tooltip, [{
key: 'enable',
// public
value: function enable() {
this._isEnabled = true;
}
}, {
key: 'disable',
value: function disable() {
this._isEnabled = false;
}
}, {
key: 'toggleEnabled',
value: function toggleEnabled() {
this._isEnabled = !this._isEnabled;
}
}, {
key: 'toggle',
value: function toggle(event) {
if (event) {
var dataKey = this.constructor.DATA_KEY;
var context = $(event.currentTarget).data(dataKey);
if (!context) {
context = new this.constructor(event.currentTarget, this._getDelegateConfig());
$(event.currentTarget).data(dataKey, context);
}
context._activeTrigger.click = !context._activeTrigger.click;
if (context._isWithActiveTrigger()) {
context._enter(null, context);
} else {
context._leave(null, context);
}
} else {
if ($(this.getTipElement()).hasClass(ClassName.IN)) {
this._leave(null, this);
return;
}
this._enter(null, this);
}
}
}, {
key: 'dispose',
value: function dispose() {
clearTimeout(this._timeout);
this.cleanupTether();
$.removeData(this.element, this.constructor.DATA_KEY);
$(this.element).off(this.constructor.EVENT_KEY);
if (this.tip) {
$(this.tip).remove();
}
this._isEnabled = null;
this._timeout = null;
this._hoverState = null;
this._activeTrigger = null;
this._tether = null;
this.element = null;
this.config = null;
this.tip = null;
}
}, {
key: 'show',
value: function show() {
var _this16 = this;
var showEvent = $.Event(this.constructor.Event.SHOW);
if (this.isWithContent() && this._isEnabled) {
$(this.element).trigger(showEvent);
var isInTheDom = $.contains(this.element.ownerDocument.documentElement, this.element);
if (showEvent.isDefaultPrevented() || !isInTheDom) {
return;
}
var tip = this.getTipElement();
var tipId = Util.getUID(this.constructor.NAME);
tip.setAttribute('id', tipId);
this.element.setAttribute('aria-describedby', tipId);
this.setContent();
if (this.config.animation) {
$(tip).addClass(ClassName.FADE);
}
var placement = typeof this.config.placement === 'function' ? this.config.placement.call(this, tip, this.element) : this.config.placement;
var attachment = this._getAttachment(placement);
$(tip).data(this.constructor.DATA_KEY, this).appendTo(document.body);
$(this.element).trigger(this.constructor.Event.INSERTED);
this._tether = new Tether({
attachment: attachment,
element: tip,
target: this.element,
classes: TetherClass,
classPrefix: CLASS_PREFIX,
offset: this.config.offset,
constraints: this.config.constraints
});
Util.reflow(tip);
this._tether.position();
$(tip).addClass(ClassName.IN);
var complete = function complete() {
var prevHoverState = _this16._hoverState;
_this16._hoverState = null;
$(_this16.element).trigger(_this16.constructor.Event.SHOWN);
if (prevHoverState === HoverState.OUT) {
_this16._leave(null, _this16);
}
};
if (Util.supportsTransitionEnd() && $(this.tip).hasClass(ClassName.FADE)) {
$(this.tip).one(Util.TRANSITION_END, complete).emulateTransitionEnd(Tooltip._TRANSITION_DURATION);
return;
}
complete();
}
}
}, {
key: 'hide',
value: function hide(callback) {
var _this17 = this;
var tip = this.getTipElement();
var hideEvent = $.Event(this.constructor.Event.HIDE);
var complete = function complete() {
if (_this17._hoverState !== HoverState.IN && tip.parentNode) {
tip.parentNode.removeChild(tip);
}
_this17.element.removeAttribute('aria-describedby');
$(_this17.element).trigger(_this17.constructor.Event.HIDDEN);
_this17.cleanupTether();
if (callback) {
callback();
}
};
$(this.element).trigger(hideEvent);
if (hideEvent.isDefaultPrevented()) {
return;
}
$(tip).removeClass(ClassName.IN);
if (Util.supportsTransitionEnd() && $(this.tip).hasClass(ClassName.FADE)) {
$(tip).one(Util.TRANSITION_END, complete).emulateTransitionEnd(TRANSITION_DURATION);
} else {
complete();
}
this._hoverState = '';
}
// protected
}, {
key: 'isWithContent',
value: function isWithContent() {
return Boolean(this.getTitle());
}
}, {
key: 'getTipElement',
value: function getTipElement() {
return this.tip = this.tip || $(this.config.template)[0];
}
}, {
key: 'setContent',
value: function setContent() {
var $tip = $(this.getTipElement());
this.setElementContent($tip.find(Selector.TOOLTIP_INNER), this.getTitle());
$tip.removeClass(ClassName.FADE).removeClass(ClassName.IN);
this.cleanupTether();
}
}, {
key: 'setElementContent',
value: function setElementContent($element, content) {
var html = this.config.html;
if (typeof content === 'object' && (content.nodeType || content.jquery)) {
// content is a DOM node or a jQuery
if (html) {
if (!$(content).parent().is($element)) {
$element.empty().append(content);
}
} else {
$element.text($(content).text());
}
} else {
$element[html ? 'html' : 'text'](content);
}
}
}, {
key: 'getTitle',
value: function getTitle() {
var title = this.element.getAttribute('data-original-title');
if (!title) {
title = typeof this.config.title === 'function' ? this.config.title.call(this.element) : this.config.title;
}
return title;
}
}, {
key: 'cleanupTether',
value: function cleanupTether() {
if (this._tether) {
this._tether.destroy();
// clean up after tether's junk classes
// remove after they fix issue
// (https://github.com/HubSpot/tether/issues/36)
$(this.element).removeClass(this._removeTetherClasses);
$(this.tip).removeClass(this._removeTetherClasses);
}
}
// private
}, {
key: '_getAttachment',
value: function _getAttachment(placement) {
return AttachmentMap[placement.toUpperCase()];
}
}, {
key: '_setListeners',
value: function _setListeners() {
var _this18 = this;
var triggers = this.config.trigger.split(' ');
triggers.forEach(function (trigger) {
if (trigger === 'click') {
$(_this18.element).on(_this18.constructor.Event.CLICK, _this18.config.selector, $.proxy(_this18.toggle, _this18));
} else if (trigger !== Trigger.MANUAL) {
var eventIn = trigger === Trigger.HOVER ? _this18.constructor.Event.MOUSEENTER : _this18.constructor.Event.FOCUSIN;
var eventOut = trigger === Trigger.HOVER ? _this18.constructor.Event.MOUSELEAVE : _this18.constructor.Event.FOCUSOUT;
$(_this18.element).on(eventIn, _this18.config.selector, $.proxy(_this18._enter, _this18)).on(eventOut, _this18.config.selector, $.proxy(_this18._leave, _this18));
}
});
if (this.config.selector) {
this.config = $.extend({}, this.config, {
trigger: 'manual',
selector: ''
});
} else {
this._fixTitle();
}
}
}, {
key: '_removeTetherClasses',
value: function _removeTetherClasses(i, css) {
return ((css.baseVal || css).match(new RegExp('(^|\\s)' + CLASS_PREFIX + '-\\S+', 'g')) || []).join(' ');
}
}, {
key: '_fixTitle',
value: function _fixTitle() {
var titleType = typeof this.element.getAttribute('data-original-title');
if (this.element.getAttribute('title') || titleType !== 'string') {
this.element.setAttribute('data-original-title', this.element.getAttribute('title') || '');
this.element.setAttribute('title', '');
}
}
}, {
key: '_enter',
value: function _enter(event, context) {
var dataKey = this.constructor.DATA_KEY;
context = context || $(event.currentTarget).data(dataKey);
if (!context) {
context = new this.constructor(event.currentTarget, this._getDelegateConfig());
$(event.currentTarget).data(dataKey, context);
}
if (event) {
context._activeTrigger[event.type === 'focusin' ? Trigger.FOCUS : Trigger.HOVER] = true;
}
if ($(context.getTipElement()).hasClass(ClassName.IN) || context._hoverState === HoverState.IN) {
context._hoverState = HoverState.IN;
return;
}
clearTimeout(context._timeout);
context._hoverState = HoverState.IN;
if (!context.config.delay || !context.config.delay.show) {
context.show();
return;
}
context._timeout = setTimeout(function () {
if (context._hoverState === HoverState.IN) {
context.show();
}
}, context.config.delay.show);
}
}, {
key: '_leave',
value: function _leave(event, context) {
var dataKey = this.constructor.DATA_KEY;
context = context || $(event.currentTarget).data(dataKey);
if (!context) {
context = new this.constructor(event.currentTarget, this._getDelegateConfig());
$(event.currentTarget).data(dataKey, context);
}
if (event) {
context._activeTrigger[event.type === 'focusout' ? Trigger.FOCUS : Trigger.HOVER] = false;
}
if (context._isWithActiveTrigger()) {
return;
}
clearTimeout(context._timeout);
context._hoverState = HoverState.OUT;
if (!context.config.delay || !context.config.delay.hide) {
context.hide();
return;
}
context._timeout = setTimeout(function () {
if (context._hoverState === HoverState.OUT) {
context.hide();
}
}, context.config.delay.hide);
}
}, {
key: '_isWithActiveTrigger',
value: function _isWithActiveTrigger() {
for (var trigger in this._activeTrigger) {
if (this._activeTrigger[trigger]) {
return true;
}
}
return false;
}
}, {
key: '_getConfig',
value: function _getConfig(config) {
config = $.extend({}, this.constructor.Default, $(this.element).data(), config);
if (config.delay && typeof config.delay === 'number') {
config.delay = {
show: config.delay,
hide: config.delay
};
}
Util.typeCheckConfig(NAME, config, this.constructor.DefaultType);
return config;
}
}, {
key: '_getDelegateConfig',
value: function _getDelegateConfig() {
var config = {};
if (this.config) {
for (var key in this.config) {
if (this.constructor.Default[key] !== this.config[key]) {
config[key] = this.config[key];
}
}
}
return config;
}
// static
}], [{
key: '_jQueryInterface',
value: function _jQueryInterface(config) {
return this.each(function () {
var data = $(this).data(DATA_KEY);
var _config = typeof config === 'object' ? config : null;
if (!data && /destroy|hide/.test(config)) {
return;
}
if (!data) {
data = new Tooltip(this, _config);
$(this).data(DATA_KEY, data);
}
if (typeof config === 'string') {
if (data[config] === undefined) {
throw new Error('No method named "' + config + '"');
}
data[config]();
}
});
}
}, {
key: 'VERSION',
get: function get() {
return VERSION;
}
}, {
key: 'Default',
get: function get() {
return Default;
}
}, {
key: 'NAME',
get: function get() {
return NAME;
}
}, {
key: 'DATA_KEY',
get: function get() {
return DATA_KEY;
}
}, {
key: 'Event',
get: function get() {
return Event;
}
}, {
key: 'EVENT_KEY',
get: function get() {
return EVENT_KEY;
}
}, {
key: 'DefaultType',
get: function get() {
return DefaultType;
}
}]);
return Tooltip;
})();
$.fn[NAME] = Tooltip._jQueryInterface;
$.fn[NAME].Constructor = Tooltip;
$.fn[NAME].noConflict = function () {
$.fn[NAME] = JQUERY_NO_CONFLICT;
return Tooltip._jQueryInterface;
};
return Tooltip;
})(jQuery);
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.0.0): popover.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
var Popover = (function ($) {
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
var NAME = 'popover';
var VERSION = '4.0.0';
var DATA_KEY = 'bs.popover';
var EVENT_KEY = '.' + DATA_KEY;
var JQUERY_NO_CONFLICT = $.fn[NAME];
var Default = $.extend({}, Tooltip.Default, {
placement: 'right',
trigger: 'click',
content: '',
template: '<div class="popover" role="tooltip">' + '<div class="popover-arrow"></div>' + '<h3 class="popover-title"></h3>' + '<div class="popover-content"></div></div>'
});
var DefaultType = $.extend({}, Tooltip.DefaultType, {
content: '(string|element|function)'
});
var ClassName = {
FADE: 'fade',
IN: 'in'
};
var Selector = {
TITLE: '.popover-title',
CONTENT: '.popover-content',
ARROW: '.popover-arrow'
};
var Event = {
HIDE: 'hide' + EVENT_KEY,
HIDDEN: 'hidden' + EVENT_KEY,
SHOW: 'show' + EVENT_KEY,
SHOWN: 'shown' + EVENT_KEY,
INSERTED: 'inserted' + EVENT_KEY,
CLICK: 'click' + EVENT_KEY,
FOCUSIN: 'focusin' + EVENT_KEY,
FOCUSOUT: 'focusout' + EVENT_KEY,
MOUSEENTER: 'mouseenter' + EVENT_KEY,
MOUSELEAVE: 'mouseleave' + EVENT_KEY
};
/**
* ------------------------------------------------------------------------
* Class Definition
* ------------------------------------------------------------------------
*/
var Popover = (function (_Tooltip) {
_inherits(Popover, _Tooltip);
function Popover() {
_classCallCheck(this, Popover);
_get(Object.getPrototypeOf(Popover.prototype), 'constructor', this).apply(this, arguments);
}
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
_createClass(Popover, [{
key: 'isWithContent',
// overrides
value: function isWithContent() {
return this.getTitle() || this._getContent();
}
}, {
key: 'getTipElement',
value: function getTipElement() {
return this.tip = this.tip || $(this.config.template)[0];
}
}, {
key: 'setContent',
value: function setContent() {
var $tip = $(this.getTipElement());
// we use append for html objects to maintain js events
this.setElementContent($tip.find(Selector.TITLE), this.getTitle());
this.setElementContent($tip.find(Selector.CONTENT), this._getContent());
$tip.removeClass(ClassName.FADE).removeClass(ClassName.IN);
this.cleanupTether();
}
// private
}, {
key: '_getContent',
value: function _getContent() {
return this.element.getAttribute('data-content') || (typeof this.config.content === 'function' ? this.config.content.call(this.element) : this.config.content);
}
// static
}], [{
key: '_jQueryInterface',
value: function _jQueryInterface(config) {
return this.each(function () {
var data = $(this).data(DATA_KEY);
var _config = typeof config === 'object' ? config : null;
if (!data && /destroy|hide/.test(config)) {
return;
}
if (!data) {
data = new Popover(this, _config);
$(this).data(DATA_KEY, data);
}
if (typeof config === 'string') {
if (data[config] === undefined) {
throw new Error('No method named "' + config + '"');
}
data[config]();
}
});
}
}, {
key: 'VERSION',
// getters
get: function get() {
return VERSION;
}
}, {
key: 'Default',
get: function get() {
return Default;
}
}, {
key: 'NAME',
get: function get() {
return NAME;
}
}, {
key: 'DATA_KEY',
get: function get() {
return DATA_KEY;
}
}, {
key: 'Event',
get: function get() {
return Event;
}
}, {
key: 'EVENT_KEY',
get: function get() {
return EVENT_KEY;
}
}, {
key: 'DefaultType',
get: function get() {
return DefaultType;
}
}]);
return Popover;
})(Tooltip);
$.fn[NAME] = Popover._jQueryInterface;
$.fn[NAME].Constructor = Popover;
$.fn[NAME].noConflict = function () {
$.fn[NAME] = JQUERY_NO_CONFLICT;
return Popover._jQueryInterface;
};
return Popover;
})(jQuery);
}(jQuery);
| BarakChamo/rc-badges | node_modules/bootstrap/dist/js/bootstrap.js | JavaScript | mit | 99,591 |
(function(global) {
var Internal = {
SENDER: 'BackgroundScript',
log: function(message) {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {'sender': Internal.SENDER, 'message': message});
});
}
};
global.ChromeLogger = {
log: function(message) {
Internal.log(message);
}
};
})(window);
| B3nRa/ChromeExtensionLogger | BackgroundLogger.js | JavaScript | mit | 455 |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends2 = require('babel-runtime/helpers/extends');
var _extends3 = _interopRequireDefault(_extends2);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = require('babel-runtime/helpers/inherits');
var _inherits3 = _interopRequireDefault(_inherits2);
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _propTypes = require('prop-types');
var _propTypes2 = _interopRequireDefault(_propTypes);
var _reactDom = require('react-dom');
var _reactDom2 = _interopRequireDefault(_reactDom);
var _rcAlign = require('rc-align');
var _rcAlign2 = _interopRequireDefault(_rcAlign);
var _rcAnimate = require('rc-animate');
var _rcAnimate2 = _interopRequireDefault(_rcAnimate);
var _PopupInner = require('./PopupInner');
var _PopupInner2 = _interopRequireDefault(_PopupInner);
var _LazyRenderBox = require('./LazyRenderBox');
var _LazyRenderBox2 = _interopRequireDefault(_LazyRenderBox);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
var Popup = function (_Component) {
(0, _inherits3["default"])(Popup, _Component);
function Popup() {
var _temp, _this, _ret;
(0, _classCallCheck3["default"])(this, Popup);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = (0, _possibleConstructorReturn3["default"])(this, _Component.call.apply(_Component, [this].concat(args))), _this), _this.onAlign = function (popupDomNode, align) {
var props = _this.props;
var alignClassName = props.getClassNameFromAlign(props.align);
var currentAlignClassName = props.getClassNameFromAlign(align);
if (alignClassName !== currentAlignClassName) {
_this.currentAlignClassName = currentAlignClassName;
popupDomNode.className = _this.getClassName(currentAlignClassName);
}
props.onAlign(popupDomNode, align);
}, _this.getTarget = function () {
return _this.props.getRootDomNode();
}, _this.saveAlign = function (align) {
_this.alignInstance = align;
}, _temp), (0, _possibleConstructorReturn3["default"])(_this, _ret);
}
Popup.prototype.componentDidMount = function componentDidMount() {
this.rootNode = this.getPopupDomNode();
};
Popup.prototype.getPopupDomNode = function getPopupDomNode() {
return _reactDom2["default"].findDOMNode(this.refs.popup);
};
Popup.prototype.getMaskTransitionName = function getMaskTransitionName() {
var props = this.props;
var transitionName = props.maskTransitionName;
var animation = props.maskAnimation;
if (!transitionName && animation) {
transitionName = props.prefixCls + '-' + animation;
}
return transitionName;
};
Popup.prototype.getTransitionName = function getTransitionName() {
var props = this.props;
var transitionName = props.transitionName;
if (!transitionName && props.animation) {
transitionName = props.prefixCls + '-' + props.animation;
}
return transitionName;
};
Popup.prototype.getClassName = function getClassName(currentAlignClassName) {
return this.props.prefixCls + ' ' + this.props.className + ' ' + currentAlignClassName;
};
Popup.prototype.getPopupElement = function getPopupElement() {
var props = this.props;
var align = props.align,
style = props.style,
visible = props.visible,
prefixCls = props.prefixCls,
destroyPopupOnHide = props.destroyPopupOnHide;
var className = this.getClassName(this.currentAlignClassName || props.getClassNameFromAlign(align));
var hiddenClassName = prefixCls + '-hidden';
if (!visible) {
this.currentAlignClassName = null;
}
var newStyle = (0, _extends3["default"])({}, style, this.getZIndexStyle());
var popupInnerProps = {
className: className,
prefixCls: prefixCls,
ref: 'popup',
onMouseEnter: props.onMouseEnter,
onMouseLeave: props.onMouseLeave,
style: newStyle
};
if (destroyPopupOnHide) {
return _react2["default"].createElement(
_rcAnimate2["default"],
{
component: '',
exclusive: true,
transitionAppear: true,
transitionName: this.getTransitionName()
},
visible ? _react2["default"].createElement(
_rcAlign2["default"],
{
target: this.getTarget,
key: 'popup',
ref: this.saveAlign,
monitorWindowResize: true,
align: align,
onAlign: this.onAlign
},
_react2["default"].createElement(
_PopupInner2["default"],
(0, _extends3["default"])({
visible: true
}, popupInnerProps),
props.children
)
) : null
);
}
return _react2["default"].createElement(
_rcAnimate2["default"],
{
component: '',
exclusive: true,
transitionAppear: true,
transitionName: this.getTransitionName(),
showProp: 'xVisible'
},
_react2["default"].createElement(
_rcAlign2["default"],
{
target: this.getTarget,
key: 'popup',
ref: this.saveAlign,
monitorWindowResize: true,
xVisible: visible,
childrenProps: { visible: 'xVisible' },
disabled: !visible,
align: align,
onAlign: this.onAlign
},
_react2["default"].createElement(
_PopupInner2["default"],
(0, _extends3["default"])({
hiddenClassName: hiddenClassName
}, popupInnerProps),
props.children
)
)
);
};
Popup.prototype.getZIndexStyle = function getZIndexStyle() {
var style = {};
var props = this.props;
if (props.zIndex !== undefined) {
style.zIndex = props.zIndex;
}
return style;
};
Popup.prototype.getMaskElement = function getMaskElement() {
var props = this.props;
var maskElement = void 0;
if (props.mask) {
var maskTransition = this.getMaskTransitionName();
maskElement = _react2["default"].createElement(_LazyRenderBox2["default"], {
style: this.getZIndexStyle(),
key: 'mask',
className: props.prefixCls + '-mask',
hiddenClassName: props.prefixCls + '-mask-hidden',
visible: props.visible
});
if (maskTransition) {
maskElement = _react2["default"].createElement(
_rcAnimate2["default"],
{
key: 'mask',
showProp: 'visible',
transitionAppear: true,
component: '',
transitionName: maskTransition
},
maskElement
);
}
}
return maskElement;
};
Popup.prototype.render = function render() {
return _react2["default"].createElement(
'div',
null,
this.getMaskElement(),
this.getPopupElement()
);
};
return Popup;
}(_react.Component);
Popup.propTypes = {
visible: _propTypes2["default"].bool,
style: _propTypes2["default"].object,
getClassNameFromAlign: _propTypes2["default"].func,
onAlign: _propTypes2["default"].func,
getRootDomNode: _propTypes2["default"].func,
onMouseEnter: _propTypes2["default"].func,
align: _propTypes2["default"].any,
destroyPopupOnHide: _propTypes2["default"].bool,
className: _propTypes2["default"].string,
prefixCls: _propTypes2["default"].string,
onMouseLeave: _propTypes2["default"].func
};
exports["default"] = Popup;
module.exports = exports['default']; | prodigalyijun/demo-by-antd | node_modules/rc-trigger/lib/Popup.js | JavaScript | mit | 8,002 |
(function($, undefined) {
function Loader() {
}
Loader.load = function(from, $target, selector) {
LoadingIndicator.addTo("body");
var result;
if (!selector) selector = '[role="dialog"]';
var options = {
async: false,
success: function(data) {
result = $target.append(data);
}
};
$.ajax(from, options);
LoadingIndicator.removeFrom("body");
return result.find(selector).first();
};
ClassRegistry.set('Loader', Loader);
})(jQuery);
| tyne/tyne | app/assets/javascripts/support/loader.js | JavaScript | mit | 504 |
/**
* Parses sleep from a string or number. If the input is not a valid time then
* {{#crossLink "anim8.defaults/sleep:property"}}anim8.defaults.sleep{{/crossLink}}
* is returned.
*
* **See:** {{#crossLink "Core/anim8.time:method"}}anim8.time{{/crossLink}}
*
* @method anim8.sleep
* @param {String|Number} time
*/
function $sleep(time)
{
return $time( time, Defaults.sleep );
}
| ClickerMonkey/anim8js | src/parsing/sleep.js | JavaScript | mit | 391 |
/*!
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
const expect = global.expect;
let numExpectations = 0;
global.expect = function() {
numExpectations += 1;
return expect.apply(this, arguments);
};
const spyOn = global.spyOn;
// Spying on console methods in production builds can mask errors.
// This is why we added an explicit spyOnDev() helper.
// It's too easy to accidentally use the more familiar spyOn() helper though,
// So we disable it entirely.
// Spying on both dev and prod will require using both spyOnDev() and spyOnProd().
global.spyOn = function() {
throw new Error(
'Do not use spyOn(). ' +
'It can accidentally hide unexpected errors in production builds. ' +
'Use spyOnDev(), spyOnProd(), or spyOnDevAndProd() instead.'
);
};
global.spyOnDev = function(...args) {
if (__DEV__) {
return spyOn(...args);
}
};
global.spyOnDevAndProd = spyOn;
global.spyOnProd = function(...args) {
if (!__DEV__) {
return spyOn(...args);
}
};
expect.extend({
...require('../matchers/reactTestMatchers'),
...require('../matchers/toThrow'),
...require('../matchers/toWarnDev'),
});
beforeEach(() => (numExpectations = 0));
jasmine.currentEnv_.addReporter({
specDone: spec => {
console.log(
`EQUIVALENCE: ${spec.description}, ` +
`status: ${spec.status}, ` +
`numExpectations: ${numExpectations}`
);
},
});
| facebook/react | scripts/jest/spec-equivalence-reporter/setupTests.js | JavaScript | mit | 1,547 |
/**
* QCObjects 1.0
* ________________
*
* Author: Jean Machuca <correojean@gmail.com>
*
* Cross Browser Javascript Framework for MVC Patterns
* QuickCorp/QCObjects is licensed under the
* GNU Lesser General Public License v3.0
* [LICENSE] (https://github.com/QuickCorp/QCObjects/blob/master/LICENSE.txt)
*
* Permissions of this copyleft license are conditioned on making available
* complete source code of licensed works and modifications under the same
* license or the GNU GPLv3. Copyright and license notices must be preserved.
* Contributors provide an express grant of patent rights. However, a larger
* work using the licensed work through interfaces provided by the licensed
* work may be distributed under different terms and without source code for
* the larger work.
*
* Copyright (C) 2015 Jean Machuca,<correojean@gmail.com>
*
* Everyone is permitted to copy and distribute verbatim copies of this
* license document, but changing it is not allowed.
*/
/*eslint no-unused-vars: "off"*/
/*eslint no-redeclare: "off"*/
/*eslint no-empty: "off"*/
/*eslint strict: "off"*/
/*eslint no-mixed-operators: "off"*/
(function(_top) {
"use strict";
var _protected_code_ = function(_) {
var __oldtoString = (typeof _.prototype !== "undefined") ? (_.prototype.toString) : (function() {
return "";
});
_.prototype.toString = function() {
var _protected_symbols = ["ComplexStorageCache",
"debug",
"info",
"warn",
"QC_Append",
"set",
"get",
"done",
"componentDone",
"_new_",
"__new__",
"Class",
"ClassFactory",
"New",
"Export",
"Package",
"Import",
"subelements",
"componentLoader",
"buildComponents",
"Controller",
"View",
"VO",
"Service",
"serviceLoader",
"JSONService",
"ConfigService",
"SourceJS",
"SourceCSS",
"ArrayList",
"ArrayCollection",
"Effect",
"Timer"
];
var _ret_;
if (_protected_symbols.includes(this.name)) {
_ret_ = this.name + "{ [QCObjects native code] }";
} else {
_ret_ = __oldtoString.call(this);
}
return _ret_;
};
};
(_protected_code_)(Function);
var _methods_ = function(_) {
var _m = [];
for (var i in _) {
if ((typeof _[i]).toLowerCase() === "function") {
_m.push(_[i]);
}
}
return _m;
};
var isBrowser = typeof window !== "undefined" && typeof window.self !== "undefined" && window === window.self;
var _DOMCreateElement = function(elementName) {
var _ret_;
if (isBrowser) {
_ret_ = document.createElement(elementName);
} else {
_ret_ = {};
}
return _ret_;
};
if (!isBrowser) {
const fs = require("fs");
}
var _DataStringify = function(data) {
var getCircularReplacer = function() {
var seen = new WeakSet();
var _level = 0;
return function(key, value) {
if (typeof value === "object" && value !== null) {
if (seen.has(value)) {
_level += 1;
return (_level <= 3) ? (_LegacyCopy(value)) : (null);
}
seen.add(value);
}
return value;
};
};
return JSON.stringify(data, getCircularReplacer());
};
if (isBrowser) {
var _subelements = function subelements(selector) {
return [...this.querySelectorAll(selector)];
};
Element.prototype.subelements = _subelements;
HTMLDocument.prototype.subelements = _subelements;
HTMLElement.prototype.subelements = _subelements;
if (typeof ShadowRoot !== "undefined"){
ShadowRoot.prototype.subelements = _subelements;
}
}
if (isBrowser) {
try {
_top = (typeof window.top !== "undefined") ? (window.top) : (window);
_top["_allowed_"] = true;
} catch (e) {
try {
_top = document;
_top["_allowed_"] = true;
} catch (e2) {
try {
_top = global;
_top["_allowed_"] = true;
} catch (e3) {
_top = {};
_top["_allowed_"] = true;
}
}
}
} else if (typeof global !== "undefined") {
_top = global;
}
var basePath = (
function() {
var _basePath = "";
if (isBrowser) {
var baseURI = _top.document.baseURI.split("/");
baseURI.pop();
_basePath = baseURI.join("/") + "/";
} else {
var process;
try {
process = require("process");
} catch (e) {
// not a process module
}
if (typeof process !== "undefined") {
_basePath = `${process.cwd()}/`;
} else {
_basePath = "";
}
}
return _basePath;
}
)();
if (isBrowser) {
/**
* Polyfilling Promise
*/
if (!("Promise" in _top)) {
_top.Promise = function(_f) {
var _p = {
then: function() {},
catch: function() {},
_then: function(response) {
this.then.call(_p, response);
},
_catch: function(response) {
this.catch.call(_p, response);
}
};
_f.call(_p, _p._then, _p._catch);
return _p;
};
}
if (typeof _top.console === "undefined") {
_top.console = function() {};
_top.console.prototype.log = function(message) {};
}
var domain = (
function() {
return (typeof document !== "undefined" && document.domain !== "") ? (document.domain) : ("localhost");
}
)();
var _secretKey = (
function() {
var __secretKey = _top[(![] + [])[((+!+[]) + (+!+[]))] + (typeof ![])[(+!+[])] + (typeof [])[((+!+[]) + (+!+[])) * ((+!+[]) + (+!+[]))] + (![] + [])[(+!+[])] + (!![] + [])[(+[])] + ([] + [] + [][
[]
])[(+[+!+[] + [+[]]]) / ((+!+[]) + (+!+[]))] + (typeof ![])[(+!+[])] + ([] + [] + [][
[]
])[(+!+[])]]["h" + (typeof ![])[(+!+[])] + (![] + [])[(+!+[] + ((+!+[]) + (+!+[])))] + (!![] + [])[(+[])]].toLowerCase();
return __secretKey;
}
)();
var is_phonegap = (
function() {
return (typeof cordova !== "undefined") ? (true) : (false);
}
)();
} else {
// This is only for code integrity purpose using non-browser implementations
// like using node.js
var _secretKey = "secret";
var domain = "localhost";
}
_top._asyncLoad = [];
var asyncLoad = function(callback, args) {
var asyncCallback = {
"func": callback,
"args": args,
"dispatch": function() {
this.func.apply(null, this.args);
}
};
_top._asyncLoad.push(asyncCallback);
return asyncCallback;
};
if (isBrowser) {
var _fireAsyncLoad = function() {
if (document.readyState === "complete") {
for (var f in _top._asyncLoad) {
var fc = _top._asyncLoad[f];
fc.dispatch();
}
}
};
document.onreadystatechange = _fireAsyncLoad;
} else if (typeof global !== "undefined") {
global._fireAsyncLoad = function() {
for (var f in _top._asyncLoad) {
var fc = _top._asyncLoad[f];
fc.dispatch();
}
};
}
_top.asyncLoad = asyncLoad;
var Logger = function() {
return {
debugEnabled: true,
infoEnabled: true,
warnEnabled: true,
debug: function(message) {
if (this.debugEnabled) {
console.log("\x1b[35m%s\x1b[0m","[DEBUG] " + message);
}
},
info: function(message) {
if (this.infoEnabled) {
console.info("\x1b[33m%s\x1b[0m","[INFO] " + message);
}
},
warn: function(message) {
if (this.warnEnabled) {
console.warn("\x1b[31m%s\x1b[0m","[WARN] " + message);
}
}
};
};
var logger = new Logger();
logger.debugEnabled = false;
logger.infoEnabled = false;
_top.logger = logger;
var Base64 = {
_keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
encode: function(e) {
var t = "";
var n, r, i, s, o, u, a;
var f = 0;
e = Base64._utf8_encode(e);
while (f < e.length) {
n = e.charCodeAt(f++);
r = e.charCodeAt(f++);
i = e.charCodeAt(f++);
s = n >> 2;
o = (n & 3) << 4 | r >> 4;
u = (r & 15) << 2 | i >> 6;
a = i & 63;
if (isNaN(r)) {
u = a = 64;
} else if (isNaN(i)) {
a = 64;
}
t = t + this._keyStr.charAt(s) + this._keyStr.charAt(o) + this._keyStr.charAt(u) + this._keyStr.charAt(a);
}
return t;
},
decode: function(e) {
var t = "";
var n, r, i;
var s, o, u, a;
var f = 0;
e = e.replace(/[^A-Za-z0-9+/=]/g, "");
while (f < e.length) {
s = this._keyStr.indexOf(e.charAt(f++));
o = this._keyStr.indexOf(e.charAt(f++));
u = this._keyStr.indexOf(e.charAt(f++));
a = this._keyStr.indexOf(e.charAt(f++));
n = s << 2 | o >> 4;
r = (o & 15) << 4 | u >> 2;
i = (u & 3) << 6 | a;
t = t + String.fromCharCode(n);
if (u !== 64) {
t = t + String.fromCharCode(r);
}
if (a !== 64) {
t = t + String.fromCharCode(i);
}
}
t = Base64._utf8_decode(t);
return t;
},
_utf8_encode: function(e) {
e = e.replace(/rn/g, "n");
var t = "";
for (var n = 0; n < e.length; n++) {
var r = e.charCodeAt(n);
if (r < 128) {
t += String.fromCharCode(r);
} else if (r > 127 && r < 2048) {
t += String.fromCharCode(r >> 6 | 192);
t += String.fromCharCode(r & 63 | 128);
} else {
t += String.fromCharCode(r >> 12 | 224);
t += String.fromCharCode(r >> 6 & 63 | 128);
t += String.fromCharCode(r & 63 | 128);
}
}
return t;
},
_utf8_decode: function(e) {
var t = "";
var n = 0;
var r = 0;
var c1 = 0;
var c2 = 0;
var c3;
while (n < e.length) {
r = e.charCodeAt(n);
if (r < 128) {
t += String.fromCharCode(r);
n++;
} else if (r > 191 && r < 224) {
c2 = e.charCodeAt(n + 1);
t += String.fromCharCode((r & 31) << 6 | c2 & 63);
n += 2;
} else {
c2 = e.charCodeAt(n + 1);
c3 = e.charCodeAt(n + 2);
t += String.fromCharCode((r & 15) << 12 | (c2 & 63) << 6 | c3 & 63);
n += 3;
}
}
return t;
}
};
var waitUntil = function(func, exp) {
var _waitUntil = function(func, exp) {
var maxWaitCycles = 2000;
var _w = 0;
var _t = setInterval(function() {
if (exp.call()) {
clearInterval(_t);
func.call();
logger.debug("Ejecuting " + func.name + " after wait");
} else {
if (_w < maxWaitCycles) {
_w += 1;
logger.debug("WAIT UNTIL " + func.name + " is true, " + _w.toString() + " cycles");
} else {
logger.debug("Max execution time for " + func.name + " expression until true");
clearInterval(_t);
}
}
}, 1);
};
setTimeout(function() {
_waitUntil(func, exp);
}, 1);
};
var ComplexStorageCache = function(params) {
var object, load, alternate;
object = params.index;
load = params.load;
alternate = params.alternate;
var cachedObjectID = this.getID(object);
var cachedResponse = localStorage.getItem(cachedObjectID);
if (this.isEmpty(cachedResponse)) {
var cachedNewResponse = load.call(null, {
"cachedObjectID": cachedObjectID,
"cachedResponse": cachedResponse,
"cache": this
});
this.save(object, cachedNewResponse);
logger.debug("RESPONSE OF {{cachedObjectID}} CACHED".replace("{{cachedObjectID}}", cachedObjectID));
} else {
var alternateResponse = alternate.call(null, {
"cachedObjectID": cachedObjectID,
"cachedResponse": cachedResponse,
"cache": this
});
logger.debug("RESPONSE OF {{cachedObjectID}} IS ALREADY CACHED ".replace("{{cachedObjectID}}", cachedObjectID));
}
return this;
};
ComplexStorageCache.prototype.getItem = function(cachedObjectID) {
var retrievedObject = localStorage.getItem(cachedObjectID);
if (!this.isEmpty(retrievedObject)) {
return JSON.parse(retrievedObject);
} else {
return null;
}
};
ComplexStorageCache.prototype.setItem = function(cachedObjectID, value) {
localStorage.setItem(cachedObjectID, _DataStringify(value));
};
ComplexStorageCache.prototype.isEmpty = function(object) {
var r = false;
switch (true) {
case (typeof object === "undefined"):
case (typeof object === "string" && object === ""):
case (typeof object === "string" && object === "undefined"):
case (typeof object === "number" && object === 0):
case (object === null):
r = true;
break;
default:
r = false;
}
return r;
};
ComplexStorageCache.prototype.getID = function(object) {
var cachedObjectID = "cachedObject_" + Base64.encode(_DataStringify(object).replace(",", "_").replace("{", "_").replace("}", "_"));
return cachedObjectID;
};
ComplexStorageCache.prototype.save = function(object, cachedNewResponse) {
var cachedObjectID = this.getID(object);
logger.debug("CACHING THE RESPONSE OF {{cachedObjectID}} ".replace("{{cachedObjectID}}", cachedObjectID));
this.setItem(cachedObjectID, cachedNewResponse);
};
ComplexStorageCache.prototype.getCached = function(object) {
var cachedObjectID = this.getID(object);
return this.getItem(cachedObjectID);
};
ComplexStorageCache.prototype.clear = function() {
for (var c in localStorage) {
if (c.startsWith("cachedObject_")) {
localStorage.removeItem(c);
}
}
};
/**
* Detecting passive events feature
*
* https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md#feature-detection
**/
// Test via a getter in the options object to see if the passive property is accessed
if (isBrowser) {
var supportsPassive = false;
try {
var opts = Object.defineProperty({}, "passive", {
get: function() {
supportsPassive = true;
return supportsPassive;
}
});
window.addEventListener("testPassive", null, opts);
window.removeEventListener("testPassive", null, opts);
} catch (e) {}
var captureFalse = function() {
return (supportsPassive) ? ({
passive: true
}) : (false);
};
// Use our detect's results. passive applied if supported, capture will be false either way.
//elem.addEventListener('touchstart', fn, captureFalse);
}
/**
* Basic Type of all elements
*/
var QC_Object = function() {};
QC_Object.prototype = {
find: function(tag) {
var _oo = [];
if (isBrowser) {
var _tags = document.subelements(tag);
for (var _t in _tags) {
var _tt = _tags[_t];
if ((typeof _tags[_t] !== "undefined") && _tags[_t].parentNode.tagName === this.parentNode.tagName) {
_oo.push(_Cast(_tt, (new QC_Object())));
}
}
} else {
//not implemented yet.
}
return _oo;
}
};
/**
* Primary instance ID of all objects
*/
var __instanceID;
// Adaptation of Production steps of ECMA-262, Edition 5, 15.2.3.5
// Reference: http://es5.github.io/#x15.2.3.5
Object.create = (function() {
// make a safe reference to Object.prototype.hasOwnProperty
var hasOwn = Object.prototype.hasOwnProperty;
return function(O) {
// 1. If Type(O) is not Object or Null throw a TypeError exception.
if (typeof O !== "object") {
throw TypeError("Object prototype may only be an Object or null. The type is " + typeof(O));
}
// 2. Let obj be the result of creating a new object as if by the
// expression new Object() where Object is the standard built-in
// constructor with that name
// 3. Set the [[Prototype]] internal property of obj to O.
QC_Object.prototype = O;
var obj = new QC_Object();
QC_Object.prototype = null;
// Let's not keep a stray reference to O...
// 4. If the argument Properties is present and not undefined, add
// own properties to obj as if by calling the standard built-in
// function Object.defineProperties with arguments obj and
// Properties.
if (arguments.length > 1) {
// Object.defineProperties does ToObject on its first argument.
var Properties = Object(arguments[1]);
for (var prop in Properties) {
if (hasOwn.call(Properties, prop)) {
obj[prop] = Properties[prop];
}
}
}
// 5. Return obj
return obj;
};
})();
// Object.assign Polyfilling
// Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#Polyfill
if (typeof Object.assign !== "function") {
// Must be writable: true, enumerable: false, configurable: true
Object.defineProperty(Object, "assign", {
value: function assign(target, varArgs) { // .length of function is 2
"use strict";
if (target === null) { // TypeError if undefined or null
throw new TypeError("Cannot convert undefined or null to object");
}
var to = Object(target);
for (var index = 1; index < arguments.length; index++) {
var nextSource = arguments[index];
if (nextSource !== null) { // Skip over if undefined or null
for (var nextKey in nextSource) {
// Avoid bugs when hasOwnProperty is shadowed
if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
to[nextKey] = nextSource[nextKey];
}
}
}
}
return to;
},
writable: true,
configurable: true
});
}
var _LegacyCopy = function(obj) {
var _ret_;
switch (typeof obj) {
case "string":
_ret_ = obj;
break;
case "number":
_ret_ = obj;
break;
case "object":
_ret_ = Object.assign({}, obj);
break;
case "function":
_ret_ = Object.assign({}, obj);
break;
default:
break;
}
return _ret_;
};
var _QC_CLASSES = {};
var _QC_PACKAGES = {};
var _QC_PACKAGES_IMPORTED = [];
var _QC_READY_LISTENERS = [];
/**
* Returns the object or function name
*
* @param Object or function
*/
var ObjectName = function(o) {
var ret = "";
if (typeof o.constructor === "function") {
ret = o.constructor.name;
} else if (typeof o.constructor === "object") {
ret = o.constructor.toString().split(" ")[1].replace("]", "");
}
return ret;
};
/**
* Casts an object to another object class type
*
* @param {Object} obj_source
* @param {Object} obj_dest
*/
var _Cast = function(obj_source, obj_dest) {
for (var v in obj_source) {
if (typeof obj_source[v] !== "undefined") {
try {
obj_dest[v] = obj_source[v];
} catch (e) {
}
}
}
return obj_dest;
};
/**
* Casts an object to another object class type. Only properties
*
* @param {Object} obj_source
* @param {Object} obj_dest
*/
var _CastProps = function(obj_source, obj_dest) {
for (var v in obj_source) {
if (typeof obj_source[v] !== "undefined" && typeof obj_source[v] !== "function") {
try {
obj_dest[v] = obj_source[v];
} catch (e) {
}
} else if (typeof obj_source[v] === "function"){
try {
obj_dest[v] = obj_source[v].bind(obj_dest);
} catch (e) {
}
}
}
return obj_dest;
};
/**
* Creates new object class of another object
*
* @param {String} name
* @param {Object} type
* @param {Object} definition
*/
var Class = function(name, type, definition) {
var o;
var name = arguments[0];
if (isBrowser) {
var type = (arguments.length > 2) ? (arguments[1]) : (HTMLElement);
} else {
var type = (arguments.length > 2) ? (arguments[1]) : (Object);
}
var definition = (arguments.length > 2) ? (arguments[2]) : (
(arguments.length > 1) ? (arguments[1]) : ({})
);
if (typeof type === "undefined") {
if (isBrowser) {
type = HTMLElement; // defaults to HTMLElement type
} else {
type = Object;
}
} else {
definition = _Cast(
(typeof definition === "undefined") ? ({}) : (definition),
(typeof type["__definition"] !== "undefined") ? (_LegacyCopy(type.__definition)) : ({})
);
}
type = (type.hasOwnProperty.call(type,"prototype")) ? (type.prototype) : (_LegacyCopy(type));
if (typeof definition !== "undefined" && !definition.hasOwnProperty.call(definition,"__new__")) {
definition["__new__"] = function(properties) {
_CastProps(properties, this);
};
(_protected_code_)(definition["__new__"]);
}
if (typeof definition !== "undefined" && !definition.hasOwnProperty.call(definition,"css")) {
definition["css"] = function QC_CSS3(_css) {
if (typeof this["body"] !== "undefined" && this["body"]["style"] !== "undefined") {
logger.debug("body style");
this["body"]["style"] = _Cast(_css, this["body"]["style"]);
}
};
(_protected_code_)(definition["css"]);
}
if (typeof definition !== "undefined" && !definition.hasOwnProperty.call(definition,"hierarchy")) {
definition["hierarchy"] = function hierarchy() {
var __classType = function(o_c) {
return (o_c.hasOwnProperty.call(o_c,"__classType")) ? (o_c.__classType) : ((o_c.hasOwnProperty.call(o_c,"__definition")) ? (o_c.__definition.__classType) : (ObjectName(o_c)));
};
var __hierarchy = [];
__hierarchy.push(__classType(this));
if (this.hasOwnProperty.call(this,"__definition")) {
__hierarchy = __hierarchy.concat(this.__definition.hierarchy.call(this.__definition));
}
return __hierarchy;
};
}
if (typeof definition !== "undefined" && !definition.hasOwnProperty.call(definition,"append")) {
definition["append"] = function QC_Append() {
var child = (arguments.length > 0) ? (arguments[0]) : (this["body"]);
if (typeof this["body"] !== "undefined") {
logger.debug("append element");
if (arguments.lenght > 0) {
logger.debug("append to element");
this["body"].append(child);
if (typeof this["childs"] === "undefined") {
this["childs"] = [];
}
this["childs"].push(child);
} else {
if (isBrowser) {
logger.debug("append to body");
document.body.append(child);
}
}
}
};
(_protected_code_)(definition["append"]);
}
if (typeof definition !== "undefined" && !definition.hasOwnProperty.call(definition,"attachIn")) {
definition["attachIn"] = function QC_AttachIn(tag) {
if (isBrowser) {
var tags = document.subelements(tag);
for (var i = 0, j = tags.length; i < j; i++) {
tags[i].append(this);
}
} else {
// not yet implemented.
}
};
(_protected_code_)(definition["attachIn"]);
}
// hack to prevent pre-population of __instanceID into the class definition
if (typeof definition !== "undefined" && definition.hasOwnProperty.call(definition,"__instanceID")){
delete definition.__instanceID;
}
o = Object.create(type, definition);
o["__definition"] = definition;
o["__definition"]["__classType"] = name;
_QC_CLASSES[name] = o;
_top[name] = _QC_CLASSES[name];
return _top[name];
};
Class.prototype.toString = function() {
return "Class(name, type, definition) { [QCObjects native code] }";
};
/**
* Returns the QCObjects Class Factory of a given ClassName
*
* @param {String} name
*/
var ClassFactory = function(className) {
var _classFactory;
if (className !== null && className.indexOf(".")>-1){
var packageName = className.split(".").slice(0,className.split(".").length-1).join(".");
var _className = className.split(".").slice(-1).join("");
var _package = Package(packageName);
var packageClasses = (typeof _package !== "undefined")?(_package.filter(classFactory=>{
return typeof classFactory !== "undefined"
&& classFactory.hasOwnProperty.call(classFactory,"__definition")
&& isQCObjects_Class(classFactory)
&& classFactory.__definition.__classType===_className
&& !classFactory.hasOwnProperty.call(classFactory,"__instanceID");}).reverse()):([]);
if (packageClasses.length>0){
_classFactory = packageClasses[0];
}
} else if (className !== null && _QC_CLASSES.hasOwnProperty.call(_QC_CLASSES,className)) {
_classFactory = _QC_CLASSES[className];
}
return _classFactory;
};
if (isBrowser) {
Element.prototype.append = function QC_Append(child) {
if (typeof child.__definition !== "undefined" && typeof child.__definition.__classType !== "undefined" && typeof child.body) {
this.appendChild(child.body);
} else {
this.appendChild(child);
}
};
/**
* A replacement for direct using of innerHTML
* use: [element].render('content') where 'content' is the string corresponding
* to the DOM to insert in the element
**/
Element.prototype.render = function QC_Render(content) {
var _self = this;
var _appendVDOM = function (_self,content){
if (typeof document.implementation.createHTMLDocument !== "undefined"){
var doc = document.implementation.createHTMLDocument("");
doc.innerHTML = content;
doc.body.subelements("*").map(function (element){
return _self.append(element);
});
}
};
if (typeof this.innerHTML !== "undefined"){
try {
this.innerHTML += content;
}catch (e){
_appendVDOM(_self,content);
}
} else {
_appendVDOM(_self,content);
}
};
}
/**
* Returns a method from a superior QCObjects Class
* It is useful for Class Inheritance in the _new_ and __new__ method constructors
* @example _super_('MySuperClass','MySuperMethod').call(this,params) #where this is the current instance and params are method parameters
*
* @param {String} className
* @param {String} classMethodName
* @param {Object} params
*/
var _super_ = function(className, classMethodName, params) {
return ClassFactory(className)[classMethodName];
};
_super_.prototype.toString = function() {
return "_super_(className,classMethodName,params) { [QCObjects native code] }";
};
/**
* Creates an object from a Class definition
*
* @param {QC_Object} o
* @param {Object} args
*/
var New = function(c, args) {
var args = (arguments.length > 1) ? (arguments[1]) : ({});
Object.__instanceID = (typeof Object.__instanceID === "undefined" || Object.__instanceID === null) ? (0) : (Object.__instanceID + 1);
__instanceID = Object.__instanceID;
var c_new = (typeof c === "undefined") ? (Object.create(({}).constructor.prototype, {})) : (Object.create(c.constructor.prototype, c.__definition));
c_new.__definition = _Cast({
"__instanceID": __instanceID
}, (typeof c !== "undefined") ? (c.__definition) : ({}));
c_new["__instanceID"] = __instanceID;
if (c_new.hasOwnProperty.call(c_new,"definition") && typeof c_new.__definition !== "undefined" && c_new.__definition !== null) {
c_new.__definition["__instanceID"] = __instanceID;
}
if (c_new.hasOwnProperty.call(c_new,"__new__")) {
if (typeof c_new !== "undefined" && !c_new.__definition.hasOwnProperty.call(c_new.__definition,"body")) {
try {
if (isBrowser) {
c_new["body"] = _Cast(c_new["__definition"], _DOMCreateElement(c_new.__definition.__classType));
c_new["body"]["style"] = _Cast(c_new.__definition, c_new["body"]["style"]);
} else {
c_new["body"] = {};
c_new["body"]["style"] = {};
}
} catch (e) {
c_new["body"] = {};
c_new["body"]["style"] = {};
}
} else if (c_new.__definition.hasOwnProperty.call(c_new.__definition,"body")) {
c_new["body"] = c_new.__definition.body;
}
c_new.__new__(args);
if (c_new.hasOwnProperty.call(c_new,"_new_")) {
c_new._new_(args);
}
}
return c_new;
};
New.prototype.toString = function() {
return "New(QCObjectsClassName, args) { [QCObjects native code] }";
};
var Export = function(f) {
if (isBrowser) {
try {
_top[f.name] = f;
window[f.name] = f;
} catch (e) {}
} else if (typeof global !== "undefined") {
if (!global.hasOwnProperty.call(global,f.name)) {
global[f.name] = f;
}
}
};
Export.prototype.toString = function() {
return "Export(function or symbol) { [QCObjects native code] }";
};
if (!isBrowser) {
var findPackageNodePath = function(packagename) {
const fs = require("fs");
var sdkPath = null;
try {
var sdkPaths = [
`${ClassFactory("CONFIG").get("projectPath")}${ClassFactory("CONFIG").get("relativeImportPath")}`,
`${ClassFactory("CONFIG").get("basePath")}${ClassFactory("CONFIG").get("relativeImportPath")}`,
`${ClassFactory("CONFIG").get("projectPath")}`,
`${ClassFactory("CONFIG").get("basePath")}`,
`${ClassFactory("CONFIG").get("relativeImportPath")}`,
`${process.cwd()}${ClassFactory("CONFIG").get("relativeImportPath")}`,
`${process.cwd()}/node_modules/` + packagename,
`${process.cwd()}/node_modules`,
`${process.cwd()}`,
"node_modules",
"./",
""
].concat(module.paths);
sdkPaths = sdkPaths.filter(p => {
return fs.existsSync(p + "/" + packagename);
});
if (sdkPaths.length > 0) {
sdkPath = sdkPaths[0];
logger.info(packagename + " is Installed.");
} else {
// logger.debug(packagename + ' is not in a standard path.');
}
} catch (e) {
// do nothing
console.log(e);
}
return sdkPath;
};
Export(findPackageNodePath);
}
Class("_Crypt", Object, {
last_string: "",
last_key: "",
construct: false,
_new_: function(o) {
var string = o["string"];
var key = (o.hasOwnProperty.call(o,"key")) ? (o["key"]) : (null);
this.__new__(o);
key = (key === null) ? (this.__instanceID) : (key);
this.last_key = key;
this.last_string = string;
this.construct = true;
},
_encrypt: function() {
var string = this.last_string;
var key = this.last_key;
var result = "";
var char;
var keychar;
for (var i = 0; i < string.length; i++) {
char = string.substr(i, 1);
keychar = key.substr((i % key.length) - 1, 1);
char = String.fromCharCode(char.charCodeAt(0) + keychar.charCodeAt(0));
result += char;
}
this.last_string = Base64.encode(result);
return this.last_string;
},
_decrypt: function() {
var string = this.last_string;
var key = this.last_key;
var result = "";
var char;
var keychar;
string = Base64.decode(string);
for (var i = 0; i < string.length; i++) {
char = string.substr(i, 1);
keychar = key.substr((i % key.length) - 1, 1);
char = String.fromCharCode(char.charCodeAt(0) - keychar.charCodeAt(0));
result += char;
}
this.last_string = result;
return this.last_string;
},
encrypt: function(string, key) {
var crypt = New(ClassFactory("_Crypt"), {
string: string,
key: (key !== "")?(key):("12345678ABC")
});
return crypt._encrypt();
},
decrypt: function(string, key) {
var crypt = New(ClassFactory("_Crypt"), {
string: string,
key: (key !== "")?(key):("12345678ABC")
});
return crypt._decrypt();
}
});
var _CryptObject = function(o) {
return ClassFactory("_Crypt").encrypt(_DataStringify(o), _secretKey);
};
var _DecryptObject = function(s) {
return JSON.parse(ClassFactory("_Crypt").decrypt(s, _secretKey));
};
Class("CONFIG", Object, {
_CONFIG: {
"relativeImportPath": "",
"remoteImportsPath": "",
"remoteSDKPath": "https://sdk.qcobjects.dev/",
"asynchronousImportsLoad": false,
"removePackageScriptAfterLoading":true,
"componentsBasePath": "",
"delayForReady": 0,
"preserveComponentBodyTag": true,
"overrideComponentTag": false,
"useConfigService": false,
"routingWay": "hash",
"useSDK": true,
"useLocalSDK": false,
"basePath": basePath
},
_CONFIG_ENC: null,
set: function(name, value) {
// hack to force update basePath from CONFIG
if (name === "basePath") {
basePath = value;
}
var _conf = (
function(config) {
if (config._CONFIG_ENC === null){
config._CONFIG_ENC = ClassFactory("_Crypt").encrypt(_DataStringify({}), _secretKey);
}
var _protectedEnc = config._CONFIG_ENC.valueOf();
var _protectedConf = config._CONFIG.valueOf();
return _CastProps(_protectedConf, _DecryptObject(_protectedEnc));
}
)(this);
_conf[name] = value;
this._CONFIG_ENC = _CryptObject(_conf);
if (this._CONFIG.hasOwnProperty.call(this._CONFIG,name)) {
this._CONFIG[name] = value;
}
},
get: function(name,_default) {
var _value;
try {
var _conf = (
function(config) {
if (config._CONFIG_ENC === null){
config._CONFIG_ENC = ClassFactory("_Crypt").encrypt(_DataStringify({}), _secretKey);
}
var _protectedEnc = config._CONFIG_ENC.valueOf();
var _protectedConf = config._CONFIG.valueOf();
return _CastProps(_protectedConf, _DecryptObject(_protectedEnc));
}
)(this);
if (typeof _conf[name] !== "undefined"){
_value = _conf[name];
} else if (typeof _default !== "undefined"){
_value = _default;
}
} catch (e){
logger.debug("Something wrong when trying to get CONFIG values");
logger.debug("No config value for: "+name);
_value = _default;
}
return _value;
}
});
var CONFIG = ClassFactory("CONFIG");
Export(CONFIG);
Export(waitUntil);
Export(_super_);
Export(ComplexStorageCache);
Export(ClassFactory);
Export(_DOMCreateElement);
var isQCObjects_Object = function (_){
return (typeof _ === "object"
&& _.hasOwnProperty.call(_,"__classType")
&& _.hasOwnProperty.call(_,"__instanceID")
&& _.hasOwnProperty.call(_,"__definition")
&& typeof _.__definition !== "undefined"
)?(true):(false);
};
var isQCObjects_Class = function (_){
return (typeof _ === "object"
&& (!_.hasOwnProperty.call(_,"__instanceID"))
&& _.hasOwnProperty.call(_,"__definition")
&& typeof _.__definition !== "undefined"
&& _.__definition.hasOwnProperty.call(_.__definition,"__classType")
)?(true):(false);
};
/**
* Defines a package for Class classification
*
* @param {Object} namespace
* @param {Object} classes
*/
var Package = function(namespace, classes) {
if (_QC_PACKAGES.hasOwnProperty.call(_QC_PACKAGES,namespace) &&
typeof _QC_PACKAGES[namespace] !== "undefined" &&
_QC_PACKAGES[namespace].hasOwnProperty.call(_QC_PACKAGES[namespace],"length") &&
_QC_PACKAGES[namespace].length > 0 &&
typeof classes !== "undefined" &&
classes.hasOwnProperty.call(classes,"length") &&
classes.length > 0
) {
for (var _c in classes.filter(
function (_c1){
return isQCObjects_Class(_c1);
}
)){
classes[_c].__definition.__namespace = namespace;
}
_QC_PACKAGES[namespace] = _QC_PACKAGES[namespace].concat(classes);
} else if (typeof classes !== "undefined"){
if (typeof classes === "object" && classes.hasOwnProperty.call(classes,"length")){
for (var _c in classes.filter(
function (_c1){
return isQCObjects_Class(_c1);
}
)){
classes[_c].__definition.__namespace = namespace;
}
} else if (isQCObjects_Class(classes)) {
classes.__definition.__namespace = namespace;
}
_QC_PACKAGES[namespace] = classes;
}
return (_QC_PACKAGES.hasOwnProperty.call(_QC_PACKAGES,namespace))?(_QC_PACKAGES[namespace]):(undefined);
};
Package.prototype.toString = function() {
return "Package(namespace, classes) { [QCObjects native code] }";
};
/**
* Imports a script with the package nomenclature
*
* @param {Object} packagename
* @param {Object} ready
* @param {Boolean} external
*/
var Import = function() {
var packagename;
var ready = function() {};
var external = false;
if (arguments.length < 1) {
return;
} else if (arguments.length === 1) {
packagename = arguments[0];
} else if (arguments.length === 2) {
packagename = arguments[0];
ready = arguments[1];
} else if (arguments.length > 2) {
packagename = arguments[0];
ready = arguments[1];
external = arguments[2];
logger.debug("[Import] Setting external=" + external.toString() + " resource to import: " + packagename);
}
if (external) {
logger.debug("[Import] Registering external resource to import: " + packagename);
} else {
logger.debug("[Import] Registering local resource to import: " + packagename);
}
var _promise_import_;
if (isBrowser) {
_promise_import_ = new Promise(function(resolve, reject) {
var allPackagesImported = function() {
var ret = false;
var cp = 0;
for (var p in _QC_PACKAGES) {
cp++;
}
if (cp < _QC_PACKAGES_IMPORTED.length) {
ret = false;
} else {
ret = true;
}
return ret;
};
var readyImported = function(e) {
_QC_PACKAGES_IMPORTED.push(ready);
if (allPackagesImported()) {
for (var _r in _QC_PACKAGES_IMPORTED) {
_QC_READY_LISTENERS.push(_QC_PACKAGES_IMPORTED[_r]);
}
}
if (isBrowser && ClassFactory("CONFIG").get("removePackageScriptAfterLoading")){
e.target.remove();
}
resolve.call(_promise_import_, {
"_imported_": e.target,
"_package_name_": packagename
});
};
if (!_QC_PACKAGES.hasOwnProperty.call(_QC_PACKAGES,packagename)) {
var s1 = _DOMCreateElement("script");
s1.type = "text/javascript";
s1.async = (ClassFactory("CONFIG").get("asynchronousImportsLoad")) ? (true) : (false);
s1.onreadystatechange = function() {
if (s1.readyState === "complete") {
readyImported.call();
}
};
s1.onload = readyImported;
s1.onerror = function(e) {
reject.call(_promise_import_, {
"_imported_": s1,
"_package_name_": packagename
});
};
s1.src = (external) ? (ClassFactory("CONFIG").get("remoteImportsPath") + packagename + ".js") : (basePath + ClassFactory("CONFIG").get("relativeImportPath") + packagename + ".js");
document.getElementsByTagName("head")[0].appendChild(s1);
}
});
_promise_import_.catch(function() {
logger.debug("Import: Error loading a package ");
});
} else {
// support to be used in a nodejs environment
_promise_import_ = new Promise(function(resolve, reject) {
try {
var standardNodePath = findPackageNodePath(packagename);
var packageAbsoluteName = "";
if (standardNodePath !== null) {
packageAbsoluteName = standardNodePath + "/" + packagename;
} else {
var jsNodePath = findPackageNodePath(packagename + ".js");
if (jsNodePath !== null) {
packageAbsoluteName = jsNodePath + "/" + packagename + ".js";
} else {
packageAbsoluteName = basePath + ClassFactory("CONFIG").get("relativeImportPath") + packagename;
}
}
try {
resolve.call(_promise_import_, {
"_imported_": require(`${packageAbsoluteName}`),
"_package_name_": packagename
});
}catch (e){
console.log(e);
reject.call(_promise_import_, {
"_imported_": null,
"_package_name_": packagename
});
}
} catch (e) {
console.log(e);
reject.call(_promise_import_, {
"_imported_": null,
"_package_name_": packagename
});
}
}).catch(function(e) {
// something wrong importing a package
console.log(e);
logger.debug("Something happened when importing " + packagename);
});
}
return _promise_import_;
};
Import.prototype.toString = function() {
return "Import(packagename,ready,external) { [QCObjects native code] }";
};
if (isBrowser) {
/**
* Adds a Cast functionality to every Element of DOM
*/
Element.prototype.Cast = function QC_Object(_o) {
_o.__definition.body = this;
var _o = New(_o);
return _o;
};
}
Class("TagElements", Array, {
show: function() {
this.map(function(element) {
return element.style.opacity = 1;
});
},
hide: function() {
this.map(function(element) {
return element.style.opacity = 0;
});
},
effect: function() {
var effectArguments = [...arguments].slice(1);
var effectClass = arguments[0];
if ((typeof effectClass).toLowerCase() === "string") {
effectClass = ClassFactory(effectClass);
}
this.map(function(element) {
return effectClass.apply.apply(effectClass, [element].concat(effectArguments));
});
},
findElements: function(elementName) {
var _o = New(ClassFactory("TagElements"));
if (isBrowser) {
for (var _k in this) {
if (typeof _k === "number" && typeof this[_k] !== "function" && this[_k].hasOwnProperty.call(this[_k],"subelements")) {
_o.push(this[_k].subelements(elementName));
}
}
} else {
// not yet implemented.
}
return _o;
}
});
/**
* Gets the element of DOM found by tag name
*
* @param {Object} tagname
* @param {Object} innerHTML
*/
var Tag = function(tagname, innerHTML) {
var _o = New(ClassFactory("TagElements"));
if (isBrowser) {
var o = document.subelements(tagname);
var addedKeys = [];
for (var _i = 0; _i < o.length; _i++) {
if (typeof innerHTML !== "undefined" && o[_i].hasOwnProperty.call(o[_i],"innerHTML")) {
o[_i].innerHTML = innerHTML;
}
if (addedKeys.indexOf(_i) < 0) {
_o.push(o[_i]);
addedKeys.push(_i);
}
}
} else {
// not yet implemented.
}
return _o;
};
/**
* Defines a Custom Ready listener
*/
function Ready(e) {
if (isBrowser) {
_QC_READY_LISTENERS.push(e.bind(window));
} else if (typeof global !== "undefined") {
_QC_READY_LISTENERS.push(e.bind(global));
}
}
var ready = Ready; // case insensitive ready option
/**
* Default Ready event function for window. Executes all micro ready events of Import calls
*
* @param {Object} e
*/
var _Ready = function(e) {
var _execReady = function() {
for (var _r in _QC_READY_LISTENERS) {
if (typeof _QC_READY_LISTENERS[_r] === "function") {
_QC_READY_LISTENERS[_r].call();
delete _QC_READY_LISTENERS[_r];
}
}
};
if (ClassFactory("CONFIG").get("delayForReady") > 0) {
if (isBrowser) {
setTimeout(_execReady.bind(window), ClassFactory("CONFIG").get("delayForReady"));
} else if (typeof global !== "undefined") {
setTimeout(_execReady.bind(global), ClassFactory("CONFIG").get("delayForReady"));
}
} else {
_execReady.call(_top);
}
};
if (isBrowser) {
window.onload = _Ready;
if (is_phonegap) {
document.addEventListener("deviceready", _Ready, captureFalse);
}
} else {
global.onload = _Ready;
}
/**
* Dynamic Data Objects Class
* Usage:
* Class('TestDDO',{
* _new_:function (){
* this.ddo = New(DDO,{
* instance:this,
* name:'ddo',
* value:0,
* fget:function (value){
* logger.debug('returned value '+ value );
* }
* })
* }
* });
*
*/
Class("DDO", Object, {
_new_: function({
instance,
name,
fget,
fset,
value
}) {
var _value;
var ddoInstance = this;
var name = (typeof name === "undefined") ? (ObjectName(ddoInstance)) : (name);
Object.defineProperty(instance, name, {
set(val) {
_value = val;
logger.debug("value changed " + name);
var ret;
if (typeof fset !== "undefined" && typeof fset === "function") {
ret = fset(_value);
} else {
ret = _value;
}
return ret;
},
get() {
logger.debug("returning value " + name);
var is_ddo = function(v) {
if (typeof v === "object" && v.hasOwnProperty.call(v,"value")) {
return v.value;
}
return v;
};
var ret;
if (typeof fget !== "undefined" && typeof fget === "function") {
ret = fget(is_ddo(_value));
} else {
ret = is_ddo(_value);
}
return ret;
}
});
}
});
Class("InheritClass", Object, {});
Class("DefaultTemplateHandler", Object, {
template: "",
assign: function(data) {
var parsedAssignmentText = this.template;
for (var k in data) {
parsedAssignmentText = parsedAssignmentText.replace((new RegExp("{{" + k + "}}", "g")), data[k]);
}
return parsedAssignmentText;
}
});
_top.__oldpopstate = _top.onpopstate;
Class("Component", Object, {
domain: domain,
basePath: basePath,
templateURI: "",
templateHandler: "DefaultTemplateHandler",
tplsource: "default",
url: "",
name: "",
method: "GET",
data: {},
reload: false,
shadowed:false,
cached: true,
done: function() {
//TODO: default done method
},
fail: function() {
//TODO: default fail method
},
set: function(name, value) {
this[name] = value;
},
get: function(name) {
return this[name];
},
rebuild: function() {
var _component = this;
var _promise = new Promise(function(resolve, reject) {
switch (true) {
case (typeof _component.get("tplsource") !== "undefined" &&
_component.get("tplsource") === "default" &&
typeof _component.get("templateURI") !== "undefined" &&
_component.get("templateURI") !== ""):
_component.set("url", _component.get("basePath") + _component.get("templateURI"));
componentLoader(_component, false).then(
function(standardResponse) {
resolve.call(_promise, standardResponse);
},
function(standardResponse) {
reject.call(_promise, standardResponse);
});
break;
case (typeof _component.get("tplsource") !== "undefined" &&
_component.get("tplsource") === "external" &&
typeof _component.get("templateURI") !== "undefined" &&
_component.get("templateURI") !== ""):
_component.set("url", _component.get("templateURI"));
componentLoader(_component, false).then(
function(standardResponse) {
resolve.call(_promise, standardResponse);
},
function(standardResponse) {
reject.call(_promise, standardResponse);
});
break;
case (typeof _component.get("tplsource") !== "undefined" &&
_component.get("tplsource") === "none"):
logger.debug("Component " + _component.name + " has specified template-source=none, so no template load was done");
var standardResponse = {
request: null,
component: _component
};
if (typeof _component.done === "function") {
_component.done.call(_component, standardResponse);
}
resolve(_promise, standardResponse);
break;
default:
logger.debug("Component " + _component.name + " will not be rebuilt because no templateURI is present");
reject.call(_promise, {
request: null,
component: _component
});
break;
}
});
return _promise;
},
Cast: function(o) {
return _Cast(this, o);
},
routingWay: null,
validRoutingWays: ["pathname", "hash", "search"],
routingNodes: [],
routings: [],
routingPath: "",
routingSelected: [],
_bindroute: function() {
if (isBrowser) {
if (!ClassFactory("Component")._bindroute.__assigned) {
document.addEventListener("componentsloaded", function(e) {
e.stopImmediatePropagation();
e.stopPropagation();
if (!ClassFactory("Component")._bindroute.__assigned) {
_top.onpopstate = function(e) {
e.stopImmediatePropagation();
e.stopPropagation();
ClassFactory("Component").route();
if (typeof e.target.__oldpopstate !== "undefined" && typeof e.target.__oldpopstate === "function") {
e.target.__oldpopstate.call(e.target, e);
}
};
Tag("a").map(function(a) {
a.oldclick = a.onclick;
a.onclick = function(e) {
var _ret_ = true;
if (!global.get("routingPaths")) {
global.set("routingPaths", []);
}
var routingWay = ClassFactory("CONFIG").get("routingWay");
var routingPath = e.target[routingWay];
if (global.get("routingPaths").includes(routingPath) &&
e.target[routingWay] !== document.location[routingWay] &&
e.target.href !== document.location.href
) {
logger.debug("A ROUTING WAS FOUND: " + routingPath);
window.history.pushState({
href: e.target.href
}, e.target.href, e.target.href);
ClassFactory("Component").route();
_ret_ = false;
} else {
logger.debug("NO ROUTING FOUND FOR: " + routingPath);
}
if (typeof e.target.oldclick !== "undefined" && typeof e.target.oldclick === "function") {
e.target.oldclick.call(e.target, e);
}
return _ret_;
};
return null;
});
ClassFactory("Component")._bindroute.__assigned = true;
}
}, captureFalse);
}
} else {
// not yet implemented.
}
},
route: function() {
var componentClass = this;
var isValidInstance = (componentClass.hasOwnProperty.call(componentClass,"__instanceID") &&
componentClass.hasOwnProperty.call(componentClass,"subcomponents")) ? (true) : (false);
var __route__ = function(routingComponents) {
for (var r = 0; r < routingComponents.length; r++) {
var rc = routingComponents[r];
if (rc.hasOwnProperty.call(rc,"_reroute_")){
rc._reroute_();
if (rc.hasOwnProperty.call(rc,"subcomponents") &&
typeof rc.subcomponents !== "undefined" &&
rc.subcomponents.length > 0
) {
logger.debug("LOOKING FOR ROUTINGS IN SUBCOMPONENTS FOR: " + rc.name);
__route__.call(componentClass, rc.subcomponents);
}
} else {
logger.debug("IT WAS NOT POSSIBLE TO RE-ROUTE: " + rc.name);
}
}
};
if (isValidInstance || global.hasOwnProperty.call(global,"componentsStack")) {
if (isValidInstance && componentClass.hasOwnProperty.call(componentClass,"name")) {
logger.debug("loading routings for instance" + componentClass.name);
}
__route__.call(componentClass, (isValidInstance) ? (componentClass.subcomponents) : (global.componentsStack));
} else {
logger.debug("An undetermined result expected if load routings. So will not be loaded this time.");
}
},
fullscreen: function() {
if (isBrowser) {
var elem = this.body;
if (elem.requestFullscreen) {
elem.requestFullscreen();
} else if (elem.mozRequestFullScreen) {
/* Firefox */
elem.mozRequestFullScreen();
} else if (elem.webkitRequestFullscreen) {
/* Chrome, Safari & Opera */
elem.webkitRequestFullscreen();
} else if (elem.msRequestFullscreen) {
/* IE/Edge */
elem.msRequestFullscreen();
}
} else {
// not yet implemented.
}
},
closefullscreen: function() {
if (isBrowser) {
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.webkitExitFullscreen) {
document.webkitExitFullscreen();
} else if (document.msExitFullscreen) {
document.msExitFullscreen();
}
} else {
// noy yet implemented.
}
},
_generateRoutingPaths: function(c) {
if (isBrowser) {
if (this.validRoutingWays.includes(this.routingWay)) {
if (typeof c !== "undefined") {
this.innerHTML = c.innerHTML;
this.routingNodes = c.subelements("routing");
this.routings = [];
for (var r = 0; r < this.routingNodes.length; r++) {
var routingNode = this.routingNodes[r];
var attributeNames = routingNode.getAttributeNames();
var routing = {};
for (var a = 0; a < attributeNames.length; a++) {
routing[attributeNames[a]] = routingNode.getAttribute(attributeNames[a]);
}
this.routings.push(routing);
if (!global.get("routingPaths")) {
global.set("routingPaths", []);
}
if (!global.get("routingPaths").includes(routing.path)) {
global.get("routingPaths").push(routing.path);
}
}
}
}
} else {
// not yet implemented.
}
},
parseTemplate: function (template){
var _self = this;
var _parsedAssignmentText;
if (_self.hasOwnProperty.call(_self,"templateHandler")) {
var value = template;
var templateHandlerName = _self.templateHandler;
var templateHandlerClass = ClassFactory(_self.templateHandler);
var templateInstance = New(templateHandlerClass, {
template: value
});
_parsedAssignmentText = templateInstance.assign(_self.data);
} else {
_parsedAssignmentText = value;
}
return _parsedAssignmentText;
},
_new_: function(properties) {
this.routingWay = ClassFactory("CONFIG").get("routingWay");
var self = this;
Object.defineProperty(self, "body", {
set(value) {
self._body = value;
self._generateRoutingPaths(value);
},
get() {
return self._body;
}
});
Object.defineProperty(self, "cacheIndex", {
set(value) {
// readonly
logger.debug("[cacheIndex] This property is readonly");
},
get() {
return Base64.encode(self.name + _DataStringify(self.routingSelected));
}
});
Object.defineProperty(self, "parsedAssignmentText", {
set(value) {
// readonly
logger.debug("[parsedAssignmentText] This property is readonly");
},
get() {
self._parsedAssignmentText = self.parseTemplate(self.template);
return self._parsedAssignmentText;
}
});
Object.defineProperty(self, "shadowRoot", {
set(value) {
if (typeof self.__shadowRoot == "undefined"){
self.__shadowRoot = value;
} else {
logger.debug("[shadowRoot] This property can only be assigned once!");
}
},
get() {
return self.__shadowRoot;
}
});
this.__new__(properties);
if (!this._reroute_()) {
this.rebuild().catch(function(standardResponse) {
logger.debug("Component not rebuilt");
});
}
},
_reroute_: function() {
//This method set the selected routing and makes the switch to the templateURI
var rc = this;
var _rebuilt = false;
if (isBrowser){
if (rc.validRoutingWays.includes(rc.routingWay)) {
rc.routingPath = document.location[rc.routingWay];
rc.routingSelected = rc.routings.filter(function(routing) {
return (new RegExp(routing.path, "g")).test(rc.routingPath);
}).reverse();
for (var r = 0; r < rc.routingSelected.length; r++) {
var routing = rc.routingSelected[r];
var componentURI = ComponentURI({
"COMPONENTS_BASE_PATH": ClassFactory("CONFIG").get("componentsBasePath"),
"COMPONENT_NAME": routing.name.toString(),
"TPLEXTENSION": rc.tplextension,
"TPL_SOURCE": "default" //here is always default in order to get the right uri
});
rc.templateURI = componentURI;
}
if (rc.routingSelected.length > 0) {
rc.template = "";
rc.body.innerHTML = "";
rc.rebuild().then(function() {
// not yet implemented.
}).catch(function(standardResponse) {
logger.debug("Component not rebuilt");
});
_rebuilt = true;
}
}
}
return _rebuilt;
},
lazyLoadImages: function (){
if (isBrowser){
var component = this;
var _componentRoot = (component.shadowed)?(component.shadowRoot):(component.body);
var _imgLazyLoaded = [..._componentRoot.subelements("img[lazy-src]")];
var _lazyLoadImages = function(image) {
image.setAttribute("src", image.getAttribute("lazy-src"));
image.onload = () => {
image.removeAttribute("lazy-src");
};
};
if ("IntersectionObserver" in window) {
var observer = new IntersectionObserver((items, observer) => {
items.forEach((item) => {
if (item.isIntersecting) {
_lazyLoadImages(item.target);
observer.unobserve(item.target);
}
});
});
_imgLazyLoaded.map(function(img) {
return observer.observe(img);
});
} else {
_imgLazyLoaded.map(_lazyLoadImages);
}
} else {
// not yet implemented
}
return null;
},
scrollIntoHash: function (){
if (isBrowser){
var component = this;
if (document.location.hash !== ""){
var scrollIntoHash = component.body.subelements(document.location.hash);
if (scrollIntoHash.length>0 && (typeof scrollIntoHash[0].scrollIntoView === "function")){
scrollIntoHash[0].scrollIntoView(
ClassFactory("CONFIG").get("scrollIntoHash",{behavior: "auto", block: "center", inline: "center"})
);
}
}
} else {
// not yet implemented
}
},
i18n_translate: function (){
if (isBrowser){
if (ClassFactory("CONFIG").get("use_i18n")){
var component = this;
var lang1=ClassFactory("CONFIG").get("lang","en");
var lang2 = navigator.language.slice(0, 2);
var i18n = global.get("i18n");
if ((lang1 !== lang2) && (typeof i18n === "object" && i18n.hasOwnProperty.call(i18n,"messages"))){
var callback_i18n = function (){
var component = this;
return new Promise(function (resolve, reject){
var messages = i18n.messages.filter(function (message){
return message.hasOwnProperty.call(message,lang1) && message.hasOwnProperty.call(message,lang2);
});
component.body.subelements("ul,li,h1,h2,h3,a,b,p,input,textarea,summary,details,option,component")
.map(function (element){
messages.map(function (message){
var _innerHTML = element.innerHTML;
_innerHTML = _innerHTML.replace(new RegExp(`${message[lang1]}`,"g"),message[lang2]);
element.innerHTML = _innerHTML;
return null;
});
return element;
});
resolve();
});
};
callback_i18n.call(component).then(function (){
logger.debug("i18n loaded for component: "+component.name);
});
}
}
} else {
// not yet implemented
}
},
runComponentHelpers: function() {
if (isBrowser){
var component = this;
/*
* BEGIN use i18n translation
*/
component.i18n_translate();
/*
* END use i18n translation
*/
/*
* BEGIN component scrollIntoHash
*/
component.scrollIntoHash();
/*
* END component scrollIntoHash
*/
/*
* BEGIN component images lazy-load
*/
component.lazyLoadImages();
/*
* END component images lazy-load
*/
} else {
// not yet implemented
}
}
});
ClassFactory("Component")._bindroute.__assigned=false;
Class("Controller", Object, {
dependencies: [],
component: null,
routingSelectedAttr: function (attrName){
return this.component.routingSelected.map(function (r){return r[attrName];}).filter(function (v){return v;}).pop();
},
isTouchable:function (){
return ("ontouchstart" in window)
|| (navigator.MaxTouchPoints > 0)
|| (navigator.msMaxTouchPoints > 0);
},
onpress:function (subelementSelector,handler){
try {
if (this.isTouchable()){
this.component.body.subelements(subelementSelector)[0].addEventListener("touchstart",handler, {passive:true});
} else {
this.component.body.subelements(subelementSelector)[0].addEventListener("click",handler, {passive:true});
}
}catch (e){
logger.debug("No button to assign press event");
}
},
createRoutingController: function (){
var controller = this;
var component = controller.component;
var controllerName = controller.routingSelectedAttr("controllerclass");
if (typeof controllerName !== "undefined"){
var _Controller = ClassFactory(controllerName);
if (typeof _Controller !== "undefined") {
component.routingController = New(_Controller, {
component: component
}); // Initializes the main controller for the component
if (component.routingController.hasOwnProperty.call(component.routingController,"done") && typeof component.routingController.done === "function") {
component.routingController.done.call(component.routingController);
}
}
}
}
});
Class("View", Object, {
dependencies: [],
component: null
});
Class("Service", Object, {
domain: domain,
basePath: basePath,
url: "",
method: "GET",
data: {},
reload: false,
cached: false,
set: function(name, value) {
this[name] = value;
},
get: function(name) {
return this[name];
}
});
Class("JSONService", ClassFactory("Service"), {
method: "GET",
cached: false,
headers: {
"Content-Type": "application/json",
"charset": "utf-8"
},
JSONresponse: null,
done: function(result) {
logger.debug("***** RECEIVED RESPONSE:");
logger.debug(result.service.template);
this.JSONresponse = JSON.parse(result.service.template);
}
});
Class("ConfigService", ClassFactory("JSONService"), {
method: "GET",
cached: false,
configFileName: "config.json",
headers: {
"Content-Type": "application/json",
"charset": "utf-8"
},
JSONresponse: null,
done: function(result) {
logger.debug("***** CONFIG LOADED:");
logger.debug(result.service.template);
this.JSONresponse = JSON.parse(result.service.template);
if (this.JSONresponse.hasOwnProperty.call(this.JSONresponse,"__encoded__")) {
this.JSONresponse = JSON.parse(ClassFactory("_Crypt").decrypt(this.JSONresponse.__encoded__, _secretKey));
}
for (var k in this.JSONresponse) {
ClassFactory("CONFIG").set(k, this.JSONresponse[k]);
}
this.configLoaded.call(this);
},
fail: function(result) {
this.configLoaded.call(this);
},
_new_: function(o) {
this.set("url", this.get("basePath") + this.get("configFileName"));
}
});
Class("VO", Object, {});
/**
* Returns a standarized uri for a component
* @example
* templateURI = ComponentURI({'COMPONENTS_BASE_PATH':'','COMPONENT_NAME':'','TPLEXTENSION':'','TPL_SOURCE':''})
* @author: Jean Machuca <correojean@gmail.com>
* @param params an object with the params to build the uri path
*/
var ComponentURI = function(params) {
var templateURI = "";
if (params["TPL_SOURCE"] === "default") {
templateURI = "{{COMPONENTS_BASE_PATH}}{{COMPONENT_NAME}}.{{TPLEXTENSION}}";
for (var k in params) {
var param = params[k];
templateURI = templateURI.replace("{{" + k + "}}", params[k]);
}
}
return templateURI;
};
/**
* Loads a simple component from a template
*
* @author: Jean Machuca <correojean@gmail.com>
* @param component a Component object
*/
var componentLoader = function(component, _async) {
var _componentLoader = function(component, _async) {
var _promise = new Promise(function(resolve, reject) {
var container = (component.hasOwnProperty.call(component,"container") && typeof component.container !== "undefined" && component.container !== null) ? (component.container) : (component.body);
if (container !== null) {
var feedComponent = function(component) {
var parsedAssignmentText = component.parsedAssignmentText;
component.innerHTML = parsedAssignmentText;
if (component.shadowed){
logger.debug("COMPONENT {{NAME}} is shadowed".replace("{{NAME}}", component.name));
logger.debug("Preparing slots for Shadowed COMPONENT {{NAME}}".replace("{{NAME}}", component.name));
var tmp_shadowContainer = _DOMCreateElement("div");
container.subelements("[slot]").map(
function (c){
if (c.parentElement===container){
tmp_shadowContainer.appendChild(c);
}
});
logger.debug("Creating shadowedContainer for COMPONENT {{NAME}}".replace("{{NAME}}", component.name));
var shadowContainer = _DOMCreateElement("div");
shadowContainer.classList.add("shadowHost");
try {
component.shadowRoot = shadowContainer.attachShadow({mode: "open"});
} catch (e){
try {
logger.debug("Shadowed COMPONENT {{NAME}} is repeated".replace("{{NAME}}", component.name));
component.shadowRoot = shadowContainer.shadowRoot;
} catch (e){
logger.debug("Shadowed COMPONENT {{NAME}} is not allowed on this browser".replace("{{NAME}}", component.name));
}
}
if (typeof component.shadowRoot !== "undefined" && component.shadowRoot !== null){
if (component.reload) {
logger.debug("FORCED RELOADING OF CONTAINER FOR Shadowed COMPONENT {{NAME}}".replace("{{NAME}}", component.name));
shadowContainer.shadowRoot.innerHTML = component.innerHTML;
} else {
tmp_shadowContainer.innerHTML = component.parseTemplate(tmp_shadowContainer.innerHTML);
logger.debug("ADDING Shadowed COMPONENT {{NAME}} ".replace("{{NAME}}", component.name));
shadowContainer.shadowRoot.innerHTML += component.innerHTML;
}
logger.debug("ADDING Slots to Shadowed COMPONENT {{NAME}} ".replace("{{NAME}}", component.name));
shadowContainer.innerHTML += tmp_shadowContainer.innerHTML;
logger.debug("APPENDING Shadowed COMPONENT {{NAME}} to Container ".replace("{{NAME}}", component.name));
if (container.subelements(".shadowHost")<1){
container.appendChild(shadowContainer);
} else {
logger.debug("Shadowed Container for COMPONENT {{NAME}} is already present in the tree ".replace("{{NAME}}", component.name));
}
} else {
logger.debug("Shadowed COMPONENT {{NAME}} is bad configured".replace("{{NAME}}", component.name));
}
} else {
if (component.reload) {
logger.debug("FORCED RELOADING OF CONTAINER FOR COMPONENT {{NAME}}".replace("{{NAME}}", component.name));
container.innerHTML = component.innerHTML;
} else {
logger.debug("ADDING COMPONENT {{NAME}} ".replace("{{NAME}}", component.name));
container.innerHTML += component.innerHTML;
}
}
var standardResponse = {
"request": xhr,
"component": component
};
resolve.call(_promise, standardResponse);
};
logger.debug("LOADING COMPONENT DATA {{DATA}} FROM {{URL}}".replace("{{DATA}}", _DataStringify(component.data)).replace("{{URL}}", component.url));
var _componentLoaded = function() {
var successStatus = (is_file) ? (0) : (200);
if (xhr.status === successStatus) {
var response = xhr.responseText;
logger.debug("Data received {{DATA}}".replace("{{DATA}}", _DataStringify(response)));
logger.debug("CREATING COMPONENT {{NAME}}".replace("{{NAME}}", component.name));
component.template = response;
if (component.cached && (typeof cache !== "undefined")) {
cache.save(component.name, component.template);
}
feedComponent.call(this, component);
} else {
var standardResponse = {
"request": xhr,
"component": component
};
reject.call(_promise, standardResponse);
}
};
if (typeof component.template === "string" && component.template !== ""){
// component already has a template it does not need to be reloaded
feedComponent.call(this, component);
} else {
var is_file = (component.url.startsWith("file:")) ? (true) : (false);
var xhr = new XMLHttpRequest();
if (!is_file){
try {
logger.debug("Calling the url of component in async mode.");
xhr.open(component.method, component.url, true);
} catch (e){
logger.debug("Last try has failed... The component cannot be loaded.");
}
} else {
if ("fetch" in _top){
logger.debug("I can use fetch...");
logger.debug("It is a file to be loaded, so I will try to use fetch");
var _p = fetch (component.url).then(response=>{
logger.debug("I got a response from fetch, so I'll feed the component");
response.text().then(text=>{
component.template=text;
feedComponent.call(this, component);
});
});
}
}
if (!is_phonegap && !is_file) {
xhr.setRequestHeader("Content-Type", "text/html");
}
if (!is_file) {
xhr.onload = _componentLoaded;
}
var _directLoad = function(is_file) {
is_file = (typeof is_file === "undefined" || !is_file)?(false):(true);
logger.debug("SENDING THE NORMAL REQUEST ");
if (is_file) {
if(!("fetch" in _top)){
logger.debug("I have to try to load the file using xhr... ");
xhr.send(null);
if (xhr.status === XMLHttpRequest.DONE) {
_componentLoaded.call(this);
}
}
} else {
logger.debug("Trying to send the data to the component... ");
xhr.send(_DataStringify(component.data));
}
};
if (component.cached && (!is_file)) {
logger.debug("USING CACHE FOR COMPONENT: " + component.name);
var cache = new ComplexStorageCache({
"index": component.cacheIndex,
"load": function(cacheController) {
_directLoad.call(this,is_file);
},
"alternate": function(cacheController) {
if (component.method === "GET") {
component.template = cacheController.cache.getCached(component.cacheIndex);
feedComponent.call(this, component);
} else {
_directLoad.call(this,is_file);
}
return;
}
});
global.lastCache = cache;
} else {
logger.debug("NOT USING CACHE FOR COMPONENT: " + component.name);
_directLoad.call(this,is_file);
}
}
return;
} else {
logger.debug("CONTAINER DOESNT EXIST");
}
});
_promise.then(function(standardResponse) {
var _ret_;
if (typeof component.done === "function") {
_ret_ = component.done.call(component, standardResponse);
}
return Promise.resolve(_ret_);
}, function(standardResponse) {
var _ret_;
if (typeof component.fail === "function") {
_ret_ = component.fail.call(component, standardResponse);
}
return Promise.reject(_ret_);
}).catch(function(e) {
logger.debug("Something wrong loading the component");
});
return _promise;
};
var _ret_;
if (typeof _async !== "undefined" && _async) {
_ret_ = asyncLoad(_componentLoader, arguments);
} else {
_ret_ = _componentLoader(component, _async);
}
return _ret_;
};
/**
* Loads a simple component from a template
*
* @author: Jean Machuca <correojean@gmail.com>
* @param service a Service object
*/
var serviceLoader = function(service, _async) {
var _serviceLoaderInBrowser = function(service, _async) {
var _promise = new Promise(
function(resolve, reject) {
logger.debug("LOADING SERVICE DATA {{DATA}} FROM {{URL}}".replace("{{DATA}}", _DataStringify(service.data)).replace("{{URL}}", service.url));
var xhr = new XMLHttpRequest();
xhr.withCredentials = service.withCredentials;
var xhrasync = true; // always async because xhr sync is deprecated
xhr.open(service.method, service.url, xhrasync);
for (var header in service.headers) {
xhr.setRequestHeader(header, service.headers[header]);
}
xhr.onload = function() {
if (xhr.status === 200) {
var response = xhr.responseText;
logger.debug("Data received {{DATA}}".replace("{{DATA}}", _DataStringify(response)));
logger.debug("CREATING SERVICE {{NAME}}".replace("{{NAME}}", service.name));
service.template = response;
if (service.cached && (typeof cache !== "undefined")) {
cache.save(service.name, service.template);
}
if (typeof service.done === "function") {
var standardResponse = {
"request": xhr,
"service": service
};
service.done.call(service, standardResponse);
resolve.call(_promise, standardResponse);
}
} else {
if (typeof service.fail === "function") {
var standardResponse = {
"request": xhr,
"service": service
};
service.fail.call(service, standardResponse);
reject.call(_promise, standardResponse);
}
}
};
var _directLoad = function() {
logger.debug("SENDING THE NORMAL REQUEST ");
try {
xhr.send(_DataStringify(service.data));
} catch (e) {
logger.debug("SOMETHING WRONG WITH REQUEST ");
reject.call(_promise, {
request: xhr,
service: service
});
}
};
if (service.cached) {
var cache = new ComplexStorageCache({
"index": service.data,
"load": function(cacheController) {
_directLoad.call(this);
},
"alternate": function(cacheController) {
if (service.method === "GET") {
service.template = cacheController.cache.getCached(service.name);
if (typeof service.done === "function") {
var standardResponse = {
"request": xhr,
"service": service
};
service.done.call(service, standardResponse);
resolve.call(_promise, standardResponse);
}
} else {
_directLoad.call(this);
}
return;
}
});
global.lastCache = cache;
} else {
_directLoad.call(this);
}
return xhr;
}
);
return _promise;
};
var _serviceLoaderInNode = function(service, _async) {
var _promise = new Promise(
function(resolve, reject) {
var serviceURL = new URL(service.url);
var req;
service.useHTTP2 = service.hasOwnProperty.call(service,"useHTTP2") && service.useHTTP2;
try {
var requestOptions;
if (service.useHTTP2) {
logger.debug("using http2");
var http2 = require("http2");
var client = http2.connect(serviceURL.origin);
requestOptions = Object.assign({
":method": service.method,
":path": serviceURL.pathname
}, service.options);
requestOptions = Object.assign(requestOptions,service.headers);
req = client.request(requestOptions);
req.setEncoding("utf8");
} else {
var request = require("request");
requestOptions = Object.assign({
"url": service.url,
headers: service.headers
}, service.options);
var req = request[service.method.toLowerCase()](service.url);
}
logger.debug("LOADING SERVICE DATA (non-browser) {{DATA}} FROM {{URL}}".replace("{{DATA}}", _DataStringify(service.data)).replace("{{URL}}", service.url));
var dataXML;
var standardResponse = {
"http2Client": client,
"request": req,
"service": service,
"responseHeaders": null
};
if (typeof service.data === "object" && service.data !== null){
if (service.useHTTP2){
try {
logger.debug("Sending data...");
let buffer = new Buffer(_DataStringify(service.data));
req.write(buffer);
}catch (e){
logger.debug("It was not possible to send any data");
}
}
}
dataXML = "";
req.on("response", (responseHeaders,flags) => {
logger.debug("receiving response...");
standardResponse.responseHeaders = responseHeaders;
for (const name in responseHeaders) {
logger.debug(`${name}: ${responseHeaders[name]}`);
}
dataXML = "";
});
req.on("data", (chunk) => {
logger.debug("receiving data...");
// do something with the data
dataXML += ""+ chunk.toString();
});
if (service.useHTTP2){
req.resume();
}
req.on("end", () => {
logger.debug("ending call...");
service.template = dataXML;
if (service.hasOwnProperty.call(service,"useHTTP2") && service.useHTTP2) {
client.destroy();
} else {
req.destroy();
}
service.done.call(service, standardResponse);
resolve.call(_promise, standardResponse);
});
if (service.useHTTP2){
req.end();
}
} catch (e) {
logger.debug(e);
service.fail.call(service, e);
reject.call(_promise, e);
}
}).catch(function(e) {
console.log(e);
logger.debug("Something happened when trying to call the service: " + service.name);
service.fail.call(service, e);
});
return _promise;
};
var _ret_;
if (isBrowser) {
if (typeof _async !== "undefined" && _async) {
_ret_ = asyncLoad(_serviceLoaderInBrowser, arguments);
} else {
_ret_ = _serviceLoaderInBrowser(service, _async);
}
} else {
_ret_ = _serviceLoaderInNode(service, _async);
}
return _ret_;
};
Export(serviceLoader);
Export(componentLoader);
Export(ComponentURI);
Export(ObjectName);
Export(_DataStringify);
Export(isQCObjects_Class);
Export(isQCObjects_Object);
asyncLoad(function() {
Class("global", Object, {
_GLOBAL: {},
set: function(name, value) {
this._GLOBAL[name] = value;
},
get: function(name,_default) {
var _value;
if (typeof this._GLOBAL[name] !== "undefined"){
_value = this._GLOBAL[name];
} else if (typeof _default !== "undefined"){
_value = _default;
}
return _value;
},
__start__: function() {
var __load__serviceWorker = function() {
var _promise;
if (isBrowser) {
_promise = new Promise(function(resolve, reject) {
if (("serviceWorker" in navigator) &&
(typeof ClassFactory("CONFIG").get("serviceWorkerURI") !== "undefined")) {
ClassFactory("CONFIG").set("serviceWorkerScope", ClassFactory("CONFIG").get("serviceWorkerScope") ? (ClassFactory("CONFIG").get("serviceWorkerScope")) : ("/"));
navigator.serviceWorker.register(ClassFactory("CONFIG").get("serviceWorkerURI"), {
scope: ClassFactory("CONFIG").get("serviceWorkerScope")
})
.then(function(registration) {
logger.debug("Service Worker Registered");
resolve.call(_promise, registration);
}, function(registration) {
logger.debug("Error registering Service Worker");
reject.call(_promise, registration);
});
navigator.serviceWorker.ready.then(function(registration) {
logger.debug("Service Worker Ready");
resolve.call(_promise, registration);
}, function(registration) {
logger.debug("Error loading Service Worker");
reject.call(_promise, registration);
});
}
});
}
return _promise;
};
var _buildComponents = function() {
if (isBrowser) {
logger.debug("Starting to bind routes");
ClassFactory("Component")._bindroute.call(ClassFactory("Component"));
logger.debug("Starting to building components");
global.componentsStack = document.buildComponents.call(document);
logger.debug("Initializing the service worker");
__load__serviceWorker.call(_top).catch(function() {
logger.debug("error loading the service worker");
});
}
};
if (ClassFactory("CONFIG").get("useConfigService")) {
global.configService = New(ClassFactory("ConfigService"));
global.configService.configLoaded = _buildComponents;
serviceLoader(global.configService);
} else {
_buildComponents.call(this);
}
}
});
Object.defineProperty(global,"PackagesNameList",{
set(val){
logger.debug("PackagesNameList is readonly");
return;
},
get(){
var _get_packages_names = function (_packages){
var _keys = [];
for (var _k in _packages){
if (
typeof _packages[_k] !== "undefined"
&& _packages[_k].hasOwnProperty.call(_packages[_k],"length")
&& _packages[_k].length>0
){
_keys.push(_k);
_keys = _keys.concat(_get_packages_names(_packages[_k]));
}
}
return _keys;
};
return _get_packages_names(_QC_PACKAGES);
}
});
Object.defineProperty(global,"PackagesList",{
set(value){
logger.debug("PackagesList is readonly");
return;
},
get(){
return global.PackagesNameList.map(function (packagename) {
return {
packageName:packagename,
classesList:Package(packagename).filter(function (_packageClass) {
return isQCObjects_Class(_packageClass);
}
)
};
});
}
});
Object.defineProperty(global,"ClassesList",{
set(value){
logger.debug("ClassesList is readonly");
return;
},
get(){
var _classesList = [];
global.PackagesList.map(function (_package_element){
_classesList = _classesList.concat(_package_element.classesList.map(
function (_class_element){
return {
packageName:_package_element.packageName,
className:_package_element.packageName+"."+_class_element.__definition.__classType,
classFactory:_class_element
};
}
));
return _package_element;
});
return _classesList;
}
});
Object.defineProperty(global,"ClassesNameList",{
set(value){
logger.debug("ClassesNameList is readonly");
return;
},
get(){
return global.ClassesList.map(function (_class_element) {
return _class_element.className;
});
}
});
if (isBrowser) {
// use of GLOBAL word is deprecated in node.js
// this is only for compatibility purpose with old versions of QCObjects in browsers
Class("GLOBAL", _QC_CLASSES["global"]); // case insensitive for compatibility con old versions;
Export(ClassFactory("GLOBAL"));
}
Export(global);
if (ClassFactory("CONFIG").get("useSDK")) {
(function() {
var remoteImportsPath = ClassFactory("CONFIG").get("remoteImportsPath");
var external = (!ClassFactory("CONFIG").get("useLocalSDK")) ? (true) : (false);
ClassFactory("CONFIG").set("remoteImportsPath", ClassFactory("CONFIG").get("remoteSDKPath"));
var tryImportingSDK = false;
var sdkName = "QCObjects-SDK";
if (isBrowser) {
tryImportingSDK = true;
} else {
var sdkPath = findPackageNodePath("qcobjects-sdk");
if (sdkPath !== null) {
sdkName = "qcobjects-sdk";
tryImportingSDK = true;
} else {
sdkName = "node_modules/qcobjects-sdk/QCObjects-SDK";
tryImportingSDK = true;
}
}
if (tryImportingSDK) {
logger.info("Importing SDK... " + sdkName);
Import(sdkName, function() {
if (external) {
logger.debug("QCObjects-SDK.js loaded from remote location");
} else {
logger.debug("QCObjects-SDK.js loaded from local");
}
ClassFactory("CONFIG").set("remoteImportsPath", remoteImportsPath);
}, external);
} else {
logger.debug("SDK has not been imported as it is not available at the moment");
}
}).call(null);
}
}, null);
if (isBrowser) {
Element.prototype.buildComponents = function(rebuildObjects = false) {
var tagFilter = (rebuildObjects) ? ("component:not([loaded])") : ("component");
var d = this;
var _buildComponent = function(components) {
var componentsBuiltWith = [];
for (var _c = 0; _c < components.length; _c++) {
var data = {};
var attributenames = components[_c].getAttributeNames().filter(function(a) {
return a.startsWith("data-");
}).map(function(a) {
return a.split("-")[1];
});
for (var attribute in attributenames) {
data[attributenames[attribute]] = components[_c].getAttribute("data-" + attributenames[attribute]);
}
var componentDone = function() {
var viewName = this.body.getAttribute("viewClass");
var _View = ClassFactory(viewName);
if (typeof _View !== "undefined") {
this.view = New(_View, {
component: this
}); // Initializes the main view for the component
if (this.view.hasOwnProperty.call(this.view,"done") && typeof this.view.done === "function") {
this.view.done.call(this.view);
}
}
var controllerName = this.body.getAttribute("controllerClass");
if (!controllerName){
controllerName = "Controller";
}
var _Controller = ClassFactory(controllerName);
if (typeof _Controller !== "undefined") {
this.controller = New(_Controller, {
component: this
}); // Initializes the main controller for the component
if (this.controller.hasOwnProperty.call(this.controller,"done") && typeof this.controller.done === "function") {
this.controller.done.call(this.controller);
}
if (this.controller.hasOwnProperty.call(this.controller,"createRoutingController")){
this.controller.createRoutingController.call(this.controller);
}
}
var effectClassName = this.body.getAttribute("effectClass");
var _Effect = ClassFactory(effectClassName);
if (typeof _Effect !== "undefined") {
this.effect = New(_Effect, {
component: this
});
this.effect.apply(this.effect.defaultParams);
}
if (this.shadowed && (typeof this.shadowRoot !== "undefined")){
this.subcomponents = _buildComponent(this.shadowRoot.subelements(tagFilter));
} else {
this.subcomponents = _buildComponent(this.body.subelements(tagFilter));
}
if (ClassFactory("CONFIG").get("overrideComponentTag")) {
this.body.outerHTML = this.body.innerHTML;
}
this.body.setAttribute("loaded", true);
this.runComponentHelpers();
if ((Tag("component[loaded=true]").length * 100 / Tag("component:not([template-source=none])").length) >= 100) {
d.dispatchEvent(new CustomEvent("componentsloaded", {
detail: {
lastComponent: this
}
}));
}
};
(_protected_code_)(componentDone);
var __shadowed_not_set = (components[_c].getAttribute("shadowed") === null) ? (true) : (false);
var shadowed = (components[_c].getAttribute("shadowed") === "true") ? (true) : (false);
var __cached_not_set = (components[_c].getAttribute("cached") === null) ? (true) : (false);
var cached = (components[_c].getAttribute("cached") === "true") ? (true) : (false);
var tplextension = (typeof ClassFactory("CONFIG").get("tplextension") !== "undefined") ? (ClassFactory("CONFIG").get("tplextension")) : ("html");
tplextension = (components[_c].getAttribute("tplextension") !== null) ? (components[_c].getAttribute("tplextension")) : (tplextension);
var tplsource = (components[_c].getAttribute("template-source") === null) ? ("default") : (components[_c].getAttribute("template-source"));
var _componentName = components[_c].getAttribute("name");
var _componentClassName = (components[_c].getAttribute("componentClass") !== null) ? (components[_c].getAttribute("componentClass")) : ("Component");
var __componentClassName = (ClassFactory("CONFIG").get("preserveComponentBodyTag"))?("com.qcobjects.components."+_componentName+".ComponentBody"):(_componentClassName);
_componentName = (_componentName !== null)?(_componentName):(
(ClassFactory(__componentClassName).hasOwnProperty.call(ClassFactory(__componentClassName),"name")
)?(
ClassFactory(__componentClassName).name
):("")
);
var componentURI;
componentURI = ComponentURI({
"COMPONENTS_BASE_PATH": ClassFactory("CONFIG").get("componentsBasePath"),
"COMPONENT_NAME": _componentName,
"TPLEXTENSION": tplextension,
"TPL_SOURCE": tplsource
});
if (ClassFactory("CONFIG").get("preserveComponentBodyTag")) {
Package("com.qcobjects.components."+_componentName+"",[
Class("ComponentBody", ClassFactory("Component"), {
name: _componentName,
reload: true
})
]);
}
var __classDefinition = ClassFactory(__componentClassName);
var __shadowed = (__shadowed_not_set) ? (__classDefinition.shadowed || ClassFactory("Component").shadowed) : (shadowed);
var __definition = {
name: _componentName,
data: data,
cached: (__cached_not_set) ? (ClassFactory("Component").cached) : (cached),
shadowed: __shadowed,
tplextension: tplextension,
body: (ClassFactory("CONFIG").get("preserveComponentBodyTag")) ? (_DOMCreateElement("componentBody")):(components[_c]),
templateURI: componentURI,
tplsource: tplsource,
subcomponents: []
};
if (typeof _componentName === "undefined" || _componentName === "" || _componentName === null){
/* this allows to use the original property defined
in the component definition if it is not present in the tag */
delete __definition.name;
}
if (componentURI === ""){
/* this allows to use the original property defined
in the component definition if it is not present in the tag */
delete __definition.templateURI;
}
var newComponent = New(__classDefinition, __definition);
if (ClassFactory("CONFIG").get("preserveComponentBodyTag")) {
components[_c].append(newComponent);
}
newComponent.done = componentDone;
componentsBuiltWith.push(newComponent);
}
return componentsBuiltWith;
};
var components = d.subelements(tagFilter);
return _buildComponent(components);
};
HTMLDocument.prototype.buildComponents = Element.prototype.buildComponents;
HTMLElement.prototype.buildComponents = Element.prototype.buildComponents;
} else {
// not yet implemented.
}
if (!isBrowser) {
Class("BackendMicroservice", Object, {
domain: domain,
basePath: basePath,
body: null,
stream: null,
request: null,
cors: function (){
if (this.route.cors){
let {allow_origins,allow_credentials,allow_methods,allow_headers} = this.route.cors;
var microservice = this;
if (typeof microservice.headers !== "object"){
microservice.headers = {};
}
if (typeof allow_origins !== "undefined"){
// an example of allow_origins is ['https://example.com','http://www.example.com']
if (allow_origins === "*" || (typeof microservice.request.headers.origin === "undefined") || [...allow_origins].indexOf(microservice.request.headers.origin)!== -1){
// for compatibility with all browsers allways return a wildcard when the origin is allowed
microservice.headers["Access-Control-Allow-Origin"] = "*";
} else {
logger.debug("Origin is not allowed: " + microservice.request.headers.origin);
logger.debug("Forcing to finish the response...");
this.body = {};
try {
this.done();
} catch (e){}
}
} else {
microservice.headers["Access-Control-Allow-Origin"] = "*";
}
if (typeof allow_credentials !== "undefined"){
microservice.headers["Access-Control-Allow-Credentials"] = allow_credentials.toString();
} else {
microservice.headers["Access-Control-Allow-Credentials"] = "true";
}
if (typeof allow_methods !== "undefined"){
microservice.headers["Access-Control-Allow-Methods"] = [...allow_methods].join(",");
} else {
microservice.headers["Access-Control-Allow-Methods"] = "GET, OPTIONS, POST";
}
if (typeof allow_headers !== "undefined"){
microservice.headers["Access-Control-Allow-Headers"] = [...allow_headers].join(",");
} else {
microservice.headers["Access-Control-Allow-Headers"] = "*";
}
}
},
_new_: function(o) {
logger.debug("Executing BackendMicroservice ");
let microservice = this;
microservice.body = null;
let request = microservice.request;
this.cors();
let stream = o.stream;
microservice.stream = stream;
stream.on("data", (data) => {
// data from POST, GET
var requestMethod = request.method.toLowerCase();
var supportedMethods = {
"post": microservice.post,
};
if (supportedMethods.hasOwnProperty.call(supportedMethods,requestMethod)) {
supportedMethods[requestMethod].call(microservice, data);
}
});
// data from POST, GET
var requestMethod = request.method.toLowerCase();
var supportedMethods = {
"get": microservice.get,
"head": microservice.head,
"put": microservice.put,
"delete": microservice.delete,
"connect": microservice.connect,
"options": microservice.options,
"trace": microservice.trace,
"patch": microservice.patch
};
if (supportedMethods.hasOwnProperty.call(supportedMethods,requestMethod)) {
supportedMethods[requestMethod].call(microservice);
}
},
head: function(formData) {
this.done();
},
get: function(formData){
this.done();
},
post: function(formData) {
this.done();
},
put: function(formData) {
this.done();
},
delete: function(formData) {
this.done();
},
connect: function(formData) {
this.done();
},
options: function(formData) {
this.done();
},
trace: function(formData) {
this.done();
},
patch: function(formData) {
this.done();
},
finishWithBody: function(stream) {
try {
stream.write(_DataStringify(this.body));
stream.end();
} catch (e) {
logger.debug("Something wrong writing the response for microservice" + e.toString());
}
},
done: function() {
var microservice = this;
var stream = microservice.stream;
stream.respond(microservice.headers);
if (microservice.body !== null) {
microservice.finishWithBody.call(microservice, stream);
}
}
});
}
Class("SourceJS", Object, {
domain: domain,
basePath: basePath,
body: _DOMCreateElement("script"),
url: "",
data: {},
async: false,
external: false,
set: function(name, value) {
this[name] = value;
},
get: function(name) {
return this[name];
},
status: false,
done: function() {},
fail: function() {},
rebuild: function() {
var context = this;
try {
document.getElementsByTagName("body")[0].appendChild(
(function(s, url, context) {
s.type = "text/javascript";
s.src = url;
s.crossOrigin = (context.hasOwnProperty.call(context,"crossOrigin")) ? (context.crossOrigin) : ("anonymous");
s.async = context.async;
s.onreadystatechange = function() {
if (this.readyState === "complete") {
context.done.call(context);
}
};
s.onload = function(e) {
context.status = true;
context.done.call(context, e);
};
s.onerror = function(e) {
context.status = false;
context.fail.call(context, e);
};
context.body = s;
return s;
}).call(this,
_DOMCreateElement("script"),
(this.external) ? (this.url) : (this.basePath + this.url), context));
} catch (e) {
context.status = false;
context.fail.call(context, e);
}
},
Cast: function(o) {
return _Cast(this, o);
},
"_new_": function(properties) {
this.__new__(properties);
this.rebuild();
}
});
Class("SourceCSS", Object, {
domain: domain,
basePath: basePath,
body: _DOMCreateElement("link"),
url: "",
data: {},
async: false,
external: false,
set: function(name, value) {
this[name] = value;
},
get: function(name) {
return this[name];
},
done: function() {},
rebuild: function() {
var context = this;
if (isBrowser){
window.document.getElementsByTagName("head")[0].appendChild(
(function(s, url, context) {
s.type = "text/css";
s.rel = "stylesheet";
s.href = url;
s.crossOrigin = "anonymous";
s.onreadystatechange = function() {
if (this.readyState === "complete") {
context.done.call(context);
}
};
s.onload = context.done;
context.body = s;
return s;
}).call(this,
_DOMCreateElement("link"),
(this.external) ? (this.url) : (this.basePath + this.url), context));
}
},
Cast: function(o) {
return _Cast(this, o);
},
"_new_": function(properties) {
this.__new__(properties);
this.rebuild();
}
});
Class("ArrayList", Array, []);
Class("ArrayCollection", Object, {
source: New(ClassFactory("ArrayList"), []),
changed: function(prop, value) {
logger.debug("VALUE CHANGED");
logger.debug(prop);
logger.debug(value);
},
push: function(value) {
var self = this;
logger.debug("VALUE ADDED");
logger.debug(value);
self.source.push(value);
},
pop: function(value) {
var self = this;
logger.debug("VALUE POPPED");
logger.debug(value);
self.source.pop(value);
},
_new_: function(source) {
var self = this;
var _index = 0;
self.source = New(ClassFactory("ArrayList"), source);
for (var _k in self.source) {
if (!isNaN(_k)) {
logger.debug("binding " + _k.toString());
(function(_pname) {
Object.defineProperty(self, _pname, {
set(value) {
logger.debug("setting " + _pname + "=" + value);
self.source[_pname] = value;
self.changed(_pname, value);
},
get() {
return self.source[_pname];
}
});
})(_k);
_index++;
}
}
self.source.length = _index;
Object.defineProperty(self, "length", {
get() {
return self.source.length;
}
});
}
});
Class("Effect", {
duration: 1000,
animate: function({
timing,
draw,
duration
}) {
let start = performance.now();
requestAnimationFrame(function animate(time) {
// timeFraction goes from 0 to 1
let timeFraction = (time - start) / duration;
if (timeFraction > 1) timeFraction = 1;
// calculate the current animation state
let progress = timing(timeFraction);
draw(Math.round(progress * 100)); // draw it
if (timeFraction < 1) {
requestAnimationFrame(animate);
} else {
// if this is an object with a done method
if (typeof this !== "undefined" &&
this.hasOwnProperty.call(this,"done") &&
(typeof this.done).toLowerCase() === "function") {
this.done.call(this);
}
}
});
}
});
Class("TransitionEffect",ClassFactory("Effect"),{
duration:385,
defaultParams:{
alphaFrom:0,
alphaTo:1,
angleFrom:180,
angleTo:0,
radiusFrom:0,
radiusTo:30,
scaleFrom:0,
scaleTo:1
},
fitToHeight:false,
fitToWidth:false,
effects: [],
_new_:function (o){
logger.info("DECLARING TransitionEffect ");
this.component.defaultParams = this.defaultParams;
},
apply: function ({alphaFrom,
alphaTo,
angleFrom,
angleTo,
radiusFrom,
radiusTo,
scaleFrom,
scaleTo}){
logger.info("EXECUTING TransitionEffect ");
if (this.fitToHeight){
this.component.body.height = this.component.body.offsetParent.scrollHeight;
}
if (this.fitToWidth){
this.component.body.width = this.component.body.offsetParent.scrollWidth;
}
this.component.body.style.display = "block";
for (var eff in this.effects){
var effectClassName = this.effects[eff];
var effectClassMethod = _super_(effectClassName,"apply");
var args = [this.component.body].concat(Object.values(
{
alphaFrom,
alphaTo,
angleFrom,
angleTo,
radiusFrom,
radiusTo,
scaleFrom,
scaleTo
}
));
effectClassMethod.apply(this,args);
}
}
});
Class("Timer", {
duration: 1000,
alive: true,
thread: function({
timing,
intervalInterceptor,
duration
}) {
var timer = this;
let start = performance.now();
requestAnimationFrame(function thread(time) {
// timeFraction goes from 0 to 1
let elapsed = (time - start);
let timeFraction = elapsed / duration;
if (timeFraction > 1) timeFraction = 1;
// calculate the current progress state
let progress = timing(timeFraction, elapsed);
intervalInterceptor(Math.round(progress * 100)); // draw it
if ((timeFraction < 1 || duration === -1) && timer.alive) {
requestAnimationFrame(thread);
}
});
}
});
Class("Toggle", ClassFactory("InheritClass"), {
_toggle: false,
_inverse: true,
_positive: null,
_negative: null,
_dispatched: null,
_args: {},
changeToggle: function() {
this._toggle = (this._toggle) ? (false) : (true);
},
_new_: function({
positive,
negative,
args
}) {
this._positive = positive;
this._negative = negative;
this._args = args;
},
fire: function() {
var toggle = this;
var _promise = new Promise(function(resolve, reject) {
if (typeof toggle._positive === "function" && typeof toggle._negative === "function") {
if (toggle._inverse) {
toggle._dispatched = (toggle._toggle) ? (toggle._negative.bind(toggle)) : (toggle._positive.bind(toggle));
} else {
toggle._dispatched = (toggle._toggle) ? (toggle._positive.bind(toggle)) : (toggle._negative.bind(toggle));
}
toggle._dispatched.call(toggle, toggle._args);
resolve.call(_promise, toggle);
} else {
logger.debug("Toggle functions are not declared");
reject.call(_promise, toggle);
}
}).then(function(toggle) {
toggle.changeToggle();
}).catch(function(e) {
logger.debug(e.toString());
});
return _promise;
}
});
/**
* Load every component tag declared in the body
**/
Ready(function() {
if (!ClassFactory("CONFIG").get("useSDK")) {
global.__start__();
}
});
/*
Public variables and functions
*/
Export(Export); /* exports the same Export function once */
Export(Import);
Export(Package);
Export(Class);
Export(New);
Export(Tag);
Export(Ready);
Export(ready);
Export(isBrowser);
Export(_methods_);
if (!isBrowser) {
if (typeof global !== "undefined" && global.hasOwnProperty.call(global,"_fireAsyncLoad")) {
global._fireAsyncLoad.call(this);
}
if (typeof global !== "undefined" && global.hasOwnProperty.call(global,"onload")) {
global.onload.call(this);
}
}
if (isBrowser) {
asyncLoad(function() {
Ready(function() {
window.onpopstate = function(event) {
event.stopImmediatePropagation();
event.stopPropagation();
ClassFactory("Component").route();
};
/*
* scroll management custom events
* usage: document.body.addEventListener('percentY90',function(e){console.log(e.detail.percentY)});
* possible events: scrollpercent, defaultscroll, percentY0, percentY25, percentY50, percentY75, percentY90
*/
Tag("*").map(function(element) {
element.addEventListener("scroll", function(event) {
event.preventDefault();
var percentY = Math.round(event.target.scrollTop * 100 / event.target.scrollHeight);
var percentX = Math.round(event.target.scrollLeft * 100 / event.target.scrollWidth);
var scrollPercentEventEvent = new CustomEvent("scrollpercent", {
detail: {
percentX: percentX,
percentY: percentY
}
});
event.target.dispatchEvent(scrollPercentEventEvent);
var secondaryEventName = "defaultscroll";
switch (true) {
case (percentY === 0):
secondaryEventName = "percentY0";
break;
case (percentY === 25):
secondaryEventName = "percentY25";
break;
case (percentY === 50):
secondaryEventName = "percentY50";
break;
case (percentY === 75):
secondaryEventName = "percentY75";
break;
case (percentY === 90):
secondaryEventName = "percentY90";
break;
default:
break;
}
var secondaryCustomEvent = new CustomEvent(secondaryEventName, {
detail: {
percentX: percentX,
percentY: percentY
}
});
event.target.dispatchEvent(secondaryCustomEvent);
});
return null;
});
});
}, null);
}
}).call(null,(typeof module === "object" && typeof module.exports === "object")?(module.exports = global):((typeof global === "object")?(global):(
(typeof window === "object")?(window):({})
)));
| cdnjs/cdnjs | ajax/libs/qcobjects/2.1.425/QCObjects.js | JavaScript | mit | 115,663 |
import { BLUR, CHANGE, FOCUS, INITIALIZE, RESET, START_ASYNC_VALIDATION, START_SUBMIT, STOP_ASYNC_VALIDATION,
STOP_SUBMIT, TOUCH, UNTOUCH } from './actionTypes';
import mapValues from './mapValues';
export const initialState = {
_asyncValidating: false,
_submitting: false,
_active: undefined
};
const getValues = (state) =>
Object.keys(state).reduce((accumulator, name) =>
name[0] === '_' ? accumulator : {
...accumulator,
[name]: state[name].value
}, {});
const reducer = (state = initialState, action = {}) => {
switch (action.type) {
case BLUR:
return {
...state,
[action.field]: {
...state[action.field],
value: action.value,
touched: !!(action.touch || (state[action.field] || {}).touched)
},
_active: undefined
};
case CHANGE:
return {
...state,
[action.field]: {
...state[action.field],
value: action.value,
touched: !!(action.touch || (state[action.field] || {}).touched),
asyncError: null,
submitError: null
}
};
case FOCUS:
return {
...state,
[action.field]: {
...state[action.field],
visited: true
},
_active: action.field
};
case INITIALIZE:
return {
...mapValues(action.data, (value) => ({
initial: value,
value: value
})),
_asyncValidating: false,
_submitting: false,
_active: undefined
};
case RESET:
return {
...mapValues(state, (field, name) => {
return name[0] === '_' ? field : {
initial: field.initial,
value: field.initial
};
}),
_active: undefined,
_asyncValidating: false,
_submitting: false
};
case START_ASYNC_VALIDATION:
return {
...state,
_asyncValidating: true
};
case START_SUBMIT:
return {
...state,
_submitting: true
};
case STOP_ASYNC_VALIDATION:
return {
...state,
...mapValues(action.errors, (error, key) => ({
...state[key],
asyncError: error
})),
_asyncValidating: false
};
case STOP_SUBMIT:
return {
...state,
...(action.errors ? mapValues(action.errors, (error, key) => ({
...state[key],
submitError: error
})) : {}),
_submitting: false
};
case TOUCH:
return {
...state,
...action.fields.reduce((accumulator, field) => ({
...accumulator,
[field]: {
...state[field],
touched: true
}
}), {})
};
case UNTOUCH:
return {
...state,
...action.fields.reduce((accumulator, field) => ({
...accumulator,
[field]: {
...state[field],
touched: false
}
}), {})
};
default:
return state;
}
};
function formReducer(state = {}, action = {}) {
const {form, key, ...rest} = action;
if (!form) {
return state;
}
if (key) {
return {
...state,
[form]: {
...state[form],
[key]: reducer((state[form] || {})[key], rest)
}
};
}
return {
...state,
[form]: reducer(state[form], rest)
};
}
/**
* Adds additional functionality to the reducer
*/
function decorate(target) {
target.plugin = function plugin(reducers) {
return decorate((state = {}, action = {}) => {
const result = this(state, action);
return {
...result,
...mapValues(reducers, (red, key) => red(result[key] || initialState, action))
};
});
};
target.normalize = function normalize(normalizers) {
return decorate((state = {}, action = {}) => {
const result = this(state, action);
return {
...result,
...mapValues(normalizers, (formNormalizers, form) => ({
...result[form],
...mapValues(formNormalizers, (fieldNormalizer, field) => ({
...result[form][field],
value: fieldNormalizer(
result[form][field] ? result[form][field].value : undefined, // value
state[form] && state[form][field] ? state[form][field].value : undefined, // previous value
getValues(result[form])) // all field values
}))
}))
};
});
};
return target;
}
export default decorate(formReducer);
| asaf/redux-form | src/reducer.js | JavaScript | mit | 4,623 |