code
stringlengths 2
1.05M
|
---|
/**
* Manages uploading and streaming of video files.
*
* @module video
*/
'use strict';
var fs, uploadPath, supportedTypes;
fs = require('fs');
uploadPath = __dirname + '/../../public/games';
console.log("uploadPath:", uploadPath);
supportedTypes = [
'video/mp4',
'video/webm',
'video/ogg'
];
module.exports = {
list: list,
request: request,
upload: upload,
uploadPath: uploadPath
};
_checkUploadDir();
function _checkUploadDir(cb) {
cb = cb || function () {};
fs.stat(uploadPath, function (err, stats) {
if (err && err.errno == -2) {
// No such file or directory
fs.mkdir(uploadPath, cb);
} else if (
(err && err.errno === 34) ||
!stats.isDirectory()
) {
// if there's no error, it means it's not a directory - remove it
if (!err) {
fs.unlinkSync(uploadPath);
}
// create directory
fs.mkdir(uploadPath, cb);
return;
}
cb();
});
}
/**
*/
function list(stream, meta) {
_checkUploadDir(function () {
fs.readdir(uploadPath, function (err, files) {
stream.write({
files: files
});
});
});
}
/**
*/
function request(client, meta) {
var file = fs.createReadStream(uploadPath + '/' + meta.name);
client.send(file);
}
/**
*/
function upload(stream, meta) {
if (!~supportedTypes.indexOf(meta.type)) {
stream.write({
err: 'Unsupported type: ' + meta.type
});
stream.end();
return;
}
var file = fs.createWriteStream(uploadPath + '/' + meta.name);
stream.pipe(file);
stream.on('data', function (data) {
stream.write({
rx: data.length / meta.size
});
});
stream.on('end', function () {
stream.write({
end: true
});
});
}
|
// 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 vendor/assets/javascripts of plugins, if any, 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
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery-ui-1.10.4.custom.min
//= require term
//= require showterm
|
/* global describe, xit, jsPDF, expect */
/**
* Standard spec tests
*/
describe("Module: Context2D: HTML comparison tests", () => {
xit("default values like a real 2d-context", () => {
var doc = new jsPDF();
var ctx = doc.canvas.getContext("2d");
expect(ctx.fillStyle).toEqual("#000000");
expect(ctx.filter).toEqual("none");
expect(ctx.font).toEqual("10px sans-serif");
expect(ctx.globalAlpha).toEqual(1);
expect(ctx.globalCompositeOperation).toEqual("source-over");
expect(ctx.imageSmoothingEnabled).toEqual(true);
expect(ctx.imageSmoothingQuality).toEqual("low");
expect(ctx.lineCap).toEqual("butt");
expect(ctx.lineDashOffset).toEqual(0);
expect(ctx.lineJoin).toEqual("miter");
expect(ctx.lineWidth).toEqual(1);
expect(ctx.miterLimit).toEqual(10);
expect(ctx.shadowBlur).toEqual(0);
expect(ctx.shadowColor).toEqual("rgba(0, 0, 0, 0)");
expect(ctx.shadowOffsetX).toEqual(0);
expect(ctx.shadowOffsetY).toEqual(0);
expect(ctx.strokeStyle).toEqual("#000000");
expect(ctx.textAlign).toEqual("start");
expect(ctx.textBaseline).toEqual("alphabetic");
});
});
|
/*
// Scheduled Backup Launcher
// Copyright (c) 2011-2015, Adam Rehn
//
// 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.
*/
$ = require('jquery');
function FormBuilder() {}
FormBuilder.build = function(tableElem, fields, defaultValues, options)
{
//Store the supplied options (if any)
this.options = ((options !== undefined) ? options : {});
//Build the table header
FormBuilder.buildHeader(tableElem, fields, this.options.remButton, this.options.reorder);
//Generate the row generation function
var rowGenFunc = FormBuilder.buildRowGenFunc(tableElem, fields, this.options.change, this.options.remButton, this.options.reorder);
//Build the table body
var tbody = $(document.createElement('tbody')).appendTo(tableElem);
defaultValues.forEach(function(value) {
tbody.append( rowGenFunc(value) );
});
//Unless requested otherwise, generate the 'add row' button
if (this.options.addButton === undefined || this.options.addButton != false)
{
var addButton = $(document.createElement('button')).text('+');
tableElem.after(addButton);
addButton.click(function()
{
tbody.append( rowGenFunc({}) );
FormBuilder.tableHideHelper(tableElem);
//If a row change handler was supplied, invoke it
if (this.options.change !== undefined) {
this.options.change();
}
});
}
//Hide the table if it is currently empty
FormBuilder.tableHideHelper(tableElem);
//Return a handle that can be used to retrieve the form values from the table
return {
'getValues': function() {
return FormBuilder.getValues(tableElem, fields);
}
};
}
//Helper function for hiding tables when they contain no rows
FormBuilder.tableHideHelper = function(tableElem)
{
//Determine if the table contains any rows
if ($('tbody tr', tableElem).length > 0) {
tableElem.show();
}
else {
tableElem.hide();
}
}
//Builds the table header
FormBuilder.buildHeader = function(tableElem, fields, remButton, reorder)
{
var thead = $(document.createElement('thead'));
var tr = $(document.createElement('tr'));
Object.keys(fields).forEach(function(field)
{
var th = $(document.createElement('th')).text(fields[field].label);
tr.append(th);
});
//Create an empty header cell for the row deletion button, if requested
if (remButton === undefined || remButton != false) {
tr.append($(document.createElement('th')));
}
//Create an empty header cell for the reordering buttons, if requested
if (reorder === true) {
tr.append($(document.createElement('th')));
}
thead.append(tr);
tableElem.append(thead);
}
//Builds the row generation function
FormBuilder.buildRowGenFunc = function(tableElem, fields, rowChangeHandler, remButton, reorder)
{
return function(values)
{
var tr = $(document.createElement('tr'));
//Build the table cell for each field
Object.keys(fields).forEach(function(fieldName)
{
//Create the table cell, marking it with the field name
var td = $(document.createElement('td')).attr('fieldname', fieldName).appendTo(tr);
//Populate the table cell based on the field type
var field = fields[fieldName];
if (field.type == 'static')
{
//Populate the table cell with the supplied static text
td.text(values[fieldName]);
}
else if (field.type == 'text' || field.type == 'time')
{
//Create the input field
var input = $(document.createElement('input')).attr('type', field.type);
td.append(input);
//If a change handler was supplied, register it and call it
if (field.change !== undefined)
{
input.change(field.change);
input.trigger('change');
}
//If a default value was supplied, apply it
var value = values[fieldName];
if (value !== undefined) {
input.val(value);
}
}
else if (field.type == 'select')
{
//Create the dropdown
var select = $(document.createElement('select')).appendTo(td);
var seenOptions = [];
field.options.forEach(function(option)
{
if (option.length > 0 && seenOptions.indexOf(option) == -1)
{
//Create the current option element
var optionElem = $(document.createElement('option')).appendTo(select);
optionElem.attr('value', option);
optionElem.text(option);
//Keep track of the encountered options, so we can avoid duplicates
seenOptions.push(option);
//If a default value was supplied, apply it
var value = values[fieldName];
if (value !== undefined && value == option) {
optionElem.attr('selected', 'selected');
}
}
});
//If a change handler was supplied, register it and call it
if (field.change !== undefined)
{
select.change(field.change);
select.trigger('change');
}
}
else if (field.type == 'checkbox')
{
//Create the checkbox
var input = $(document.createElement('input')).attr('type', 'checkbox')
td.append(input);
//If a change handler was supplied, register it and call it
if (field.change !== undefined)
{
input.change(field.change);
input.trigger('change');
}
//If a default value was supplied, apply it
var value = values[fieldName];
if (value !== undefined && value == true) {
input.attr('checked', 'checked');
}
}
else if (field.type == 'button')
{
//Create the custom button
var button = $(document.createElement('button')).appendTo(td);
button.text(field.buttonLabel);
button.click(function() {
field.buttonHandler( button );
});
//If a default value was supplied, apply it
var value = values[fieldName];
value = ((value !== undefined) ? value : '');
button.attr('value', value);
}
});
//Unless requested otherwise, build the table cell for the row deletion button
if (remButton === undefined || remButton != false)
{
var delButton = $(document.createElement('button')).text('-');
tr.append($(document.createElement('td')).append(delButton));
delButton.click(function()
{
tr.remove();
FormBuilder.tableHideHelper(tableElem);
//If a row change handler was supplied, invoke it
if (rowChangeHandler !== undefined) {
rowChangeHandler();
}
});
}
//If requested, build the table cell for the up and down buttons
if (reorder === true)
{
var upButton = $(document.createElement('button')).text('↑').attr('class', 'reorder');
var downButton = $(document.createElement('button')).text('↓').attr('class', 'reorder');
tr.append($(document.createElement('td')).append(upButton).append(downButton));
upButton.click(function()
{
//Swap the current row with the previous one
var sibling = tr.prev();
if (sibling.length > 0) {
sibling.before(tr);
}
//If a row change handler was supplied, invoke it
if (rowChangeHandler !== undefined) {
rowChangeHandler();
}
});
downButton.click(function()
{
//Swap the current row with the next one
var sibling = tr.next();
if (sibling.length > 0) {
sibling.after(tr);
}
//If a row change handler was supplied, invoke it
if (rowChangeHandler !== undefined) {
rowChangeHandler();
}
});
}
return tr;
};
}
FormBuilder.getValues = function(tableElem, fields)
{
var that = this;
var values = [];
var fieldNames = Object.keys(fields);
//Determine the number of extra columns, based on which options are active
var extraRows = 0;
if (this.options.remButton === undefined || this.options.remButton != false) { extraRows++; }
if (this.options.reorder === true) { extraRows++; }
//Iterate over each table row
tableElem.find('> tbody > tr').each(function(index, row)
{
//Verify that the number of cells matches our fields (plus one for the remove button, if we're using it)
var cells = $(row).find('> td');
if (cells.length == fieldNames.length + extraRows)
{
var rowVals = {};
//Iterate over the table cells
for (var i = 0; i < fieldNames.length; ++i)
{
//Retrieve the value from the input element
var elem = $(cells.get(i)).find('input, select, radio, textarea, button').first();
var value = elem.val();
if (elem.attr('type') == 'checkbox') {
value = elem.is(':checked');
}
rowVals[ fieldNames[i] ] = value;
}
values.push(rowVals);
}
});
return values;
}
|
/*!
angular-xeditable - 0.1.7
Edit-in-place for angular.js
Build date: 2013-10-26
*/
/*
angular-xeditable module
*/
angular.module('xeditable', [])
.value('editableOptions', {
theme: 'default', //bs2, bs3,
buttons: 'right',
blur: 'cancel'
});
/*
Angular-ui bootstrap datepicker
http://angular-ui.github.io/bootstrap/#/datepicker
*/
angular.module('xeditable').directive('editableBsdate', ['editableDirectiveFactory',
function(editableDirectiveFactory) {
return editableDirectiveFactory({
directiveName: 'editableBsdate',
inputTpl: '<input type="text">'
});
}]);
/*
Angular-ui bootstrap editable timepicker
http://angular-ui.github.io/bootstrap/#/timepicker
*/
angular.module('xeditable').directive('editableBstime', ['editableDirectiveFactory',
function(editableDirectiveFactory) {
return editableDirectiveFactory({
directiveName: 'editableBstime',
inputTpl: '<timepicker></timepicker>',
render: function() {
this.parent.render.call(this);
// timepicker can't update model when ng-model set directly to it
// see: https://github.com/angular-ui/bootstrap/issues/1141
// so we wrap it into DIV
var div = angular.element('<div class="well well-small" style="display:inline-block;"></div>');
// move ng-model to wrapping div
div.attr('ng-model', this.inputEl.attr('ng-model'));
this.inputEl.removeAttr('ng-model');
// move ng-change to wrapping div
if(this.attrs.eNgChange) {
div.attr('ng-change', this.inputEl.attr('ng-change'));
this.inputEl.removeAttr('ng-change');
}
// wrap
this.inputEl.wrap(div);
}
});
}]);
//checkbox
angular.module('xeditable').directive('editableCheckbox', ['editableDirectiveFactory',
function(editableDirectiveFactory) {
return editableDirectiveFactory({
directiveName: 'editableCheckbox',
inputTpl: '<input type="checkbox">',
render: function() {
this.parent.render.call(this);
if(this.attrs.eTitle) {
this.inputEl.wrap('<label></label>');
this.inputEl.after(angular.element('<span></span>').text(' '+this.attrs.eTitle));
}
},
autosubmit: function() {
var self = this;
self.inputEl.bind('change', function() {
setTimeout(function() {
self.scope.$apply(function() {
self.scope.$form.$submit();
});
}, 500);
});
}
});
}]);
/*
Input types: text|email|tel|number|url|search|color|date|datetime|time|month|week
*/
(function() {
var types = 'text|email|tel|number|url|search|color|date|datetime|time|month|week'.split('|');
//todo: datalist
// generate directives
angular.forEach(types, function(type) {
var directiveName = 'editable'+type.charAt(0).toUpperCase() + type.slice(1);
angular.module('xeditable').directive(directiveName, ['editableDirectiveFactory',
function(editableDirectiveFactory) {
return editableDirectiveFactory({
directiveName: directiveName,
inputTpl: '<input type="'+type+'">'
});
}]);
});
//`range` is bit specific
angular.module('xeditable').directive('editableRange', ['editableDirectiveFactory',
function(editableDirectiveFactory) {
return editableDirectiveFactory({
directiveName: 'editableRange',
inputTpl: '<input type="range" id="range" name="range">',
render: function() {
this.parent.render.call(this);
this.inputEl.after('<output>{{$data}}</output>');
}
});
}]);
}());
//select
angular.module('xeditable').directive('editableSelect', ['editableDirectiveFactory',
function(editableDirectiveFactory) {
return editableDirectiveFactory({
directiveName: 'editableSelect',
inputTpl: '<select></select>',
autosubmit: function() {
var self = this;
self.inputEl.bind('change', function() {
self.scope.$apply(function() {
self.scope.$form.$submit();
});
});
}
});
}]);
//textarea
angular.module('xeditable').directive('editableTextarea', ['editableDirectiveFactory',
function(editableDirectiveFactory) {
return editableDirectiveFactory({
directiveName: 'editableTextarea',
inputTpl: '<textarea></textarea>',
addListeners: function() {
var self = this;
self.parent.addListeners.call(self);
// submit textarea by ctrl+enter even with buttons
if (self.single && self.buttons !== 'no') {
self.autosubmit();
}
},
autosubmit: function() {
var self = this;
self.inputEl.bind('keydown', function(e) {
if ((e.ctrlKey || e.metaKey) && (e.keyCode === 13)) {
self.scope.$apply(function() {
self.scope.$form.$submit();
});
}
});
}
});
}]);
/**
* EditableController class.
* Attached to element with `editable-xxx` directive.
*
* @namespace editable-element
*/
/*
TODO: this file should be refactored to work more clear without closures!
*/
angular.module('xeditable').factory('editableController', ['$q', '$document', 'editableUtils', '$rootScope',
function($q, $document, utils, $rootScope) {
// array of opened editable controls
var shown = [];
// bind click to body: cancel|submit editables
$document.bind('click', function(e) {
// ignore right/middle button click
if (e.which !== 1) {
return;
}
var toCancel = [];
var toSubmit = [];
for (var i=0; i<shown.length; i++) {
// exclude self
if (shown[i].clicked) {
shown[i].clicked = false;
continue;
}
if (shown[i].blur === 'cancel') {
toCancel.push(shown[i]);
}
if (shown[i].blur === 'submit') {
toSubmit.push(shown[i]);
}
}
if (toCancel.length || toSubmit.length) {
$rootScope.$apply(function() {
angular.forEach(toCancel, function(v){ v.scope.$form.$hide(); });
angular.forEach(toSubmit, function(v){ v.scope.$form.$submit(); });
});
}
});
//EditableController function
EditableController.$inject = ['$scope', '$attrs', '$element', '$parse', 'editableThemes', 'editableOptions', '$rootScope', '$compile', '$q'];
function EditableController($scope, $attrs, $element, $parse, editableThemes, editableOptions, $rootScope, $compile, $q) {
var valueGetter;
//if control is disabled - it does not participate in waiting process
var inWaiting;
var self = this;
self.scope = $scope;
self.elem = $element;
self.attrs = $attrs;
self.inputEl = null;
self.editorEl = null;
self.single = true;
self.error = '';
self.theme = editableThemes[editableOptions.theme] || editableThemes['default'];
self.parent = {};
self.clicked = false; //used to check in document click handler if control was clicked or not
//to be overwritten by directive
self.inputTpl = '';
self.directiveName = '';
//runtime (defaults)
self.single = null;
/**
* Attributes defined with `e-*` prefix automatically transfered from original element to
* control.
* For example, if you set `<span editable-text="user.name" e-style="width: 100px"`>
* then input will appear as `<input style="width: 100px">`.
* See [demo](#text-customize).
*
* @var {any|attribute} e-*
* @memberOf editable-element
*/
/**
* Whether to show ok/cancel buttons. Values: `right|no`.
* If set to `no` control automatically submitted when value changed.
* If control is part of form buttons will never be shown.
*
* @var {string|attribute} buttons
* @memberOf editable-element
*/
self.buttons = 'right';
/**
* Action when control losses focus. Values: `cancel|submit|ignore`.
* If control is part of form `blur` automatically set to `ignore`.
*
* @var {string|attribute} blur
* @memberOf editable-element
*/
self.blur = 'ignore'; // can be 'cancel|submit|ignore'
//init
self.init = function(single) {
self.single = single;
self.name = $attrs.eName || $attrs[self.directiveName];
/*
if(!$attrs[directiveName] && !$attrs.eNgModel && ($attrs.eValue === undefined)) {
throw 'You should provide value for `'+directiveName+'` or `e-value` in editable element!';
}
*/
if($attrs[self.directiveName]) {
valueGetter = $parse($attrs[self.directiveName]);
} else {
throw 'You should provide value for `'+self.directiveName+'` in editable element!';
}
// settings for single and non-single
if (!self.single) {
// hide buttons for non-single
self.buttons = 'no';
self.blur = 'ignore';
} else {
self.buttons = self.attrs.buttons || editableOptions.buttons;
self.blur = self.attrs.blur || (self.buttons === 'no' ? 'cancel' : editableOptions.blur);
}
//moved to show()
//self.render();
//if name defined --> watch changes and update $data in form
if($attrs.eName) {
self.scope.$watch('$data', function(newVal){
self.scope.$form.$data[$attrs.eName] = newVal;
});
}
/**
* Called when control is shown.
* See [demo](#select-remote).
*
* @var {method|attribute} onshow
* @memberOf editable-element
*/
if($attrs.onshow) {
self.onshow = function() {
return self.catchError($parse($attrs.onshow)($scope));
};
}
/**
* Called when control is hidden after both save or cancel.
*
* @var {method|attribute} onhide
* @memberOf editable-element
*/
if($attrs.onhide) {
self.onhide = function() {
return $parse($attrs.onhide)($scope);
};
}
/**
* Called when control is cancelled.
*
* @var {method|attribute} oncancel
* @memberOf editable-element
*/
if($attrs.oncancel) {
self.oncancel = function() {
return $parse($attrs.oncancel)($scope);
};
}
/**
* Called during submit before value is saved to model.
* See [demo](#onbeforesave).
*
* @var {method|attribute} onbeforesave
* @memberOf editable-element
*/
if ($attrs.onbeforesave) {
self.onbeforesave = function() {
return self.catchError($parse($attrs.onbeforesave)($scope));
};
}
/**
* Called during submit after value is saved to model.
* See [demo](#onaftersave).
*
* @var {method|attribute} onaftersave
* @memberOf editable-element
*/
if ($attrs.onaftersave) {
self.onaftersave = function() {
return self.catchError($parse($attrs.onaftersave)($scope));
};
}
// watch change of model to update editable element
// now only add/remove `editable-empty` class.
// Initially this method called with newVal = undefined, oldVal = undefined
// so no need initially call handleEmpty() explicitly
$scope.$parent.$watch($attrs[self.directiveName], function(newVal, oldVal) {
self.handleEmpty();
});
};
self.render = function() {
var theme = self.theme;
//build input
self.inputEl = angular.element(self.inputTpl);
//build controls
self.controlsEl = angular.element(theme.controlsTpl);
self.controlsEl.append(self.inputEl);
//build buttons
if(self.buttons !== 'no') {
self.buttonsEl = angular.element(theme.buttonsTpl);
self.submitEl = angular.element(theme.submitTpl);
self.cancelEl = angular.element(theme.cancelTpl);
self.buttonsEl.append(self.submitEl).append(self.cancelEl);
self.controlsEl.append(self.buttonsEl);
self.inputEl.addClass('editable-has-buttons');
}
//build error
self.errorEl = angular.element(theme.errorTpl);
self.controlsEl.append(self.errorEl);
//build editor
self.editorEl = angular.element(self.single ? theme.formTpl : theme.noformTpl);
self.editorEl.append(self.controlsEl);
// transfer `e-*|data-e-*|x-e-*` attributes
for(var k in $attrs.$attr) {
if(k.length <= 1) {
continue;
}
var transferAttr = false;
var nextLetter = k.substring(1, 2);
// if starts with `e` + uppercase letter
if(k.substring(0, 1) === 'e' && nextLetter === nextLetter.toUpperCase()) {
transferAttr = k.substring(1); // cut `e`
} else {
continue;
}
// exclude `form` and `ng-submit`,
if(transferAttr === 'Form' || transferAttr === 'NgSubmit') {
continue;
}
// convert back to lowercase style
transferAttr = transferAttr.substring(0, 1).toLowerCase() + utils.camelToDash(transferAttr.substring(1));
// workaround for attributes without value (e.g. `multiple = "multiple"`)
var attrValue = ($attrs[k] === '') ? transferAttr : $attrs[k];
// set attributes to input
self.inputEl.attr(transferAttr, attrValue);
}
self.inputEl.addClass('editable-input');
self.inputEl.attr('ng-model', '$data');
// add directiveName class to editor, e.g. `editable-text`
self.editorEl.addClass(utils.camelToDash(self.directiveName));
if(self.single) {
self.editorEl.attr('editable-form', '$form');
}
//apply `postrender` method of theme
if(angular.isFunction(theme.postrender)) {
theme.postrender.call(self);
}
};
//show
self.show = function() {
// set value. copy not needed.
// self.scope.$data = angular.copy(valueGetter($scope.$parent));
self.scope.$data = valueGetter($scope.$parent);
/*
Originally render() was inside init() method, but some directives polluting editorEl,
so it is broken on second openning.
Cloning is not a solution as jqLite can not clone with event handler's.
*/
self.render();
// insert into DOM
$element.after(self.editorEl);
// compile (needed to attach ng-* events from markup)
$compile(self.editorEl)($scope);
// attach listeners (`escape`, autosubmit, etc)
self.addListeners();
// hide element
$element.addClass('editable-hide');
// add to internal list
// setTimeout needed to prevent closing right after opening (e.g. when trigger by button)
setTimeout(function() {
if(utils.indexOf(shown, self) === -1) {
shown.push(self);
}
}, 0);
// onshow
return self.onshow();
};
//hide
self.hide = function() {
//console.log('editable hide', self.name);
self.editorEl.remove();
$element.removeClass('editable-hide');
// remove from internal list
utils.arrayRemove(shown, self);
// onhide
return self.onhide();
// todo: to think is it really needed or not
/*
if($element[0].tagName === 'A') {
$element[0].focus();
}
*/
};
// cancel
self.cancel = function() {
// oncancel
self.oncancel();
// don't call hide() here as it called in form's code
};
/*
Called after show to attach listeners
*/
self.addListeners = function() {
// bind keyup for `escape`
self.inputEl.bind('keyup', function(e) {
if(!self.single) {
return;
}
switch(e.keyCode) {
// hide on `escape` press
case 27:
self.scope.$form.$cancel();
break;
}
});
// autosubmit when `no buttons`
if (self.single && self.buttons === 'no') {
self.autosubmit();
}
// click - mark element as clicked to exclude in document click handler
self.editorEl.bind('click', function(e) {
// ignore right/middle button click
if (e.which !== 1) {
return;
}
self.clicked = true;
});
};
// setWaiting
self.setWaiting = function(value) {
if (value) {
//participate in waiting only if not disabled
inWaiting = !self.inputEl.attr('disabled') &&
!self.inputEl.attr('ng-disabled') &&
!self.inputEl.attr('ng-enabled');
if (inWaiting) {
self.inputEl.attr('disabled', 'disabled');
if(self.buttonsEl) {
self.buttonsEl.find('button').attr('disabled', 'disabled');
}
}
} else {
if (inWaiting) {
self.inputEl.removeAttr('disabled');
if (self.buttonsEl) {
self.buttonsEl.find('button').removeAttr('disabled');
}
}
}
};
self.activate = function() {
setTimeout(function() {
self.inputEl[0].focus();
}, 0);
};
self.setError = function(msg) {
if(!angular.isObject(msg)) {
$scope.$error = msg;
self.error = msg;
}
};
/*
Checks that result is string or promise returned string and shows it as error message
Applied to onshow, onbeforesave, onaftersave
*/
self.catchError = function(result, noPromise) {
if (angular.isObject(result) && noPromise !== true) {
$q.when(result).then(
//success and fail handlers are equal
angular.bind(this, function(r) {
this.catchError(r, true);
}),
angular.bind(this, function(r) {
this.catchError(r, true);
})
);
//check $http error
} else if (noPromise && angular.isObject(result) && result.status &&
(result.status !== 200) && result.data && angular.isString(result.data)) {
this.setError(result.data);
//set result to string: to let form know that there was error
result = result.data;
} else if (angular.isString(result)) {
this.setError(result);
}
return result;
};
self.save = function() {
valueGetter.assign($scope.$parent, angular.copy(self.scope.$data));
// no need to call handleEmpty here as we are watching change of model value
// self.handleEmpty();
};
/*
attach/detach `editable-empty` class to element
*/
self.handleEmpty = function() {
var val = valueGetter($scope.$parent);
var isEmpty = val === null || val === undefined || val === "" || (angular.isArray(val) && val.length === 0);
$element.toggleClass('editable-empty', isEmpty);
};
/*
Called when `buttons = "no"` to submit automatically
*/
self.autosubmit = angular.noop;
self.onshow = angular.noop;
self.onhide = angular.noop;
self.oncancel = angular.noop;
self.onbeforesave = angular.noop;
self.onaftersave = angular.noop;
}
return EditableController;
}]);
/*
editableFactory:
- attaches editableController to element
- used to generate editable directives
Depends on: editableController, editableFormFactory
*/
angular.module('xeditable').factory('editableDirectiveFactory',
['$parse', '$compile', 'editableThemes', '$rootScope', '$document', 'editableController', 'editableFormController',
function($parse, $compile, editableThemes, $rootScope, $document, editableController, editableFormController) {
//directive object
return function(overwrites) {
return {
restrict: 'A',
scope: true,
require: [overwrites.directiveName, '?^form'],
controller: editableController,
link: function(scope, elem, attrs, ctrl) {
//editable controller
var eCtrl = ctrl[0];
//form controller
var eFormCtrl;
var hasForm = false;
//if not inside form, but we have `e-form`:
//check if form exists somewhere in scope. If exists - bind, otherwise create.
if(ctrl[1]) {
eFormCtrl = ctrl[1];
hasForm = true;
} else if(attrs.eForm) {
var getter = $parse(attrs.eForm)(scope);
if(getter) { //getter defined, form above
eFormCtrl = getter;
hasForm = true;
} else { //form below or not exist: check document.forms
for(var i=0; i<$document[0].forms.length;i++){
if($document[0].forms[i].name === attrs.eForm) {
//form is below and not processed yet
eFormCtrl = null;
hasForm = true;
break;
}
}
}
}
/*
if(hasForm && !attrs.eName) {
throw 'You should provide `e-name` for editable element inside form!';
}
*/
//check for `editable-form` attr in form
/*
if(eFormCtrl && ) {
throw 'You should provide `e-name` for editable element inside form!';
}
*/
//store original props to `parent` before merge
angular.forEach(overwrites, function(v, k) {
if(eCtrl[k] !== undefined) {
eCtrl.parent[k] = eCtrl[k];
}
});
//merge overwrites to base editable controller
angular.extend(eCtrl, overwrites);
//init editable ctrl
eCtrl.init(!hasForm);
//publich editable controller as `$editable` to be referenced in html
scope.$editable = eCtrl;
// add `editable` class to element
elem.addClass('editable');
// hasForm
if(hasForm) {
if(eFormCtrl) {
scope.$form = eFormCtrl;
if(!scope.$form.$addEditable) {
throw 'Form with editable elements should have `editable-form` attribute.';
}
scope.$form.$addEditable(eCtrl);
} else {
// future form (below): add editable controller to buffer and add to form later
$rootScope.$$editableBuffer = $rootScope.$$editableBuffer || {};
$rootScope.$$editableBuffer[attrs.eForm] = $rootScope.$$editableBuffer[attrs.eForm] || [];
$rootScope.$$editableBuffer[attrs.eForm].push(eCtrl);
scope.$form = null; //will be re-assigned later
}
// !hasForm
} else {
//create editableform controller
scope.$form = editableFormController();
//add self to editable controller
scope.$form.$addEditable(eCtrl);
//elem.after(self.editorEl);
//console.log('w:', scope.$$watchers.length);
//$compile(eCtrl.editorEl)(scope);
//scope.$form.$addEditable(eCtrl);
//console.log('w:', scope.$$watchers.length);
//eCtrl.editorEl.remove();
//if `e-form` provided, publish local $form in scope
if(attrs.eForm) {
scope.$parent[attrs.eForm] = scope.$form;
}
//bind click - if no external form defined
if(!attrs.eForm) {
elem.addClass('editable-click');
elem.bind('click', function(e) {
e.preventDefault();
e.editable = eCtrl;
scope.$apply(function(){
scope.$form.$show();
});
});
}
}
}
};
};
}]);
/*
Returns editableForm controller
*/
angular.module('xeditable').factory('editableFormController',
['$parse', 'editablePromiseCollection',
function($parse, editablePromiseCollection) {
var base = {
$addEditable: function(editable) {
//console.log('add editable', editable.elem, editable.elem.bind);
this.$editables.push(editable);
//'on' is not supported in angular 1.0.8
editable.elem.bind('$destroy', angular.bind(this, this.$removeEditable, editable));
//bind editable's local $form to self (if not bound yet, below form)
if (!editable.scope.$form) {
editable.scope.$form = this;
}
//if form already shown - call show() of new editable
if (this.$visible) {
editable.catchError(editable.show());
}
},
$removeEditable: function(editable) {
//arrayRemove
for(var i=0; i < this.$editables.length; i++) {
if(this.$editables[i] === editable) {
this.$editables.splice(i, 1);
return;
}
}
},
/**
* Shows form with editable controls.
*
* @method $show()
* @memberOf editable-form
*/
$show: function() {
if (this.$visible) {
return;
}
this.$visible = true;
var pc = editablePromiseCollection();
//own show
pc.when(this.$onshow());
//clear errors
this.$setError(null, '');
//children show
angular.forEach(this.$editables, function(editable) {
pc.when(editable.show());
});
//wait promises and activate
pc.then({
onWait: angular.bind(this, this.$setWaiting),
onTrue: angular.bind(this, this.$activate),
onFalse: angular.bind(this, this.$activate),
onString: angular.bind(this, this.$activate)
});
},
/**
* Sets focus on form field specified by `name`.
*
* @method $activate(name)
* @param {string} name name of field
* @memberOf editable-form
*/
$activate: function(name) {
var i;
if (this.$editables.length) {
//activate by name
if (angular.isString(name)) {
for(i=0; i<this.$editables.length; i++) {
if (this.$editables[i].name === name) {
this.$editables[i].activate();
return;
}
}
}
//try activate error field
for(i=0; i<this.$editables.length; i++) {
if (this.$editables[i].error) {
this.$editables[i].activate();
return;
}
}
//by default activate first field
this.$editables[0].activate();
}
},
/**
* Hides form with editable controls without saving.
*
* @method $hide()
* @memberOf editable-form
*/
$hide: function() {
if (!this.$visible) {
return;
}
this.$visible = false;
// self hide
this.$onhide();
// children's hide
angular.forEach(this.$editables, function(editable) {
editable.hide();
});
},
/**
* Triggers `oncancel` event and calls `$hide()`.
*
* @method $cancel()
* @memberOf editable-form
*/
$cancel: function() {
if (!this.$visible) {
return;
}
// self cancel
this.$oncancel();
// children's cancel
angular.forEach(this.$editables, function(editable) {
editable.cancel();
});
// self hide
this.$hide();
},
$setWaiting: function(value) {
this.$waiting = !!value;
// we can't just set $waiting variable and use it via ng-disabled in children
// because in editable-row form is not accessible
angular.forEach(this.$editables, function(editable) {
editable.setWaiting(!!value);
});
},
/**
* Shows error message for particular field.
*
* @method $setError(name, msg)
* @param {string} name name of field
* @param {string} msg error message
* @memberOf editable-form
*/
$setError: function(name, msg) {
angular.forEach(this.$editables, function(editable) {
if(!name || editable.name === name) {
editable.setError(msg);
}
});
},
$submit: function() {
if (this.$waiting) {
return;
}
//clear errors
this.$setError(null, '');
//children onbeforesave
var pc = editablePromiseCollection();
angular.forEach(this.$editables, function(editable) {
pc.when(editable.onbeforesave());
});
/*
onbeforesave result:
- true/undefined: save data and close form
- false: close form without saving
- string: keep form open and show error
*/
pc.then({
onWait: angular.bind(this, this.$setWaiting),
onTrue: angular.bind(this, checkSelf, true),
onFalse: angular.bind(this, checkSelf, false),
onString: angular.bind(this, this.$activate)
});
//save
function checkSelf(childrenTrue){
var pc = editablePromiseCollection();
pc.when(this.$onbeforesave());
pc.then({
onWait: angular.bind(this, this.$setWaiting),
onTrue: childrenTrue ? angular.bind(this, this.$save) : angular.bind(this, this.$hide),
onFalse: angular.bind(this, this.$hide),
onString: angular.bind(this, this.$activate)
});
}
},
$save: function() {
// write model for each editable
angular.forEach(this.$editables, function(editable) {
editable.save();
});
//call onaftersave of self and children
var pc = editablePromiseCollection();
pc.when(this.$onaftersave());
angular.forEach(this.$editables, function(editable) {
pc.when(editable.onaftersave());
});
/*
onaftersave result:
- true/undefined/false: just close form
- string: keep form open and show error
*/
pc.then({
onWait: angular.bind(this, this.$setWaiting),
onTrue: angular.bind(this, this.$hide),
onFalse: angular.bind(this, this.$hide),
onString: angular.bind(this, this.$activate)
});
},
$onshow: angular.noop,
$oncancel: angular.noop,
$onhide: angular.noop,
$onbeforesave: angular.noop,
$onaftersave: angular.noop
};
return function() {
return angular.extend({
$editables: [],
/**
* Form visibility flag.
*
* @var {bool} $visible
* @memberOf editable-form
*/
$visible: false,
/**
* Form waiting flag. It becomes `true` when form is loading or saving data.
*
* @var {bool} $waiting
* @memberOf editable-form
*/
$waiting: false,
$data: {}
}, base);
};
}]);
/**
* EditableForm directive. Should be defined in <form> containing editable controls.
* It add some usefull methods to form variable exposed to scope by `name="myform"` attribute.
*
* @namespace editable-form
*/
angular.module('xeditable').directive('editableForm',
['$rootScope', '$parse', 'editableFormController',
function($rootScope, $parse, editableFormController) {
return {
restrict: 'A',
require: ['form'],
//require: ['form', 'editableForm'],
//controller: EditableFormController,
compile: function() {
return {
pre: function(scope, elem, attrs, ctrl) {
var form = ctrl[0];
var eForm;
/*
Maybe it's better attach editable controller to form's controller not in pre()
but in controller itself.
This allows to use ng-init already in <form> tag, otherwise we can't (in FF).
*/
//if `editableForm` has value - publish smartly under this value
//this is required only for single editor form that is created and removed
if(attrs.editableForm) {
if(scope[attrs.editableForm] && scope[attrs.editableForm].$show) {
eForm = scope[attrs.editableForm];
angular.extend(form, eForm);
} else {
eForm = editableFormController();
scope[attrs.editableForm] = eForm;
angular.extend(eForm, form);
}
} else { //just merge to form and publish if form has name
eForm = editableFormController();
angular.extend(form, eForm);
}
//read editables from buffer (that appeared before FORM tag)
var buf = $rootScope.$$editableBuffer;
var name = form.$name;
if(name && buf && buf[name]) {
angular.forEach(buf[name], function(editable) {
eForm.$addEditable(editable);
});
delete buf[name];
}
},
post: function(scope, elem, attrs, ctrl) {
var eForm;
if(attrs.editableForm && scope[attrs.editableForm] && scope[attrs.editableForm].$show) {
eForm = scope[attrs.editableForm];
} else {
eForm = ctrl[0];
}
/**
* Called when form is shown.
*
* @var {method|attribute} onshow
* @memberOf editable-form
*/
if(attrs.onshow) {
eForm.$onshow = angular.bind(eForm, $parse(attrs.onshow), scope);
}
/**
* Called when form hides after both save or cancel.
*
* @var {method|attribute} onhide
* @memberOf editable-form
*/
if(attrs.onhide) {
eForm.$onhide = angular.bind(eForm, $parse(attrs.onhide), scope);
}
/**
* Called when form is cancelled.
*
* @var {method|attribute} oncancel
* @memberOf editable-form
*/
if(attrs.oncancel) {
eForm.$oncancel = angular.bind(eForm, $parse(attrs.oncancel), scope);
}
/**
* Whether form initially rendered in shown state.
*
* @var {bool|attribute} shown
* @memberOf editable-form
*/
if(attrs.shown && $parse(attrs.shown)(scope)) {
eForm.$show();
}
// onbeforesave, onaftersave
if(!attrs.ngSubmit && !attrs.submit) {
/**
* Called after all children `onbeforesave` callbacks but before saving form values
* to model.
* If at least one children callback returns `non-string` - it will not not be called.
* See [editable-form demo](#editable-form) for details.
*
* @var {method|attribute} onbeforesave
* @memberOf editable-form
*
*/
if(attrs.onbeforesave) {
eForm.$onbeforesave = function() {
return $parse(attrs.onbeforesave)(scope, {$data: eForm.$data});
};
}
/**
* Called when form values are saved to model.
* See [editable-form demo](#editable-form) for details.
*
* @var {method|attribute} onaftersave
* @memberOf editable-form
*
*/
if(attrs.onaftersave) {
eForm.$onaftersave = function() {
return $parse(attrs.onaftersave)(scope, {$data: eForm.$data});
};
}
elem.bind('submit', function(event) {
event.preventDefault();
scope.$apply(function() {
eForm.$submit();
});
});
}
}
};
}
};
}]);
/*
Helpers
*/
/*
Collect results of function calls. Shows waiting if there are promises.
Finally, applies callbacks if:
- onTrue(): all results are true and all promises resolved to true
- onFalse(): at least one result is false or promise resolved to false
- onString(): at least one result is string or promise rejected or promise resolved to string
*/
angular.module('xeditable').factory('editablePromiseCollection', ['$q', function($q) {
function promiseCollection() {
return {
promises: [],
hasFalse: false,
hasString: false,
when: function(result, noPromise) {
if (result === false) {
this.hasFalse = true;
} else if (!noPromise && angular.isObject(result)) {
this.promises.push($q.when(result));
} else if (angular.isString(result)){
this.hasString = true;
} else { //result === true || result === undefined || result === null
return;
}
},
//callbacks: onTrue, onFalse, onString
then: function(callbacks) {
callbacks = callbacks || {};
var onTrue = callbacks.onTrue || angular.noop;
var onFalse = callbacks.onFalse || angular.noop;
var onString = callbacks.onString || angular.noop;
var onWait = callbacks.onWait || angular.noop;
var self = this;
if (this.promises.length) {
onWait(true);
$q.all(this.promises).then(
//all resolved
function(results) {
onWait(false);
//check all results via same `when` method (without checking promises)
angular.forEach(results, function(result) {
self.when(result, true);
});
applyCallback();
},
//some rejected
function(error) {
onWait(false);
onString();
}
);
} else {
applyCallback();
}
function applyCallback() {
if (!self.hasString && !self.hasFalse) {
onTrue();
} else if (!self.hasString && self.hasFalse) {
onFalse();
} else {
onString();
}
}
}
};
}
return promiseCollection;
}]);
angular.module('xeditable').factory('editableUtils', [function() {
return {
indexOf: function (array, obj) {
if (array.indexOf) return array.indexOf(obj);
for ( var i = 0; i < array.length; i++) {
if (obj === array[i]) return i;
}
return -1;
},
arrayRemove: function (array, value) {
var index = this.indexOf(array, value);
if (index >= 0) {
array.splice(index, 1);
}
return value;
},
// copy from https://github.com/angular/angular.js/blob/master/src/Angular.js
camelToDash: function(str) {
var SNAKE_CASE_REGEXP = /[A-Z]/g;
return str.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
return (pos ? '-' : '') + letter.toLowerCase();
});
},
dashToCamel: function(str) {
var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
var MOZ_HACK_REGEXP = /^moz([A-Z])/;
return str.
replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
return offset ? letter.toUpperCase() : letter;
}).
replace(MOZ_HACK_REGEXP, 'Moz$1');
}
};
}]);
/*
Editable themes:
- default
- bootstrap 2
- bootstrap 3
Note: in postrender() `this` is instance of editableController
*/
angular.module('xeditable').factory('editableThemes', function() {
var themes = {
//default
'default': {
formTpl: '<form class="editable-wrap"></form>',
noformTpl: '<span class="editable-wrap"></span>',
controlsTpl: '<span class="editable-controls"></span>',
inputTpl: '',
errorTpl: '<div class="editable-error" ng-show="$error">{{$error}}</div>',
buttonsTpl: '<span class="editable-buttons"></span>',
submitTpl: '<button type="submit" class="btn btn-primary">save</button>',
cancelTpl: '<button type="button" class="btn btn-primary" ng-click="$form.$cancel()">cancel</button>'
},
//bs2
'bs2': {
formTpl: '<form class="form-inline editable-wrap" role="form"></form>',
noformTpl: '<span class="editable-wrap"></span>',
controlsTpl: '<div class="editable-controls controls control-group" ng-class="{\'error\': $error}"></div>',
inputTpl: '',
errorTpl: '<div class="editable-error help-block" ng-show="$error">{{$error}}</div>',
buttonsTpl: '<span class="editable-buttons"></span>',
submitTpl: '<button type="submit" class="btn btn-primary"><span class="icon-ok icon-white"></span></button>',
cancelTpl: '<button type="button" class="btn" ng-click="$form.$cancel()">'+
'<span class="icon-remove"></span>'+
'</button>'
},
//bs3
'bs3': {
formTpl: '<form class="form-inline editable-wrap" role="form"></form>',
noformTpl: '<span class="editable-wrap"></span>',
controlsTpl: '<div class="editable-controls form-group" ng-class="{\'has-error\': $error}"></div>',
inputTpl: '',
errorTpl: '<div class="editable-error help-block" ng-show="$error">{{$error}}</div>',
buttonsTpl: '<span class="editable-buttons"></span>',
submitTpl: '<button type="submit" class="btn btn-primary"><span class="glyphicon glyphicon-ok"></span></button>',
cancelTpl: '<button type="button" class="btn btn-default" ng-click="$form.$cancel()">'+
'<span class="glyphicon glyphicon-remove"></span>'+
'</button>',
//bs3 specific prop to change buttons class: btn-sm, btn-lg
buttonsClass: '',
//bs3 specific prop to change standard inputs class: input-sm, input-lg
inputClass: '',
postrender: function() {
//apply `form-control` class to std inputs
switch(this.directiveName) {
case 'editableText':
case 'editableSelect':
case 'editableTextarea':
this.inputEl.addClass('form-control');
if(this.theme.inputClass) {
// don`t apply `input-sm` and `input-lg` to select multiple
// should be fixed in bs itself!
if(this.inputEl.attr('multiple') &&
(this.theme.inputClass === 'input-sm' || this.theme.inputClass === 'input-lg')) {
break;
}
this.inputEl.addClass(this.theme.inputClass);
}
break;
}
//apply buttonsClass (bs3 specific!)
if(this.buttonsEl && this.theme.buttonsClass) {
this.buttonsEl.find('button').addClass(this.theme.buttonsClass);
}
}
}
};
return themes;
}); |
/**
* @file Ingress-ICE, common utilities, not related to Google/Niantic
* @license MIT
*/
/*global version */
/*global phantom */
/**
* console.log() wrapper
* @param {String} str - what to announce
*/
function announce(str) {
console.log(getDateTime(0) + ': ' + str);
}
/**
* Returns Date and time
* @param {number} format - the format of output, 0 for DD.MM.YYY HH:MM:SS, 1 for YYYY-MM-DD--HH-MM-SS (for filenames)
* @returns {String} date
*/
function getDateTime(format) {
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth()+1;
var day = now.getDate();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
if(month.toString().length === 1) {
month = '0' + month;
}
if(day.toString().length === 1) {
day = '0' + day;
}
if(hour.toString().length === 1) {
hour = '0' + hour;
}
if(minute.toString().length === 1) {
minute = '0' + minute;
}
if(second.toString().length === 1) {
second = '0' + second;
}
var dateTime;
if (format === 1) {
dateTime = year + '-' + month + '-' + day + '--' + hour + '-' + minute + '-' + second;
} else {
dateTime = day + '.' + month + '.' + year + ' '+hour+':'+minute+':'+second;
}
return dateTime;
}
/**
* Quit if an error occured
* @param {String} err - the error text
*/
function quit(err) {
if (err) {
announce('ICE crashed. Reason: ' + err + ' :(');
} else {
announce('Quit');
}
phantom.exit();
}
/**
* Greeter. Beautiful ASCII-Art logo.
*/
function greet() {
console.log('\n _____ ) ___ _____) \n (, / (__/_____) / \n / / )__ \n ___/__ / / \n(__ / (______) (_____) v' + version + '\n\nIf you need help or want a new feature, visit https://github.com/nibogd/ingress-ice/issues');
}
|
"use strict";
var AbstractView = require('./abstract'),
util = require('util'),
Inflector = require('../inflector/inflector');
/**
* This is the main view object.
* Which is also used by default.
*
* @class ViewJson
* @extends AbstractView
* @param {Object} config The config object
* @constructor
*/
function ViewJson(config) {
AbstractView.call(this, config);
}
util.inherits(ViewJson, AbstractView);
/**
* This method will receive a model object and will set it locally.
* Also it will set the mimetype of the response.
*
* @method initialize
* @param {Object} config The config object of the object
* @returns {Promise} The initialized object.
*/
ViewJson.prototype.initialize = function (config) {
config.mimetype = 'application/json';
return AbstractView.prototype.initialize.call(this, config);
};
/**
* This is the overridden display method which will format our data and return it to the controller when done.
*
* @method display
* @returns {Promise} The promise containing the json as a string.
*/
ViewJson.prototype.display = function () {
var self = this;
if (Inflector.isPlural(self.request.view)) {
return this._viewPlural(self.data);
}
return this._viewSingle(self.data);
};
/**
* The _viewSingle method will display a single object together with the provided states.
*
* @method _viewSingle
* @private
* @param {Object} data The data to convert to a string.
* @returns {Object} The JSON string containing a single object.
*/
ViewJson.prototype._viewSingle = function(data) {
var self = this;
return Promise.resolve(data)
.then(function(data) {
return JSON.stringify({
item: data.getData(),
states: self.model.states.get()
});
});
};
/**
* The _viewPlural method will display a list of objects together with the provided states.
*
* @method _viewPlural
* @private
* @param {Object} data The data to convert to a string.
* @returns {Object} The JSON string containing a list of objects.
*/
ViewJson.prototype._viewPlural = function(data) {
var self = this;
return Promise.resolve(data)
.then(function(data) {
return self.model.getTotal()
.then(function(total) {
return JSON.stringify({
items: data.getData(),
total: total,
states: self.model.states.get()
});
});
});
};
module.exports = ViewJson;
|
window.onload=function() {
document.getElementById("meetup-login").addEventListener("click", function () {
window.location = TWIG.logoutUrl;
});
} |
const a = [];
export default a; |
function preLoad() {
if (!this.support.loading) {
alert("You need the Flash Player to use SWFUpload.");
return false;
} else if (!this.support.imageResize) {
alert("You need Flash Player 10 to upload resized images.");
return false;
}
}
function loadFailed() {
alert("Something went wrong while loading SWFUpload. If this were a real application we'd clean up and then give you an alternative");
}
function fileQueueError(file, errorCode, message) {
try {
var imageName = "error.gif";
var errorName = "";
if (errorCode === SWFUpload.errorCode_QUEUE_LIMIT_EXCEEDED) {
errorName = "You have attempted to queue too many files.";
}
if (errorName !== "") {
alert(errorName);
return;
}
switch (errorCode) {
case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
imageName = "zerobyte.gif";
break;
case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
imageName = "toobig.gif";
break;
case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
default:
alert(message);
break;
}
addImage("images/" + imageName);
} catch (ex) {
this.debug(ex);
}
}
function fileDialogComplete(numFilesSelected, numFilesQueued) {
try {
if (numFilesQueued > 0) {
this.startResizedUpload(this.getFile(0).ID, this.customSettings.thumbnail_width, this.customSettings.thumbnail_height, SWFUpload.RESIZE_ENCODING.JPEG, this.customSettings.thumbnail_quality, false);
}
} catch (ex) {
this.debug(ex);
}
}
function uploadProgress(file, bytesLoaded) {
try {
var percent = Math.ceil((bytesLoaded / file.size) * 100);
var progress = new FileProgress(file, this.customSettings.upload_target);
progress.setProgress(percent);
progress.setStatus("Uploading...");
progress.toggleCancel(true, this);
} catch (ex) {
this.debug(ex);
}
}
function uploadSuccess(file, serverData) {
try {
var progress = new FileProgress(file, this.customSettings.upload_target);
if (serverData.substring(0, 7) === "FILEID:") {
addImage("thumbnail.php?id=" + serverData.substring(7));
progress.setStatus("Upload Complete.");
progress.toggleCancel(false);
} else {
addImage("images/error.gif");
progress.setStatus("Error.");
progress.toggleCancel(false);
alert(serverData);
}
} catch (ex) {
this.debug(ex);
}
}
function uploadComplete(file) {
try {
/* I want the next upload to continue automatically so I'll call startUpload here */
if (this.getStats().files_queued > 0) {
this.startResizedUpload(this.getFile(0).ID, this.customSettings.thumbnail_width, this.customSettings.thumbnail_height, SWFUpload.RESIZE_ENCODING.JPEG, this.customSettings.thumbnail_quality, false);
} else {
var progress = new FileProgress(file, this.customSettings.upload_target);
progress.setComplete();
progress.setStatus("All images received.");
progress.toggleCancel(false);
}
} catch (ex) {
this.debug(ex);
}
}
function uploadError(file, errorCode, message) {
var imageName = "error.gif";
var progress;
try {
switch (errorCode) {
case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
try {
progress = new FileProgress(file, this.customSettings.upload_target);
progress.setCancelled();
progress.setStatus("Cancelled");
progress.toggleCancel(false);
}
catch (ex1) {
this.debug(ex1);
}
break;
case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
try {
progress = new FileProgress(file, this.customSettings.upload_target);
progress.setCancelled();
progress.setStatus("Stopped");
progress.toggleCancel(true);
}
catch (ex2) {
this.debug(ex2);
}
case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
imageName = "uploadlimit.gif";
break;
default:
alert(message);
break;
}
addImage("images/" + imageName);
} catch (ex3) {
this.debug(ex3);
}
}
function addImage(src) {
var newImg = document.createElement("img");
newImg.style.margin = "5px";
newImg.style.verticalAlign = "middle";
var divThumbs = document.getElementById("thumbnails");
divThumbs.insertBefore(newImg, divThumbs.firstChild);
//document.getElementById("thumbnails").appendChild(newImg);
if (newImg.filters) {
try {
newImg.filters.item("DXImageTransform.Microsoft.Alpha").opacity = 0;
} catch (e) {
// If it is not set initially, the browser will throw an error. This will set it if it is not set yet.
newImg.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + 0 + ')';
}
} else {
newImg.style.opacity = 0;
}
newImg.onload = function () {
fadeIn(newImg, 0);
};
newImg.src = src;
}
function fadeIn(element, opacity) {
var reduceOpacityBy = 5;
var rate = 30; // 15 fps
if (opacity < 100) {
opacity += reduceOpacityBy;
if (opacity > 100) {
opacity = 100;
}
if (element.filters) {
try {
element.filters.item("DXImageTransform.Microsoft.Alpha").opacity = opacity;
} catch (e) {
// If it is not set initially, the browser will throw an error. This will set it if it is not set yet.
element.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + opacity + ')';
}
} else {
element.style.opacity = opacity / 100;
}
}
if (opacity < 100) {
setTimeout(function () {
fadeIn(element, opacity);
}, rate);
}
}
/* ******************************************
* FileProgress Object
* Control object for displaying file info
* ****************************************** */
function FileProgress(file, targetID) {
this.fileProgressID = "divFileProgress";
this.fileProgressWrapper = document.getElementById(this.fileProgressID);
if (!this.fileProgressWrapper) {
this.fileProgressWrapper = document.createElement("div");
this.fileProgressWrapper.className = "progressWrapper";
this.fileProgressWrapper.id = this.fileProgressID;
this.fileProgressElement = document.createElement("div");
this.fileProgressElement.className = "progressContainer";
var progressCancel = document.createElement("a");
progressCancel.className = "progressCancel";
progressCancel.href = "#";
progressCancel.style.visibility = "hidden";
progressCancel.appendChild(document.createTextNode(" "));
var progressText = document.createElement("div");
progressText.className = "progressName";
progressText.appendChild(document.createTextNode(file.name));
var progressBar = document.createElement("div");
progressBar.className = "progressBarInProgress";
var progressStatus = document.createElement("div");
progressStatus.className = "progressBarStatus";
progressStatus.innerHTML = " ";
this.fileProgressElement.appendChild(progressCancel);
this.fileProgressElement.appendChild(progressText);
this.fileProgressElement.appendChild(progressStatus);
this.fileProgressElement.appendChild(progressBar);
this.fileProgressWrapper.appendChild(this.fileProgressElement);
document.getElementById(targetID).appendChild(this.fileProgressWrapper);
fadeIn(this.fileProgressWrapper, 0);
} else {
this.fileProgressElement = this.fileProgressWrapper.firstChild;
this.fileProgressElement.childNodes[1].firstChild.nodeValue = file.name;
}
this.height = this.fileProgressWrapper.offsetHeight;
}
FileProgress.prototype.setProgress = function (percentage) {
this.fileProgressElement.className = "progressContainer green";
this.fileProgressElement.childNodes[3].className = "progressBarInProgress";
this.fileProgressElement.childNodes[3].style.width = percentage + "%";
};
FileProgress.prototype.setComplete = function () {
this.fileProgressElement.className = "progressContainer blue";
this.fileProgressElement.childNodes[3].className = "progressBarComplete";
this.fileProgressElement.childNodes[3].style.width = "";
};
FileProgress.prototype.setError = function () {
this.fileProgressElement.className = "progressContainer red";
this.fileProgressElement.childNodes[3].className = "progressBarError";
this.fileProgressElement.childNodes[3].style.width = "";
};
FileProgress.prototype.setCancelled = function () {
this.fileProgressElement.className = "progressContainer";
this.fileProgressElement.childNodes[3].className = "progressBarError";
this.fileProgressElement.childNodes[3].style.width = "";
};
FileProgress.prototype.setStatus = function (status) {
this.fileProgressElement.childNodes[2].innerHTML = status;
};
FileProgress.prototype.toggleCancel = function (show, swfuploadInstance) {
this.fileProgressElement.childNodes[0].style.visibility = show ? "visible" : "hidden";
if (swfuploadInstance) {
var fileID = this.fileProgressID;
this.fileProgressElement.childNodes[0].onclick = function () {
swfuploadInstance.cancelUpload(fileID);
return false;
};
}
};
|
/**
* Welcome to your Workbox-powered service worker!
*
* You'll need to register this file in your web app and you should
* disable HTTP caching for this file too.
* See https://goo.gl/nhQhGp
*
* The rest of the code is auto-generated. Please don't update this file
* directly; instead, make changes to your Workbox build configuration
* and re-run your build process.
* See https://goo.gl/2aRDsh
*/
importScripts("https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js");
importScripts(
"/precache-manifest.ccbdeeb71afb649b0da09d906ed467da.js"
);
self.addEventListener('message', (event) => {
if (event.data && event.data.type === 'SKIP_WAITING') {
self.skipWaiting();
}
});
workbox.core.clientsClaim();
/**
* The workboxSW.precacheAndRoute() method efficiently caches and responds to
* requests for URLs in the manifest.
* See https://goo.gl/S9QRab
*/
self.__precacheManifest = [].concat(self.__precacheManifest || []);
workbox.precaching.precacheAndRoute(self.__precacheManifest, {});
workbox.routing.registerNavigationRoute(workbox.precaching.getCacheKeyForURL("/index.html"), {
blacklist: [/^\/_/,/\/[^\/?]+\.[^\/]+$/],
});
|
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path d="M8.14 9.3l-1.01 2.89h2.09L8.2 9.3z" /><path d="M22.42 8c-.27 0-.51.19-.57.45l-1.1 4.65h-.06l-1.33-4.57c-.09-.31-.38-.53-.71-.53-.32 0-.61.21-.7.52l-1.4 4.59h-.05l-1.1-4.66c-.06-.26-.3-.45-.57-.45-.32 0-.55.26-.57.55C13.06 6.43 10.79 5 8.17 5c-3.87 0-7 3.13-7 7s3.13 7 7 7c3.83 0 6.93-3.08 6.99-6.89l.62 2.33c.09.33.38.56.72.56.33 0 .62-.22.72-.54l1.4-4.7h.06L20 14.45c.1.33.39.55.73.55h.02c.34 0 .64-.23.72-.56l1.51-5.71c.1-.37-.18-.73-.56-.73zm-11.8 7c-.24 0-.45-.15-.53-.38l-.49-1.41H6.77l-.5 1.42c-.09.22-.3.37-.54.37-.39 0-.67-.39-.53-.76l2.12-5.65c.14-.36.48-.59.85-.59s.71.23.85.59l2.12 5.65c.14.37-.13.76-.52.76z" /></React.Fragment>
, 'WbAutoRounded');
|
(function() {
mw.loader.using(['jquery', 'oojs-ui', 'mediawiki.util', 'mediawiki.api'], function() {
if ($.inArray('合理使用理據待檢查影像', mw.config.get('wgCategories')) === -1) {
return;
}
function mark() {
var templates = [
'Euro coin copyright tag',
'Non-free album cover', 'Albumcover',
'Non-free architectural work',
'Non-free biog-pic', 'Dead', 'NFBP',
'Non-free Canadian Crown Copyright',
'Non-free Crown copyright', 'Ir-Crown-UK',
'Non-free currency-EU coin national',
'Non-free historic image', 'HistoricImageRationale', 'Historicphoto',
'Non-free logo', 'Tv-logo', 'Gamelogo', 'Logo',
'Non-free Old-50',
'Non-free Old-70',
'Non-free Philippines government',
'Non-free poster', 'Movie poster', 'Posters', 'Politicalposter', 'Movieposter', 'Poster', 'Non-free movie poster',
'Non-free product cover',
'Non-free school logo',
'Non-free Scout logo', 'Non-Free Scout Logo', 'Non-Free Scout logo',
'Non-free seal',
'Non-free sheet music',
'Non-free software cover',
'Non-free title-card', 'Titlecard',
'Non-free video game cover', 'Non-free game cover', 'Gamecover',
'Non-free video game screenshot', 'Non-free game screenshot', 'Game-screenshot',
'Non-free video screenshot',
'Non-free web screenshot', 'Web-screenshot',
'Software-screenshot', 'Mac-software-screenshot', 'Windows-software-screenshot', 'Non-free software screenshot',
'Symbol', 'Coatofarms', 'Non-free flag', 'Seal', 'Non-free symbol',
'非自由奥林匹克媒体', 'Non-free Olympics media',
'音訊樣本', 'Music sample', 'Non-free audio sample',
];
var temregex = $(templates).map(function() {
var temp = this;
temp = temp.replace(/[ _]/g, '[ _]');
if (temp[0].toUpperCase() != temp[0].toLowerCase()) {
temp = '[' + temp[0].toUpperCase() + temp[0].toLowerCase() + ']' + temp.substr(1)
}
return temp;
}).get().join('|');
new mw.Api().edit(mw.config.get('wgPageName'), function(revision) {
var content = revision.content;
var regex = new RegExp('{{\\s*(' + temregex + ')\\s*(?:\\|.+?)?}}', 'g');
var m;
var cnt = 0;
while ((m = regex.exec(content)) !== null) {
mw.notify('在頁面上找到 ' + m[1])
cnt += 1;
}
if (cnt == 0) {
mw.notify('在頁面上找不到任何合理使用模板');
return $.Deferred().reject('fail');
}
regex = new RegExp('({{\\s*(?:' + temregex + ')\\s*(?:\\|.+?)?)}}', 'g');
content = content.replace(regex, '$1|image has rationale=yes}}');
regex = new RegExp('({{\\s*(?:' + temregex + ')\\s*[^{}]*?)\\|image[ _]has[ _]rationale=[^|{}]*([^{}]*?\\|image has rationale=yes}})', 'g');
content = content.replace(regex, '$1$2');
if (content == revision.content) {
mw.notify('標記時發生錯誤');
return $.Deferred().reject('fail');
}
return {
text: content,
basetimestamp: revision.timestamp,
summary: '標記 image has rationale',
minor: true
};
}).then(function() {
mw.notify('已標記 image has rationale');
window.location = mw.util.wikiScript("index") + "?" + $.param({
'title': mw.config.get('wgPageName'),
'diff': 'cur',
'oldid': 'prev'
});
}, function(e) {
if (e == 'editconflict') {
mw.notify('標記時發生編輯衝突');
} else if (e == 'fail') {
//
} else if (e == 'cancel') {
mw.notify('已取消');
} else {
mw.notify('標記時發生未知錯誤:' + e);
}
});
}
$("code:contains('image has rationale')").parent().append('<center><a class="mark_image_has_rationale" href="#"><span class="mw-ui-button mw-ui-progressive">標記 image has rationale</span></a></center>');
$('.mark_image_has_rationale').click(function() {
mark();
return false;
});
});
})();
|
window.fbAsyncInit = function() {
FB.init({
appId : '667375806717283',
xfbml : true,
version : 'v2.2'
});
};
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
|
define(function (require, exports, module) {
'use strict';
/*global tinymce:true */
(function() {
tinymce.create('tinymce.plugins.BBCodePlugin', {
init : function(ed) {
var self = this, dialect = ed.getParam('bbcode_dialect', 'punbb').toLowerCase();
ed.on('beforeSetContent', function(e) {
e.content = self['_' + dialect + '_bbcode2html'](e.content);
});
ed.on('postProcess', function(e) {
if (e.set) {
e.content = self['_' + dialect + '_bbcode2html'](e.content);
}
if (e.get) {
e.content = self['_' + dialect + '_html2bbcode'](e.content);
}
});
},
getInfo: function() {
return {
longname: 'BBCode Plugin',
author: 'Moxiecode Systems AB',
authorurl: 'http://www.tinymce.com',
infourl: 'http://www.tinymce.com/wiki.php/Plugin:bbcode'
};
},
// Private methods
// HTML -> BBCode in PunBB dialect
_punbb_html2bbcode : function(s) {
s = tinymce.trim(s);
function rep(re, str) {
s = s.replace(re, str);
}
// example: <strong> to [b]
rep(/<a.*?href=\"(.*?)\".*?>(.*?)<\/a>/gi,"[url=$1]$2[/url]");
rep(/<font.*?color=\"(.*?)\".*?class=\"codeStyle\".*?>(.*?)<\/font>/gi,"[code][color=$1]$2[/color][/code]");
rep(/<font.*?color=\"(.*?)\".*?class=\"quoteStyle\".*?>(.*?)<\/font>/gi,"[quote][color=$1]$2[/color][/quote]");
rep(/<font.*?class=\"codeStyle\".*?color=\"(.*?)\".*?>(.*?)<\/font>/gi,"[code][color=$1]$2[/color][/code]");
rep(/<font.*?class=\"quoteStyle\".*?color=\"(.*?)\".*?>(.*?)<\/font>/gi,"[quote][color=$1]$2[/color][/quote]");
rep(/<span style=\"color: ?(.*?);\">(.*?)<\/span>/gi,"[color=$1]$2[/color]");
rep(/<font.*?color=\"(.*?)\".*?>(.*?)<\/font>/gi,"[color=$1]$2[/color]");
rep(/<span style=\"font-size:(.*?);\">(.*?)<\/span>/gi,"[size=$1]$2[/size]");
rep(/<font>(.*?)<\/font>/gi,"$1");
rep(/<img.*?src=\"(.*?)\".*?\/>/gi,"[img]$1[/img]");
rep(/<span class=\"codeStyle\">(.*?)<\/span>/gi,"[code]$1[/code]");
rep(/<span class=\"quoteStyle\">(.*?)<\/span>/gi,"[quote]$1[/quote]");
rep(/<strong class=\"codeStyle\">(.*?)<\/strong>/gi,"[code][b]$1[/b][/code]");
rep(/<strong class=\"quoteStyle\">(.*?)<\/strong>/gi,"[quote][b]$1[/b][/quote]");
rep(/<em class=\"codeStyle\">(.*?)<\/em>/gi,"[code][i]$1[/i][/code]");
rep(/<em class=\"quoteStyle\">(.*?)<\/em>/gi,"[quote][i]$1[/i][/quote]");
rep(/<u class=\"codeStyle\">(.*?)<\/u>/gi,"[code][u]$1[/u][/code]");
rep(/<u class=\"quoteStyle\">(.*?)<\/u>/gi,"[quote][u]$1[/u][/quote]");
rep(/<\/(strong|b)>/gi,"[/b]");
rep(/<(strong|b)>/gi,"[b]");
rep(/<\/(em|i)>/gi,"[/i]");
rep(/<(em|i)>/gi,"[i]");
rep(/<\/u>/gi,"[/u]");
rep(/<span style=\"text-decoration: ?underline;\">(.*?)<\/span>/gi,"[u]$1[/u]");
rep(/<u>/gi,"[u]");
rep(/<blockquote[^>]*>/gi,"[quote]");
rep(/<\/blockquote>/gi,"[/quote]");
rep(/<br \/>/gi,"\n");
rep(/<br\/>/gi,"\n");
rep(/<br>/gi,"\n");
rep(/<p>/gi,"");
rep(/<\/p>/gi,"\n");
rep(/ |\u00a0/gi," ");
rep(/"/gi,"\"");
rep(/</gi,"<");
rep(/>/gi,">");
rep(/&/gi,"&");
return s;
},
// BBCode -> HTML from PunBB dialect
_punbb_bbcode2html : function(s) {
s = tinymce.trim(s);
function rep(re, str) {
s = s.replace(re, str);
}
// example: [b] to <strong>
rep(/\n/gi,"<br />");
rep(/\[b\]/gi,"<strong>");
rep(/\[\/b\]/gi,"</strong>");
rep(/\[i\]/gi,"<em>");
rep(/\[\/i\]/gi,"</em>");
rep(/\[u\]/gi,"<u>");
rep(/\[\/u\]/gi,"</u>");
rep(/\[url=([^\]]+)\](.*?)\[\/url\]/gi,"<a href=\"$1\">$2</a>");
rep(/\[url\](.*?)\[\/url\]/gi,"<a href=\"$1\">$1</a>");
rep(/\[img\](.*?)\[\/img\]/gi,"<img src=\"$1\" />");
rep(/\[color=(.*?)\](.*?)\[\/color\]/gi,"<font color=\"$1\">$2</font>");
rep(/\[code\](.*?)\[\/code\]/gi,"<span class=\"codeStyle\">$1</span> ");
rep(/\[quote.*?\](.*?)\[\/quote\]/gi,"<span class=\"quoteStyle\">$1</span> ");
return s;
}
});
// Register plugin
tinymce.PluginManager.add('bbcode', tinymce.plugins.BBCodePlugin);
})();
});
|
var webpack = require("webpack");
var path = require("path");
var autoprefixer = require("autoprefixer");
module.exports = {
context: __dirname,
entry: {
"application": "./assets/application.js",
"application_server": "./assets/application_server.js"
},
output: {
path: path.join(__dirname, "public/assets/js"),
publicPath: "/assets/js/",
filename: "[name].js",
chunkFilename: "[hash]/js/[id].js",
},
module: {
rules: [
{
test: /\.js?$/,
exclude: /(node_modules|bower_components)/,
use: [
{
loader: 'babel-loader',
options: {
presets: ['es2015'],
plugins: ['transform-runtime']
}
}
],
},
{
test: /\.styl?$/,
exclude: /main\.styl?$/,
use: [
{
loader: 'style-loader'
},
{
loader: 'css-loader'
},
{
loader: 'postcss-loader'
},
{
loader: 'stylus-loader'
}
]
},
{
test: /\.html/,
use: [
{
loader: 'babel-loader',
options: {
presets: ['es2015'],
plugins: ['transform-runtime']
}
},
{
loader: 'template-string-loader'
}
],
},
{
test: /\.svg$/,
use: [
{
loader: 'icons-loader'
}
],
},
{
test: /\.font\.(js|json)$/,
use: [
{
loader: "style-loader"
},
{
loader: "css-loader"
},
{
loader: "fontgen-loader"
}
]
}
],
},
resolve: {
modules: ["node_modules", "assets"],
alias: {
"router": "ascesis/router",
"config": path.join(__dirname, "config/")
}
},
plugins: [
new webpack.ProvidePlugin({
'fetch': 'imports-loader?this=>global!exports-loader?global.fetch!whatwg-fetch'
}),
].concat(process.env['NODE_ENV'] === 'production'
? new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
})
: []
),
};
|
import { Button, Card, Icon, Image as ImageComponent, Item, Label } from 'semantic-ui-react';
import React, { Component } from 'react';
import PropTypes from 'prop-types';
class CarsItem extends Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
// this.handleAddClick = this.handleAddClick.bind(this);
// this.handleRemoveClick = this.handleRemoveClick.bind(this);
}
handleClick() {
const ifAddItemInCart = this.props.selected;
if (ifAddItemInCart) {
this.props.removeItemFromCart();
console.log('REMOVE FROM CART');
} else {
this.props.addItemToCart();
console.log('ADD TO CART');
}
}
// handleAddClick() {
// this.props.addItemToCart();
// console.log('ADD TO CART');
// }
// handleRemoveClick() {
// this.props.removeItemFromCart();
// console.log('REMOVE FROM CART');
// }
render() {
const itemInCart = this.props.selected;
const {
img,
modelName,
price,
description,
} = this.props;
return (
<Item>
<Item.Image src={img} size="tiny" />
<Item.Content>
<Item.Header as="a"><h3>{modelName}</h3></Item.Header>
<Item.Description>{description}</Item.Description>
<Item.Extra>
<Button
content={!itemInCart ? ('Add To Cart') : ('Remove')}
type="button"
color={!itemInCart ? ('teal') : ('red')}
floated="right"
className={!itemInCart ? ('btn') : ('btn-remove')}
onClick={this.handleClick}
// onClick={!itemInCart ? (this.handleAddClick) : (this.handleRemoveClick)}
/>
<Label>IMAX</Label>
<Label icon="dollar" content={price} />
</Item.Extra>
</Item.Content>
</Item>
);
}
}
CarsItem.propTypes = {
id: PropTypes.number,
modelName: PropTypes.string,
price: PropTypes.number,
img: PropTypes.string,
description: PropTypes.string,
};
export default CarsItem;
|
module.exports = function (pages, done) {
pages.forEach(function (val, key) {
if (key - 1 > -1) {
pages[key].next = pages[key - 1]
}
if (key + 1 < pages.length) {
pages[key].previous = pages[key + 1]
}
})
done(null, pages)
}
|
var find = require('dom-select');
var EVENT = require('../../../model/model').socketEvents;
var SERVERNAME = window.location.origin;
var Cookies = require('cookies-js');
var Import = require('./shapes/Import');
module.exports = function(io, framework, AppState){
var curSession = window.location.href;
curSession = curSession.split('/');
var end = curSession.length -1;
var curSessionId = curSession[end];
curSession = '/'+curSession[end - 1] +'/'+ curSession[end];
var socket = io.connect(SERVERNAME);
socket.on(EVENT.badSession,function(){
socket.nsp = '/home';
});
socket.emit(EVENT.validateSession, curSessionId);
socket = io.connect(SERVERNAME + curSession);
socket.on('connect', function(info) {
//AppState.sessionId = curSessionId;
});
// if(Cookies.get('UserId') === curSessionId) {
// socket.emit(EVENT.joinSession);
// }
//socket.emit(EVENT.joinSession);
//};
socket.on(EVENT.announcement,function(msg){
//update user list clientside
//update chat tab with msg
var Chattab = find('.chatMessageBox .chatMessages');
var li = document.createElement('li');
li.innerHTML = msg;
Chattab.appendChild(li);
//adjust all users priority
//send edited user list to db
});
socket.on(EVENT.deleteSession,function(){
socket.disconnect();
framework.go('/home');
location.reload();
});
socket.on(EVENT.clearShapes, function(){
console.log('clearing shapes')
APP_STATE.clearShapes();
});
socket.on(EVENT.removeShape, function(shapeId) {
AppState.Canvas.Shapes.removeShapeByID(shapeId);
});
// socket.on(EVENT.imageUpload, function(location) {
// image = new Import(AppState.Tools.importer, location);
// image = AppState.Canvas.Shapes.addNew(image);
// image.setMoveListeners(AppState);
// });
return socket;
}
|
module.exports = {
endpoint: "http://example.com"
}
|
const os = require('os');
const shelljs = require('shelljs');
const nixt = require('nixt');
const cliPath = `${__dirname}/../node_modules/.bin/yo`;
const tmpDir = `${os.tmpdir()}/generator-angular-lib-test`;
describe('generator', () => {
it('should run successfully', done => {
console.info('Testing generator in', tmpDir);
shelljs.rm('-rf', tmpDir);
shelljs.mkdir(tmpDir);
shelljs.exec('npm link');
nixt()
.cwd(tmpDir)
.run(`${cliPath} angular-library`)
.on(/What is the github project organisation or username/).respond('mattlewis92\n')
.on(/What is the github repository name/).respond('angular-lib-test\n')
.on(/What is the npm module name/).respond('angular-lib-test\n')
.on(/What should the NgModule name be/).respond('LibTestModule\n')
.on(/What should the component \/ directive selector prefix be /).respond('mwl\n')
.on(/What is the human readable project title/).respond('\n')
.on(/What is the project description/).respond('Description\n')
.on(/What is the author name/).respond('Matt Lewis\n')
.on(/What package manager should be used to install dependencies/).respond('\n')
.end(err => {
if (err) {
return done(err);
}
shelljs.cd(tmpDir);
const commands = ['npm test', 'npm run build:demo', 'npm run compodoc'];
const failedCommands = commands
.map(command => shelljs.exec(command))
.filter(result => result.code !== 0);
shelljs.rm('-rf', tmpDir);
if (failedCommands.length > 0) {
done(new Error('Generator test failed'));
} else {
done();
}
});
});
});
|
import {combineReducers} from 'redux';
import {routeReducer} from 'redux-simple-router';
import users from './users';
import app from './app';
import files from './files';
import data from './data';
export default combineReducers({
routing: routeReducer,
app,
users,
files,
data
});
|
import path from 'path';
import baseConfig from './base.config';
export default baseConfig({
input: {
app: [path.join(__dirname, '../src/web/index')]
},
output: {
path: path.join(__dirname, '../build/electron/js')
},
globals: {
'process.env': {
NODE_ENV: '"production"'
}
}
});
|
(function() {
var LineBuffer, Stream, async, exec, fs, getUserShell, parseEnv, path, spawn,
__hasProp = Object.prototype.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; },
__slice = Array.prototype.slice;
fs = require("fs");
path = require("path");
async = require("async");
exec = require("child_process").exec;
spawn = require("child_process").spawn;
Stream = require('stream').Stream;
exports.LineBuffer = LineBuffer = (function(_super) {
__extends(LineBuffer, _super);
function LineBuffer(stream) {
var self;
this.stream = stream;
this.readable = true;
this._buffer = "";
self = this;
this.stream.on('data', function() {
var args;
args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
return self.write.apply(self, args);
});
this.stream.on('end', function() {
var args;
args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
return self.end.apply(self, args);
});
}
LineBuffer.prototype.write = function(chunk) {
var index, line, _results;
this._buffer += chunk;
_results = [];
while ((index = this._buffer.indexOf("\n")) !== -1) {
line = this._buffer.slice(0, index);
this._buffer = this._buffer.slice(index + 1, this._buffer.length);
_results.push(this.emit('data', line));
}
return _results;
};
LineBuffer.prototype.end = function() {
var args;
args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
if (args.length > 0) this.write.apply(this, args);
if (this._buffer.length) this.emit('data', this._buffer);
return this.emit('end');
};
return LineBuffer;
})(Stream);
exports.bufferLines = function(stream, callback) {
var buffer;
buffer = new LineBuffer(stream);
buffer.on("data", callback);
return buffer;
};
exports.mkdirp = function(dirname, callback) {
var p;
return fs.lstat((p = path.normalize(dirname)), function(err, stats) {
var paths;
if (err) {
paths = [p].concat((function() {
var _results;
_results = [];
while (p !== "/" && p !== ".") {
_results.push(p = path.dirname(p));
}
return _results;
})());
return async.forEachSeries(paths.reverse(), function(p, next) {
return path.exists(p, function(exists) {
if (exists) {
return next();
} else {
return fs.mkdir(p, 0755, function(err) {
if (err) {
return callback(err);
} else {
return next();
}
});
}
});
}, callback);
} else if (stats.isDirectory()) {
return callback();
} else {
return callback("file exists");
}
});
};
exports.chown = function(path, owner, callback) {
var chown, error;
error = "";
chown = spawn("chown", [owner, path]);
chown.stderr.on("data", function(data) {
return error += data.toString("utf8");
});
return chown.on("exit", function(code) {
return callback(error, code === 0);
});
};
exports.pause = function(stream) {
var onClose, onData, onEnd, queue, removeListeners;
queue = [];
onData = function() {
var args;
args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
return queue.push(['data'].concat(__slice.call(args)));
};
onEnd = function() {
var args;
args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
return queue.push(['end'].concat(__slice.call(args)));
};
onClose = function() {
return removeListeners();
};
removeListeners = function() {
stream.removeListener('data', onData);
stream.removeListener('end', onEnd);
return stream.removeListener('close', onClose);
};
stream.on('data', onData);
stream.on('end', onEnd);
stream.on('close', onClose);
return function() {
var args, _i, _len, _results;
removeListeners();
_results = [];
for (_i = 0, _len = queue.length; _i < _len; _i++) {
args = queue[_i];
_results.push(stream.emit.apply(stream, args));
}
return _results;
};
};
exports.sourceScriptEnv = function(script, env, options, callback) {
var command;
if (options.call) {
callback = options;
options = {};
} else {
if (options == null) options = {};
}
command = "" + options.before + ";\nsource '" + script + "' > /dev/null;\nenv";
return exec(command, {
cwd: path.dirname(script),
env: env
}, function(err, stdout, stderr) {
if (err) {
err.message = "'" + script + "' failed to load";
err.stdout = stdout;
err.stderr = stderr;
callback(err);
}
return callback(null, parseEnv(stdout));
});
};
exports.getUserEnv = function(callback) {
var user;
user = process.env.LOGNAME;
return getUserShell(function(shell) {
return exec("env", function(err, stdout, stderr) {
if (err) {
return callback(err);
} else {
return callback(null, parseEnv, stdout);
}
});
});
};
getUserShell = function(callback) {
var command;
command = "dscl . -read '/Users/" + process.env.LOGNAME + "' UserShell";
return exec(command, function(err, stdout, stderr) {
var match, matches, shell;
if (err) {
return callback(process.env.SHELL);
} else {
if (matches = stdout.trim().match(/^UserShell: (.+)$/)) {
match = matches[0], shell = matches[1];
return callback(shell);
} else {
return callback(process.env.SHELL);
}
}
});
};
parseEnv = function(stdout) {
var env, line, match, matches, name, value, _i, _len, _ref;
env = {};
_ref = stdout.split("\n");
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
line = _ref[_i];
if (matches = line.match(/([^=]+)=(.+)/)) {
match = matches[0], name = matches[1], value = matches[2];
env[name] = value;
}
}
return env;
};
}).call(this);
|
!function(t){function n(r){if(e[r])return e[r].exports;var o=e[r]={exports:{},id:r,loaded:!1};return t[r].call(o.exports,o,o.exports,n),o.loaded=!0,o.exports}var e={};return n.m=t,n.c=e,n.p="",n(0)}([function(t,n,e){"use strict";e(4),function(t,n,e){function r(n,r){var s=arguments.length>2&&arguments[2]!==e?arguments[2]:"",c=arguments[3];(n=i[n])&&(t("body").append('<div class="x-tips J-x-tips '+n+" "+s+'"><p>'+r+"</p></div>"),o(c))}var o=void 0,i={success:"x-tips-success",error:"x-tips-error"};(o=function(){var n=arguments.length>0&&arguments[0]!==e?arguments[0]:2e3,r=void 0,o=t(".J-x-tips"),i=(o.length,0);(r=function(t){var e=o.eq(t);e&&e.stop(!0,!0).fadeIn(function(){e.delay(n).fadeOut(function(){e.remove(),r(t+1)})})})(i)})(),t.tips=r}(jQuery,window)},,,,function(t,n){}]); |
import controller from './upArrow.controller'
export default function upArrow(){
return {
restrict: 'EA',
scope: {
},
template: require("./upArrow.tpl.html"),
controller: controller.UID,
controllerAs: "vm",
bindToController: true,
link: (scope, el, attr, ctrl) => {
}
}
}
|
// layout defaults
var LayoutDefaults = {
'lineHeight': 1.2,
'margin': .5,
'pageWidth': 8.5,
'pageHeight': 11,
'transpose': 0,
'capo': 0,
'flats': false,
'fontSize': 14,
'fontFiles': {
'regular': 'fonts/OpenSans/OpenSans-Regular.ttf',
'bold': 'fonts/OpenSans/OpenSans-Bold.ttf'
},
// song information
'metadata': {},
// decorations
'decorations': [],
// auto flats feature
'autoFlats': {
'enabled': false,
'favorFlats': true // only applies to F#/Gb
},
// transform all chords - even if transposition is 0, chords are processed
'transformAllChords': false,
// use ♯ and ♭ instead of # and b
'useFancySymbols': false
};
module.exports = LayoutDefaults; |
'use strict';
module.exports = function(app) {
var users = require('../../app/controllers/users.server.controller');
var trips = require('../../app/controllers/trips.server.controller');
// Trips Routes
app.route('/trips')
.get(trips.list)
.post(users.requiresLogin, trips.create);
app.route('/trips/:tripId')
.get(trips.read)
.put(users.requiresLogin, trips.hasAuthorization, trips.update)
.delete(users.requiresLogin, trips.hasAuthorization, trips.delete);
// Finish by binding the Trip middleware
app.param('tripId', trips.tripByID);
};
|
version https://git-lfs.github.com/spec/v1
oid sha256:6c9c8a94f3233ce93cf461951456edee840d47380250675151562b842bded867
size 21793
|
'use strict';
(function () {
var BASE64_MARKER = ';base64,';
function convertDataURIToBinary(dataURI) {
var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
var base64 = dataURI.substring(base64Index);
var raw = window.atob(base64);
var rawLength = raw.length;
var array = new Uint8Array(new ArrayBuffer(rawLength));
var i;
for (i = 0; i < rawLength; i++) {
array[i] = raw.charCodeAt(i);
}
return array;
}
function delta (root, name) {
if (root && root[name]) {
var res = Number(root[name]);
if ((res !== 1) && (res !== -1)) { return 0; }
return res;
}
return 0;
}
function ring (name, inc, size, init) {
var res;
res = parseInt(localStorage [name]);
if (res || res === 0) {
res += inc;
if (res >= size) {
res -= size;
} else if (res < 0) {
res += size;
}
} else {
res = init;
}
localStorage [name] = res;
return res;
}
function setStyle (id, prop) {
var e = document.getElementById(id);
e.removeAttribute('style');
for (var p in prop) {
e.style [p] = prop [p];
}
}
function editorState (op) {
var drot = delta(op, 'rot');
var dper = delta(op, 'per');
var rot = ring('drom.editor.rot', drot, 4, 0);
var per = ring('drom.editor.per', dper, 7, 3);
var sizeTXT = ((per + 2) * 10) + '%';
var sizeSVG = ((8 - per) * 10) + '%';
var styleTXT, styleSVG;
if (rot === 1) { // SVG|TXT
styleSVG = {width: sizeSVG, height: '100%', cssFloat: 'left', overflow: 'hidden'};
styleTXT = {height: '100%'};
} else if (rot === 2) { // SVG/TXT
styleSVG = {width: '100%', height: sizeSVG, overflow: 'hidden'};
styleTXT = {height: sizeTXT};
} else if (rot === 3) { // TXT|SVG
styleSVG = {width: sizeSVG, height: '100%', cssFloat: 'right', overflow: 'hidden'};
styleTXT = {width: sizeTXT, height: '100%'};
} else { // TXT/SVG
styleSVG = {width: '100%', height: sizeSVG, position: 'absolute', bottom: 0, overflow: 'hidden'};
styleTXT = {height: sizeTXT};
}
setStyle('SVG', styleSVG);
setStyle('TXT', styleTXT);
WaveDrom.EditorRefresh();
}
function editorInit () {
if (document.location.search) {
WaveDrom.cm.setValue(decodeURIComponent(window.location.search.substr(1)));
// document.getElementById ('InputJSON_0').value = decodeURIComponent(window.location.search.substr(1));
}
window.ondragover = function(e) { e.preventDefault(); return false; };
window.ondrop = function(e) { e.preventDefault(); return false; };
if (typeof process === 'object') { // nodewebkit detection
var holder = document.getElementById('content');
holder.ondragover = function () { this.className = 'hover'; return false; };
holder.ondragend = function () { this.className = ''; return false; };
holder.ondrop = function (e) {
e.preventDefault();
for (var i = 0; i < e.dataTransfer.files.length; ++i) {
console.log(e.dataTransfer.files[i].path);
}
return false;
};
}
editorState();
}
function setFullURL () {
document.location.search = encodeURIComponent(document.getElementById('InputJSON_0').value);
}
function menuOpen (e) {
function closestById(el, id) {
while (el.id !== id) {
el = el.parentNode;
if (!el) {
return null;
}
}
return el;
}
var doc = document.getElementById('menux');
if (closestById(e.target, 'Menu') && (doc.style.display === 'none')) {
doc.style.display = 'inline';
} else {
doc.style.display = 'none';
}
}
function gotoWaveDromHome () {
window.open('http://wavedrom.com').focus();
}
function gotoWaveDromGuide () {
window.open('tutorial.html').focus();
}
function loadJSON () {
function chooseFile(name) {
var chooser = document.querySelector(name);
chooser.addEventListener('change', function() {
var fs = require('fs');
var filename = chooser.value;
if (!filename) { return; }
fs.readFile(filename, 'utf-8', function(err, data) {
if (err) {
console.log('error');
}
WaveDrom.cm.setValue(data);
});
}, false);
chooser.click();
}
if (typeof process === 'object') { // nodewebkit detection
chooseFile('#fileDialogLoad');
} else {
var cfse = window.chooseFileSystemEntries;
if (cfse !== undefined) {
// PWA: https://web.dev/native-file-system/#read-file
cfse().then(function (fh) {
if (fh.isFile === true) {
fh.getFile().then(function (file) {
file.text().then(function (content) {
WaveDrom.cm.setValue(content);
});
});
}
});
}
}
}
function saveJSON () {
var a;
function sjson () {
return localStorage.waveform;
}
function chooseFile(name) {
var chooser = document.querySelector(name);
chooser.addEventListener('change', function() {
var fs = require('fs');
var filename = this.value;
if (!filename) { return; }
fs.writeFile(filename, sjson(), function(err) {
if (err) {
console.log('error');
}
});
this.value = '';
}, false);
chooser.click();
}
if (typeof process === 'object') { // nodewebkit detection
chooseFile('#fileDialogSave');
} else {
var cfse = window.chooseFileSystemEntries;
if (cfse !== undefined) {
// PWA: https://web.dev/native-file-system/#write-file
cfse({
type: 'saveFile',
accepts: [{
description: 'JSON file',
extensions: ['json', 'js', 'json5'],
mimeType: ['application/json', 'text/javascript', 'text/json5']
}]
}).then(function (fh) {
fh.createWriter().then(function (writer) {
writer.write(0, sjson()).then(function () {
writer.close();
});
});
});
} else {
a = document.createElement('a');
a.href = 'data:text/json;base64,' + btoa(sjson());
a.download = 'wavedrom.json';
var theEvent = document.createEvent('MouseEvent');
theEvent.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
a.dispatchEvent(theEvent);
a.click();
}
}
}
function ssvg () {
var svg, ser;
svg = document.getElementsByTagName('svg')[0]; // document.getElementById('svgcontent_0');
ser = new XMLSerializer();
return '<?xml version="1.0" standalone="no"?>\n'
+ '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n'
+ '<!-- Created with WaveDrom -->\n'
+ ser.serializeToString(svg);
}
function saveSVG () {
var a;
function chooseFile(name) {
var chooser = document.querySelector(name);
chooser.addEventListener('change', function() {
var fs = require('fs');
var filename = this.value;
if (!filename) { return; }
fs.writeFile(filename, ssvg(), function(err) {
if(err) {
console.log('error');
}
});
this.value = '';
}, false);
chooser.click();
}
if (typeof process === 'object') { // nodewebkit detection
chooseFile('#fileDialogSVG');
} else {
var cfse = window.chooseFileSystemEntries;
if (cfse !== undefined) {
// PWA: https://web.dev/native-file-system/#write-file
cfse({
type: 'saveFile',
accepts: [{
description: 'SVG file',
extensions: ['svg'],
mimeType: ['image/svg+xml']
}]
}).then(function (fh) {
fh.createWriter().then(function (writer) {
writer.write(0, ssvg()).then(function () {
writer.close();
});
});
});
} else {
a = document.createElement('a');
a.href = 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(ssvg())));
a.download = 'wavedrom.svg';
var theEvent = document.createEvent('MouseEvent');
theEvent.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
a.dispatchEvent(theEvent);
// a.click();
}
}
}
function pngdata (done) {
var img = new Image();
var canvas = document.createElement('canvas');
function onload () {
canvas.width = img.width;
canvas.height = img.height;
var context = canvas.getContext('2d');
context.drawImage(img, 0, 0);
var res = canvas.toDataURL('image/png');
done(res);
}
var svgBody = ssvg();
var svgdata = 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svgBody)));
img.src = svgdata;
if (img.complete) {
onload();
} else {
img.onload = onload;
}
}
function savePNG () {
var a;
function chooseFile(name) {
var chooser = document.querySelector(name);
chooser.addEventListener('change', function() {
var fs = require('fs');
var filename = this.value;
if (!filename) { return; }
pngdata(function (data) {
data = data.replace(/^data:image\/\w+;base64,/, '');
var buf = new Buffer(data, 'base64');
fs.writeFile(filename, buf, function(err) {
if (err) {
console.log('error');
}
});
this.value = '';
});
}, false);
chooser.click();
}
if (typeof process === 'object') { // nodewebkit detection
chooseFile('#fileDialogPNG');
} else {
var cfse = window.chooseFileSystemEntries;
if (cfse !== undefined) {
// PWA: https://web.dev/native-file-system/#write-file
cfse({
type: 'saveFile',
accepts: [{
description: 'PNG file',
extensions: ['png'],
mimeType: ['image/png']
}]
}).then(function (fh) {
fh.createWriter().then(function (writer) {
pngdata(function (uri) {
writer.write(0, convertDataURIToBinary(uri))
.then(function () {
writer.close();
});
});
});
});
} else {
a = document.createElement('a');
pngdata(function (res) {
a.href = res;
a.download = 'wavedrom.png';
var theEvent = document.createEvent('MouseEvent');
theEvent.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
a.dispatchEvent(theEvent);
// a.click();
});
}
}
}
WaveDrom.editorInit = editorInit;
WaveDrom.menuOpen = menuOpen;
WaveDrom.loadJSON = loadJSON;
WaveDrom.saveJSON = saveJSON;
WaveDrom.saveSVG = saveSVG;
WaveDrom.savePNG = savePNG;
WaveDrom.editorState = editorState;
WaveDrom.setFullURL = setFullURL;
WaveDrom.gotoWaveDromGuide = gotoWaveDromGuide;
WaveDrom.gotoWaveDromHome = gotoWaveDromHome;
})();
/* eslint-env node, browser */
/* global WaveDrom */
/* eslint no-console: 1 */
|
var helpers = require('../../helpers');
module.exports = function(context, stepInfo) {
var img = context.processedImage;
helpers.dimension.resolveStep(img, stepInfo);
if (stepInfo.width < 1 || stepInfo.height < 1) {
// don't permit <= 0 inputs
throw new Error('resize width or height cannot be <= 0');
}
if (isNaN(stepInfo.width) && isNaN(stepInfo.height)) {
throw new Error('resize width or height required');
}
var aspectX = helpers.dimension.getXAspect(img);
var aspectY = helpers.dimension.getYAspect(img);
if (isNaN(stepInfo.width)) {
stepInfo.width = Math.round(stepInfo.height * aspectX);
}
if (isNaN(stepInfo.height)) {
stepInfo.height = Math.round(stepInfo.width * aspectY);
}
if (context.options.maxSize) {
// request should never exceed permitted output size
if (stepInfo.width > context.options.maxSize.width) {
stepInfo.width = context.options.maxSize.width;
}
if (stepInfo.height > context.options.maxSize.height) {
stepInfo.height = context.options.maxSize.height;
}
}
var ignoreAspect = stepInfo.ignoreAspect === 'true';
if (!ignoreAspect) {
var w = stepInfo.width,
h = stepInfo.height;
if (stepInfo.min !== undefined) {
// use min if specified
// apply aspect
h = Math.round(stepInfo.width * aspectY);
if (h < stepInfo.height) {
// if height less than minimum, set to min
h = stepInfo.height;
w = Math.ceil(stepInfo.height * aspectX);
}
if (w < stepInfo.width) {
// if width less than minimum, set to min
w = stepInfo.width;
h = Math.ceil(stepInfo.width * aspectY);
}
} else {
// use max otherwise
// apply aspect
h = Math.round(w * aspectY);
if (h > stepInfo.height) {
// if height more than maximum, reduce to max
h = stepInfo.height;
w = Math.floor(h * aspectX);
}
if (w > stepInfo.width) {
// if width more than maximum, reduce to max
w = stepInfo.width;
h = Math.floor(w * aspectY);
}
}
stepInfo.width = w;
stepInfo.height = h;
}
if (stepInfo.canGrow !== 'true') {
if (stepInfo.width > img.info.width) {
stepInfo.width = img.info.width;
if (!ignoreAspect) {
stepInfo.height = Math.ceil(stepInfo.width * aspectY);
}
}
if (stepInfo.height > img.info.height) {
stepInfo.height = img.info.height;
if (!ignoreAspect) {
stepInfo.width = Math.ceil(stepInfo.height * aspectX);
}
}
}
// track new dimensions for followup operations
img.info.width = stepInfo.width;
img.info.height = stepInfo.height;
var rgba = helpers.rgba.getRGBA(stepInfo);
context.sharp
.resize(stepInfo.width, stepInfo.height, {
interpolator: stepInfo.interpolator || 'bicubic',
fit: stepInfo.fit || 'fill', // we'll handle aspect ourselves (by default) to avoid having to recompute dimensions
position: stepInfo.position || 'centre',
background: rgba
});
};
|
define([
'aux/ajax'
], function (Ajax) {
/**
* A module to perform several AJAX calls
* @exports multi-ajax
*/
function MultiAjax () {
this._ajax = new Ajax();
}
/**
* Return a function that can be used as a callback for the Json loading requests.
*
* @memberOf module:multi-ajax
* @protected
*
* @param {string[]} urls Location of json files
* @param {integer} index Index of the url being processed
* @param {string} method Defaults to get
* @param {function} onload Success callback
* @param {function} onerror Error callback
* @param {Object[]} responses Partial response, array containing all the responses collected by previous requests
*/
MultiAjax.prototype._loadJsonCallbackGenerator = function (urls, index, method, onload, onerror, responses) {
var $this = this;
return function (response) {
responses.push(response);
if (index < urls.length - 1) {
$this._loadJson.call($this, urls, index + 1, method, onload, onerror, responses);
} else {
onload(responses);
}
};
};
/**
* Request and parse a single Json object, using a generated callback to collect the response.
*
* @memberOf module:multi-ajax
* @protected
*
* @param {string[]} urls Location of json files
* @param {integer} index Index of the url being processed
* @param {string} method Defaults to get
* @param {function} onload Success callback
* @param {function} onerror Error callback
* @param {Object[]} responses Partial response, array containing all the responses collected by previous requests
*/
MultiAjax.prototype._loadJson = function (urls, index, method, onload, onerror, responses) {
this._ajax.loadJson(
urls[index],
method,
this._loadJsonCallbackGenerator.call(this, urls, index, method, onload, onerror, responses),
onerror
);
};
/**
* Execute several ajax requests parsing the responses into a list of JSON objects.
*
* @memberOf module:multi-ajax
* @public
*
* @param {string[]} urls Location of json files
* @param {string} method Defaults to get
* @param {function} onload Success callback
* @param {function} onerror Error callback
*/
MultiAjax.prototype.loadJson = function (urls, method, onload, onerror) {
this._loadJson.call(this, urls, 0, method, onload, onerror, []);
};
return MultiAjax;
});
|
const debug = require('debug')('app:webpack:loaders');
const env = require('../base-config/environment');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const isDev = env.isDev;
const isProd = env.isProd;
module.exports = () => {
const rules = [{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: [{ loader: 'babel-loader' }]
}, {
test: /\.json$/,
use: [{ loader: 'json-loader' }]
},{
test: /\.(css)$/,
use: [
{
loader: 'style-loader'
}, {
loader: 'css-loader',
options: {
minimize: isProd,
sourceMap: !isProd,
modules: true
}
}, 'postcss-loader'
]
}, {
test: /\.(less)$/,
use: [
{
loader: 'style-loader'
}, {
loader: 'css-loader',
options: {
minimize: isProd,
sourceMap: !isProd
}
}, {
loader: 'postcss-loader'
}, {
loader: 'less-loader',
options: {
sourceMap: !isProd
}
}
]
}, {
test: /\.(png|jpg)$/,
use: [{
loader: 'url-loader',
options: {
limit: 8192
}
}]
}];
if (!isDev) {
debug('Apply ExtractTextPlugin to CSS loaders.');
rules.filter(rule => rule.use && rule.use.find(loaderObj => /css/.test(loaderObj.loader.split('?')[0])))
.forEach((rule) => {
const first = rule.use[0];
const rest = rule.use.slice(1);
rule.loader = ExtractTextPlugin.extract({ fallbackLoader: first, loader: rest });
delete rule.use;
});
}
return rules;
};
|
import Enum from '../../lib/Enum';
export default new Enum([
'init',
'initSuccess',
'reset',
'resetSuccess',
], 'dateTimeFormat');
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }();
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _IconBase = require('./../components/IconBase/IconBase');
var _IconBase2 = _interopRequireDefault(_IconBase);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
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; }
var SocialWordpress = function (_React$Component) {
_inherits(SocialWordpress, _React$Component);
function SocialWordpress() {
_classCallCheck(this, SocialWordpress);
return _possibleConstructorReturn(this, Object.getPrototypeOf(SocialWordpress).apply(this, arguments));
}
_createClass(SocialWordpress, [{
key: 'render',
value: function render() {
if (this.props.bare) {
return _react2.default.createElement(
'g',
null,
_react2.default.createElement(
'g',
null,
_react2.default.createElement('path', { d: 'M259,271.3L226.2,367h-0.1l-25.4,73.1c1.8,0.5,3.5,0.9,5.3,1.4c0.1,0,0.2,0,0.3,0c15.8,4.2,32.4,6.5,49.5,6.5 c8.5,0,16.8-0.5,24.9-1.8c11.2-1.4,22-3.8,32.5-7.1c0,0,0,0,0,0c2.6-0.8,5.2-1.7,7.8-2.6c-2.8-6-8.8-19.3-9.1-19.9L259,271.3z' }),
_react2.default.createElement('path', { d: 'M80.8,180.5c-10,22.6-16.8,50.4-16.8,75.5c0,6.3,0.3,12.6,0.9,18.8c6.9,71.2,52.9,131,116.1,157.9c2.6,1.1,5.3,2.2,8,3.2 L96,180.6C88,180.3,86.5,180.8,80.8,180.5z' }),
_react2.default.createElement('path', { d: 'M430.2,175.4c-4.3-9.3-9.4-18.2-15.1-26.6c-1.6-2.4-3.4-4.8-5.1-7.2c-21.5-28.8-50.8-51.4-84.9-64.6 C303.7,68.6,280.3,64,255.9,64c-60.3,0-114.2,28-149.4,71.7c-6.5,8-12.3,16.6-17.5,25.6c14.2,0.1,31.8,0.1,33.8,0.1 c18.1,0,46-2.2,46-2.2c9.4-0.6,10.4,13.1,1.1,14.2c0,0-9.4,1.1-19.8,1.6l62.9,187l37.8-113.3L224,175.1c-9.4-0.5-18.1-1.6-18.1-1.6 c-9.4-0.5-8.2-14.8,1-14.2c0,0,28.5,2.2,45.5,2.2c18.1,0,46-2.2,46-2.2c9.3-0.6,10.5,13.1,1.1,14.2c0,0-9.3,1.1-19.7,1.6 l62.3,185.6l17.3-57.6c8.7-22.4,13.1-40.9,13.1-55.7c0-21.3-7.7-36.1-14.3-47.6c-8.7-14.3-16.9-26.3-16.9-40.4 c0-15.9,12-30.7,29-30.7c0.7,0,1.5,0,2.2,0c26.2-0.7,34.8,25.3,35.9,43c0,0,0,0.4,0,0.6c0.4,7.2,0.1,12.5,0.1,18.8 c0,17.4-3.3,37.1-13.1,61.8l-39,112.8l-22.3,65.7c1.8-0.8,3.5-1.6,5.3-2.5c56.7-27.4,98-82,106.7-146.7c1.3-8.5,1.9-17.2,1.9-26 C448,227.3,441.6,199.9,430.2,175.4z' })
)
);
}return _react2.default.createElement(
_IconBase2.default,
null,
_react2.default.createElement(
'g',
null,
_react2.default.createElement('path', { d: 'M259,271.3L226.2,367h-0.1l-25.4,73.1c1.8,0.5,3.5,0.9,5.3,1.4c0.1,0,0.2,0,0.3,0c15.8,4.2,32.4,6.5,49.5,6.5 c8.5,0,16.8-0.5,24.9-1.8c11.2-1.4,22-3.8,32.5-7.1c0,0,0,0,0,0c2.6-0.8,5.2-1.7,7.8-2.6c-2.8-6-8.8-19.3-9.1-19.9L259,271.3z' }),
_react2.default.createElement('path', { d: 'M80.8,180.5c-10,22.6-16.8,50.4-16.8,75.5c0,6.3,0.3,12.6,0.9,18.8c6.9,71.2,52.9,131,116.1,157.9c2.6,1.1,5.3,2.2,8,3.2 L96,180.6C88,180.3,86.5,180.8,80.8,180.5z' }),
_react2.default.createElement('path', { d: 'M430.2,175.4c-4.3-9.3-9.4-18.2-15.1-26.6c-1.6-2.4-3.4-4.8-5.1-7.2c-21.5-28.8-50.8-51.4-84.9-64.6 C303.7,68.6,280.3,64,255.9,64c-60.3,0-114.2,28-149.4,71.7c-6.5,8-12.3,16.6-17.5,25.6c14.2,0.1,31.8,0.1,33.8,0.1 c18.1,0,46-2.2,46-2.2c9.4-0.6,10.4,13.1,1.1,14.2c0,0-9.4,1.1-19.8,1.6l62.9,187l37.8-113.3L224,175.1c-9.4-0.5-18.1-1.6-18.1-1.6 c-9.4-0.5-8.2-14.8,1-14.2c0,0,28.5,2.2,45.5,2.2c18.1,0,46-2.2,46-2.2c9.3-0.6,10.5,13.1,1.1,14.2c0,0-9.3,1.1-19.7,1.6 l62.3,185.6l17.3-57.6c8.7-22.4,13.1-40.9,13.1-55.7c0-21.3-7.7-36.1-14.3-47.6c-8.7-14.3-16.9-26.3-16.9-40.4 c0-15.9,12-30.7,29-30.7c0.7,0,1.5,0,2.2,0c26.2-0.7,34.8,25.3,35.9,43c0,0,0,0.4,0,0.6c0.4,7.2,0.1,12.5,0.1,18.8 c0,17.4-3.3,37.1-13.1,61.8l-39,112.8l-22.3,65.7c1.8-0.8,3.5-1.6,5.3-2.5c56.7-27.4,98-82,106.7-146.7c1.3-8.5,1.9-17.2,1.9-26 C448,227.3,441.6,199.9,430.2,175.4z' })
)
);
}
}]);
return SocialWordpress;
}(_react2.default.Component);
exports.default = SocialWordpress;
;SocialWordpress.defaultProps = { bare: false }; |
import path from 'path';
import fs from 'fs';
import test from 'ava';
import proxyquire from 'proxyquire';
import hasha from 'hasha';
import makeDir from 'make-dir';
import sinon from 'sinon';
import rimraf from 'rimraf';
// Istanbul (used by nyc to instrument the code) won't load when mock-fs is
// installed. Require the index.js here so it can be instrumented.
import '.'; // eslint-disable-line import/no-unassigned-import
const PKG_HASH = '101044df7719e0cfa10cbf1ad7b1c63e';
const mainCacheDir = path.join(__dirname, '.test-cache');
let currentDir = 0;
function createCacheDir(id) {
return path.join(mainCacheDir, `test-${id}`);
}
function withMockedFs() {
const makeDir = proxyquire('make-dir', {});
makeDir.sync = sinon.spy(makeDir.sync);
const packageHash = {
sync() {
return PKG_HASH;
}
};
const cachingTransform = proxyquire('.', {
'make-dir': makeDir,
'package-hash': packageHash
});
cachingTransform.makeDir = makeDir;
return cachingTransform;
}
function wrap(opts, noCacheDirOpt) {
if (typeof opts === 'function') {
opts = {transform: opts};
}
if (!noCacheDirOpt && !opts.cacheDir) {
opts.cacheDir = createCacheDir(currentDir);
currentDir++;
}
if (opts.cacheDir) {
rimraf.sync(opts.cacheDir);
}
const cachingTransform = withMockedFs();
const wrapped = cachingTransform(opts);
wrapped.makeDir = cachingTransform.makeDir;
wrapped.cacheDir = opts.cacheDir;
return wrapped;
}
function append(val) {
return input => `${input} ${val}`;
}
test.before(() => {
rimraf.sync(mainCacheDir);
});
test.after.always(() => {
rimraf.sync(mainCacheDir);
});
test('saves transform result to cache directory', t => {
const transform = wrap(append('bar'));
t.is(transform('foo'), 'foo bar');
t.is(transform('FOO'), 'FOO bar');
// Manual sha256 sum of '<PKG_HASH>foo'
const filename1 = path.join(transform.cacheDir, '1dc458245419414bbdd40b53bb266691bacc8abcd21ff3440e0f4bc5a04c77d2');
const filename2 = path.join(transform.cacheDir, 'ccf3ca00a6fb76fa7ca8101e5a697ab1bf3544b762f64ea1e6c790f8095317d5');
t.is(fs.readFileSync(filename1, 'utf8'), 'foo bar');
t.is(fs.readFileSync(filename2, 'utf8'), 'FOO bar');
});
test('skips transform if cache file exists', t => {
const transform = wrap(() => t.fail());
transform.makeDir.sync(transform.cacheDir);
fs.writeFileSync(path.join(transform.cacheDir, '1dc458245419414bbdd40b53bb266691bacc8abcd21ff3440e0f4bc5a04c77d2'), 'foo bar');
t.is(transform('foo'), 'foo bar');
});
test('able to specify alternate extension', t => {
const transform = wrap({
transform: append('bar'),
ext: '.js'
});
t.is(transform('foo'), 'foo bar');
const filename = path.join(transform.cacheDir, '1dc458245419414bbdd40b53bb266691bacc8abcd21ff3440e0f4bc5a04c77d2.js');
t.is(fs.readFileSync(filename, 'utf8'), 'foo bar');
});
test('makeDir is only called once', t => {
const transform = wrap({
transform: append('bar')
});
t.is(transform.makeDir.sync.callCount, 0);
t.is(transform('foo'), 'foo bar');
t.is(transform.makeDir.sync.callCount, 1);
t.is(transform('bar'), 'bar bar');
t.is(transform.makeDir.sync.callCount, 1);
});
test('makeDir is only called once, with factory', t => {
const transform = wrap({
factory: () => append('bar')
});
t.is(transform.makeDir.sync.callCount, 0);
t.is(transform('foo'), 'foo bar');
t.is(transform.makeDir.sync.callCount, 1);
t.is(transform('bar'), 'bar bar');
t.is(transform.makeDir.sync.callCount, 1);
});
test('makeDir is never called if `createCacheDir === false`', t => {
const transform = wrap(
{
transform: append('bar'),
createCacheDir: false
}
);
t.is(transform.makeDir.sync.callCount, 0);
const error = t.throws(() => transform('foo'), Error);
t.is(error.code, 'ENOENT');
t.is(transform.makeDir.sync.callCount, 0);
makeDir.sync(transform.cacheDir);
t.is(transform('foo'), 'foo bar');
t.is(transform.makeDir.sync.callCount, 0);
});
test('makeDir is never called if `createCacheDir === false`, with factory', t => {
const transform = wrap(
{
factory: () => append('bar'),
createCacheDir: false
}
);
t.is(transform.makeDir.sync.callCount, 0);
const error = t.throws(() => transform('foo'), Error);
t.is(error.code, 'ENOENT');
t.is(transform.makeDir.sync.callCount, 0);
makeDir.sync(transform.cacheDir);
t.is(transform('foo'), 'foo bar');
t.is(transform.makeDir.sync.callCount, 0);
});
test('additional opts are passed to transform', t => {
const transform = wrap((input, additionalOpts) => {
t.is(input, 'foo');
t.deepEqual(additionalOpts, {bar: 'baz'});
return 'FOO!';
});
t.is(transform('foo', {bar: 'baz'}), 'FOO!');
});
test('filename is generated from the sha256 hash of the package hash, the input content and the salt', t => {
const transform = wrap(
{
transform: append('bar'),
salt: 'baz'
}
);
transform('FOO');
const filename = path.join(transform.cacheDir, hasha([PKG_HASH, 'FOO', 'baz'], {algorithm: 'sha256'}));
t.is(fs.readFileSync(filename, 'utf8'), 'FOO bar');
});
test('factory is only called once', t => {
const factory = sinon.spy(() => append('foo'));
const transform = wrap({factory});
t.is(factory.callCount, 0);
t.is(transform('bar'), 'bar foo');
t.is(factory.callCount, 1);
t.deepEqual(factory.firstCall.args, [transform.cacheDir]);
t.is(transform('baz'), 'baz foo');
t.is(factory.callCount, 1);
});
test('checks for sensible options', t => {
const transform = append('bar');
const factory = () => transform;
const cacheDir = '/someDir';
t.throws(() => wrap({factory, transform, cacheDir}));
t.throws(() => wrap({cacheDir}, true));
t.throws(() => wrap({factory}, true));
t.throws(() => wrap({transform}, true));
t.notThrows(() => {
wrap({factory});
wrap({transform});
});
});
test('cacheDir is only required if caching is enabled', t => {
t.notThrows(() => {
wrap({transform: append('bar'), disableCache: true}, true);
});
t.throws(() => {
wrap({transform: append('bar')}, true);
});
});
test('shouldTransform can bypass transform', t => {
const transform = wrap({
shouldTransform: (code, file) => {
t.is(code, 'baz');
t.is(file, '/baz.js');
return false;
},
transform: () => t.fail()
});
t.is(transform('baz', '/baz.js'), 'baz');
});
test('shouldTransform can enable transform', t => {
const transform = wrap({
shouldTransform: (code, file) => {
t.is(code, 'foo');
t.is(file, '/foo.js');
return true;
},
transform: append('bar')
});
t.is(transform('foo', '/foo.js'), 'foo bar');
});
test('disableCache:true, disables cache - transform is called multiple times', t => {
const transformSpy = sinon.spy(append('bar'));
const transform = wrap({
disableCache: true,
transform: transformSpy
});
t.is(transformSpy.callCount, 0);
t.is(transform('foo'), 'foo bar');
t.is(transformSpy.callCount, 1);
t.is(transform('foo'), 'foo bar');
t.is(transformSpy.callCount, 2);
});
test('disableCache:default, enables cache - transform is called once per hashed input', t => {
const transformSpy = sinon.spy(append('bar'));
const transform = wrap({transform: transformSpy});
t.is(transformSpy.callCount, 0);
t.is(transform('foo'), 'foo bar');
t.is(transformSpy.callCount, 1);
t.is(transform('foo'), 'foo bar');
t.is(transformSpy.callCount, 1);
});
test('can provide additional input to the hash function', t => {
t.plan(4);
const hashData = function (code, filename) {
t.is(code, 'foo');
t.is(filename, '/foo.js');
return 'extra-foo-data';
};
const transform = wrap({
salt: 'this is salt',
transform: append('bar'),
hashData
});
const filename = path.join(transform.cacheDir, hasha([PKG_HASH, 'foo', 'this is salt', 'extra-foo-data'], {algorithm: 'sha256'}));
t.is(transform('foo', '/foo.js'), 'foo bar');
t.is(fs.readFileSync(filename, 'utf8'), 'foo bar');
});
test('can provide an array of additional input to the hash function', t => {
t.plan(4);
const hashData = function (code, filename) {
t.is(code, 'foo');
t.is(filename, '/foo.js');
return ['extra-foo-data', 'even-more-data'];
};
const transform = wrap({
salt: 'this is salt',
transform: append('bar'),
hashData
});
const filename = path.join(transform.cacheDir, hasha([PKG_HASH, 'foo', 'this is salt', 'extra-foo-data', 'even-more-data'], {algorithm: 'sha256'}));
t.is(transform('foo', '/foo.js'), 'foo bar');
t.is(fs.readFileSync(filename, 'utf8'), 'foo bar');
});
test('onHash callback fires after hashing', t => {
t.plan(3);
const onHash = function (code, filename, hash) {
t.is(code, 'foo');
t.is(filename, '/foo.js');
t.is(hash, hasha([PKG_HASH, code, 'this is salt'], {algorithm: 'sha256'}));
};
const transform = wrap({
salt: 'this is salt',
transform: append('bar'),
onHash
});
transform('foo', '/foo.js');
});
test('custom encoding changes value loaded from disk', t => {
const transform = wrap({
transform: () => t.fail(),
encoding: 'hex'
});
makeDir.sync(transform.cacheDir);
fs.writeFileSync(path.join(transform.cacheDir, hasha([PKG_HASH, 'foo'], {algorithm: 'sha256'})), 'foo bar');
t.is(transform('foo'), Buffer.from('foo bar').toString('hex'));
});
test('custom encoding is respected when writing to disk', t => {
const transform = wrap({
transform: code => code,
encoding: 'utf16le'
});
makeDir.sync(transform.cacheDir);
t.is(transform('foobar'), 'foobar');
fs.readFileSync(path.join(transform.cacheDir, hasha([PKG_HASH, 'foobar'], {algorithm: 'sha256'})), 'binary');
});
test('custom encoding changes the value stored to disk', t => {
const transform = wrap({
transform: code => Buffer.from(code + ' bar').toString('hex'),
encoding: 'hex'
});
t.is(transform('foo'), Buffer.from('foo bar').toString('hex'));
const filename = path.join(transform.cacheDir, hasha([PKG_HASH, 'foo'], {algorithm: 'sha256'}));
t.is(fs.readFileSync(filename, 'utf8'), 'foo bar');
});
test('buffer encoding returns a buffer', t => {
const transform = wrap({
transform: () => t.fail(),
encoding: 'buffer'
});
makeDir.sync(transform.cacheDir);
fs.writeFileSync(path.join(transform.cacheDir, hasha([PKG_HASH, 'foo'], {algorithm: 'sha256'})), 'foo bar');
const result = transform('foo');
t.true(Buffer.isBuffer(result));
t.is(result.toString(), 'foo bar');
});
test('salt can be a buffer', t => {
const transform = wrap({
transform: () => t.fail(),
salt: Buffer.from('some-salt')
});
makeDir.sync(transform.cacheDir);
const filename = path.join(transform.cacheDir, hasha([PKG_HASH, 'foo', Buffer.from('some-salt', 'utf8')], {algorithm: 'sha256'}));
fs.writeFileSync(filename, 'foo bar');
t.is(transform('foo'), 'foo bar');
});
test('filenamePrefix uses metadata to prefix filename', t => {
const transform = wrap({
transform: () => t.fail(),
filenamePrefix: metadata => path.parse(metadata.filename || '').name + '-'
});
makeDir.sync(transform.cacheDir);
const filename = path.join(transform.cacheDir, 'source-' + hasha([PKG_HASH, 'foo'], {algorithm: 'sha256'}));
fs.writeFileSync(filename, 'foo bar');
t.is(transform('foo', {filename: path.join(__dirname, 'source.js')}), 'foo bar');
});
|
import assertString from './util/assertString';
/* Based on https://tools.ietf.org/html/rfc3339#section-5.6 */
const dateFullYear = /[0-9]{4}/;
const dateMonth = /(0[1-9]|1[0-2])/;
const dateMDay = /([12]\d|0[1-9]|3[01])/;
const timeHour = /([01][0-9]|2[0-3])/;
const timeMinute = /[0-5][0-9]/;
const timeSecond = /([0-5][0-9]|60)/;
const timeSecFrac = /(\.[0-9]+)?/;
const timeNumOffset = new RegExp(`[-+]${timeHour.source}:${timeMinute.source}`);
const timeOffset = new RegExp(`([zZ]|${timeNumOffset.source})`);
const partialTime = new RegExp(`${timeHour.source}:${timeMinute.source}:${timeSecond.source}${timeSecFrac.source}`);
const fullDate = new RegExp(`${dateFullYear.source}-${dateMonth.source}-${dateMDay.source}`);
const fullTime = new RegExp(`${partialTime.source}${timeOffset.source}`);
const rfc3339 = new RegExp(`${fullDate.source}[ tT]${fullTime.source}`);
export default function isRFC3339(str) {
assertString(str);
return rfc3339.test(str);
}
|
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var bodyParser = require('body-parser');
var multer = require('multer');
var mongoose = require('mongoose');
var MongoStore = require('connect-mongo')(session);
var app = express();
var paginate = require('express-paginate');
app.use(paginate.middleware(15, 100));
var config = require('./config.json');
var passport = require('passport');
var db = mongoose.connect(config.dburl,function(err){
if(err)
console.log(err);
});
db.connections[0].on('error', console.error.bind(console, 'connect error: '));
db.connections[0].once('open', function(){
console.log('mongodb connected');
});
// view engine setup
app.set('views', path.join(__dirname, 'app/views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
app.use(favicon(__dirname + '/app/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(multer({ dest: './app/uploads/'}));
app.use(cookieParser());
app.use(session({
name: 'SESSIONID',
secret: 'mc',
cookie: {
//maxAge: 10000
},
store: new MongoStore({
mongooseConnection: mongoose.connection,
ttl: 60*60 //1小时。单位:秒
}
),
resave: false,
saveUninitialized: false
}));
app.use(express.static(path.join(__dirname, 'app/public')));
//加载passport功能
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser(function (user, done) {
done(null, user);
});
passport.deserializeUser(function (user, done) {
done(null, user);
});
//加载路由
var routes = require('./app/routes/routes.js')(app);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('您访问的网页好像被苦力怕吃掉了 :(');
err.status = 404;
next(err);
});
//设置生产变量
if(config.env && config.env == 'production'){
app.set('env','production');
}
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.locals.pretty = true;
console.log('debug mode');
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
console.log(err);
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
|
'use strict';
module.exports = {
db: 'mongodb://localhost/uCtrl'
};
|
import React from "react"
import Link from "gatsby-link"
import Layout from "../layouts/layout"
import Head from "../components/head"
const AboutMe = () => {
return(
<Layout>
<Head title="About Me" />
<h2>Ismael Melendez</h2>
<br/>
<p>I am a software and web developer building technology to connect and inform people, so they are more engaged in democracy.
Let's create. <a href="mailto:[email protected]">Send email.</a> </p>
<p> Languages and Technologies: C++, Python, Javascript, SQL<br/> React, Django, Axios, Git, LAMP, Jamstack</p>
<p>Skills: Web Development | Social Media Marketing | Writing | Editing | Nonprofit Organizations | Public Speaking | Event Planning | Lobbying | Content creator and curator </p>
</Layout>
)
}
export default AboutMe |
"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: "M5 6h14v2H5z",
opacity: ".3"
}, "0"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M21 12V6c0-1.1-.9-2-2-2h-1V2h-2v2H8V2H6v2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h7v-2H5V10h14v2h2zm-2-4H5V6h14v2zm-3.36 12c.43 1.45 1.77 2.5 3.36 2.5 1.93 0 3.5-1.57 3.5-3.5s-1.57-3.5-3.5-3.5c-.95 0-1.82.38-2.45 1H18V18h-4v-4h1.5v1.43c.9-.88 2.14-1.43 3.5-1.43 2.76 0 5 2.24 5 5s-2.24 5-5 5c-2.42 0-4.44-1.72-4.9-4h1.54z"
}, "1")], 'EventRepeatTwoTone');
exports.default = _default; |
// #1
// function evenNumbers(array, number) {
// const result = [];
// for (let i = 0; i <= array.length; i++) {
// if (array[i] % 2 == 0) result.push(array[i]);
// }
// return result.splice(result.length - number, number);
// }
// #2
// function evenNumbers(array, number) {
// const result = [];
// array.map((x) => {
// if (x % 2 === 0) {
// result.push(x);
// }
// });
// return result.slice(-number);
// }
// #3
// function evenNumbers(array, number) {
// return array.filter((x) => !(x % 2)).splice(-number);
// }
// #4
const evenNumbers = (array, number) =>
array.filter((x) => !(x % 2)).splice(-number);
|
/**
* @overview The based service function.
* @author Chao Wang (hit9)
* @copyright 2015 Eleme, Inc. All rights reserved.
*/
'use strict';
const events = require('events');
const fivebeans = require('fivebeans');
const net = require('net');
const ssdb = require('ssdb');
const Sequelize = require('sequelize');
const config = require('./config');
const log = require('./log');
const protocol = require('./protocol');
const util = require('./util');
/**
* Connection buffer parser.
*/
function ConnBufferParser() {
this.unfinished = new Buffer('');
}
/**
* Parse buffer to string chunks.
*
* @param {Buffer} buf
* @return {Array}
*/
ConnBufferParser.prototype.parse = function(buf) {
var result;
// pick up the unfinished buffer last time
buf = Buffer.concat([this.unfinished, buf]);
result = protocol.decode(buf);
this.unfinished = result[1];
return result[0];
};
/**
* Base service class.
*/
function Service() {
events.EventEmitter.call(this);
}
util.inherits(Service, events.EventEmitter);
/**
* Create a socket tcp server (using bell protocol).
*
* @param {Number} port
* @param {Function} cb // function(datapoints)
* @return {Service} // this
*/
Service.prototype.createSocketServer = function(port, cb) {
this.sock = net.createServer(function(conn) {
var fd = conn._handle.fd;
log.info("new connection established (fd %d)", fd);
if (!conn._bufferParser) {
conn._bufferParser = new ConnBufferParser();
}
//------------------ conn on data -----------------------
conn.on('data', function(buf) {
var datapoints;
try {
datapoints = conn._bufferParser.parse(buf);
} catch (e) {
log.warn("invalid input: %s", buf.slice(0, 45));
return;
}
cb(datapoints);
});
//------------------ conn on close -----------------------
conn.on('close', function() {
delete conn._bufferParser;
log.info("client disconnected (fd %d)", fd);
});
})
//------------------ server on error -----------------------
.on('error', function(err) {
log.error('socket error: %s', err);
})
//-------------------- bind server -----------------------
.listen(port, function() {
log.info("listening on port %d..", port);
});
return this;
};
/**
* Create beanstalk client and patch it.
*/
Service.prototype.createBeansClient = function() {
var host = config.beanstalkd.host;
var port = config.beanstalkd.port;
this.beans = new fivebeans.client(host, port);
util.patchBeansClient(this.beans);
return this;
};
/**
* Connect to beanstalkd (yield blocking).
*
* @param {String} action // 'use'/'watch'
*/
Service.prototype.connectBeans = function *(action) {
var self = this,
beans = this.beans,
tube = config.beanstalkd.tube;
action = action || 'use';
beans.on('connect', function() {
beans[action](tube, function(err) {
if (err)
throw err;
log.info('beanstalkd connected, %s tube %s', action, tube);
self.emit('beans connected');
});
}).connect();
// yield until beans was connected
yield function(done) {
self.on('beans connected', done);
};
return this;
};
/**
* Create ssdb client pool.
*
* @return {Service} // this
*/
Service.prototype.createSsdbPool = function() {
var options = {
port: config.ssdb.port,
host: config.ssdb.host,
size: config.ssdb.size,
promisify: true
};
if (config.ssdb.auth && config.ssdb.auth.length > 0) {
options.auth = config.ssdb.auth;
}
this.ssdb = ssdb.createPool(options);
return this;
};
/**
* Create sequelize instance.
*
* @return {Service} // this
*/
Service.prototype.createSequelize = function() {
this.sequelize = new Sequelize(null, null, null, {
dialect: 'sqlite',
storage: config.sqlite.file,
logging: false,
});
return this;
};
module.exports = Service;
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends2 = require('babel-runtime/helpers/extends');
var _extends3 = _interopRequireDefault(_extends2);
var _classnames = require('classnames');
var _classnames2 = _interopRequireDefault(_classnames);
var _propTypes = require('prop-types');
var _propTypes2 = _interopRequireDefault(_propTypes);
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _lib = require('../../lib');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function StepDescription(props) {
var children = props.children,
className = props.className,
description = props.description;
var classes = (0, _classnames2.default)('description', className);
var rest = (0, _lib.getUnhandledProps)(StepDescription, props);
var ElementType = (0, _lib.getElementType)(StepDescription, props);
return _react2.default.createElement(
ElementType,
(0, _extends3.default)({}, rest, { className: classes }),
_lib.childrenUtils.isNil(children) ? description : children
);
}
StepDescription.handledProps = ['as', 'children', 'className', 'description'];
StepDescription._meta = {
name: 'StepDescription',
parent: 'Step',
type: _lib.META.TYPES.ELEMENT
};
StepDescription.propTypes = process.env.NODE_ENV !== "production" ? {
/** An element type to render as (string or function). */
as: _lib.customPropTypes.as,
/** Primary content. */
children: _propTypes2.default.node,
/** Additional classes. */
className: _propTypes2.default.string,
/** Shorthand for primary content. */
description: _lib.customPropTypes.contentShorthand
} : {};
exports.default = StepDescription; |
// Generated by CoffeeScript 1.10.0
(function() {
var UI_JS, VERSION, Weya, template;
VERSION = 9;
Weya = (require('weya')).Weya;
UI_JS = ['static', 'parser', 'reader', 'nodes', 'render'];
template = function() {
return this.html(function() {
this.head(function() {
this.meta({
charset: "utf-8"
});
this.title(this.$.title);
this.meta({
name: "viewport",
content: "width=device-width, initial-scale=1.0"
});
this.meta({
name: "apple-mobile-web-app-capable",
content: "yes"
});
this.link({
href: 'http://fonts.googleapis.com/css?family=Raleway:400,100,200,300,500,600,700,800,900',
rel: 'stylesheet',
type: 'text/css'
});
this.link({
href: "lib/skeleton/css/skeleton.css",
rel: "stylesheet"
});
this.link({
href: "lib/highlightjs/styles/default.css",
rel: "stylesheet"
});
this.link({
href: "css/style.css",
rel: "stylesheet"
});
this.link({
href: "blog.css",
rel: "stylesheet"
});
return this.script('(function(i,s,o,g,r,a,m){i[\'GoogleAnalyticsObject\']=r;i[r]=i[r]||function(){\n(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),\nm=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)\n})(window,document,\'script\',\'//www.google-analytics.com/analytics.js\',\'ga\');\n\nga(\'create\', \'UA-44255805-1\', \'auto\');\nga(\'send\', \'pageview\');');
});
return this.body(function() {
var file, i, len, ref, results;
this.div(".container.wallapatta-container", function() {
this.div(".header", function() {
this.h1(function() {
return this.a({
href: "index.html"
}, "VARUNA JAYASIRI");
});
return this.a(".button", {
href: "https://www.twitter.com/vpj"
}, "@vpj");
});
return this.div(".wallapatta", function() {
this.h1(".title", this.$.title);
this.h3(".date", "" + this.$.date);
return this.div(".row", function() {
this.div(".wallapatta-main.nine.columns", "###MAIN###");
this.div(".wallapatta-sidebar.three.columns", "###SIDEBAR###");
return this.div({
style: {
display: 'none'
}
}, "###CODE###");
});
});
});
this.script({
src: "lib/highlightjs/highlight.pack.js"
});
this.script({
src: "lib/weya/weya.js"
});
this.script({
src: "lib/weya/base.js"
});
this.script({
src: "lib/mod/mod.js"
});
ref = this.$.scripts;
results = [];
for (i = 0, len = ref.length; i < len; i++) {
file = ref[i];
results.push(this.script({
src: "js/" + file + ".js?v=" + VERSION
}));
}
return results;
});
});
};
exports.html = function(options) {
var html;
if (options == null) {
options = {};
}
if (options.scripts == null) {
options.scripts = UI_JS;
}
html = Weya.markup({
context: options
}, template);
html = html.replace('###MAIN###', options.main);
html = html.replace('###SIDEBAR###', options.sidebar);
html = html.replace('###CODE###', "<div class='wallapatta-code'>" + options.code + "</div>");
html = "<!DOCTYPE html>" + html;
return html;
};
}).call(this);
|
// additional template-script
require( ['jquery', 'underscore', 'backbone'], function( $, _, Backbone ) {'use strict';
var Template = Backbone.View.extend( {
render : function( ) {
return;
},
events : {},
initialize : function( ) {
_.bindAll( this, 'render' );
this.render( );
}
} );
var template = new Template;
} );
|
objective('Javascript', function() {
it('can write singular values')
// module.exports = 1
});
|
{
"type": "cbml",
"nodes": [
{
"type": "block",
"pos": 0,
"endpos": 101,
"value": "/*<header info=\"file\">*/\n/**\n * (*<replace encoding=\"base64\">2014-10-16</replace>*)\n */\n/*</header>*/",
"tag": "header",
"language": "c",
"attrs": {
"info": "file"
},
"line": 1,
"col": 1,
"nodes": [
{
"type": "text",
"pos": 24,
"endpos": 32,
"value": "\n/**\n * ",
"line": 1,
"col": 25
},
{
"type": "block",
"pos": 32,
"endpos": 83,
"value": "(*<replace encoding=\"base64\">2014-10-16</replace>*)",
"comment": true,
"tag": "replace",
"language": "pascal",
"attrs": {
"encoding": "base64"
},
"line": 3,
"col": 4,
"nodes": [
{
"type": "text",
"pos": 61,
"endpos": 71,
"value": "2014-10-16",
"line": 3,
"col": 33
}
],
"content": "2014-10-16",
"prefix": "(*<replace encoding=\"base64\">",
"suffix": "</replace>*)"
},
{
"type": "text",
"pos": 83,
"endpos": 88,
"value": "\n */\n",
"line": 3,
"col": 55
}
],
"content": "\n/**\n * (*<replace encoding=\"base64\">2014-10-16</replace>*)\n */\n",
"prefix": "/*<header info=\"file\">*/",
"suffix": "/*</header>*/"
},
{
"type": "text",
"pos": 101,
"endpos": 102,
"value": "\n",
"line": 5,
"col": 14
}
],
"endpos": 102
} |
/**
* Created by Dmitry_Fisenko on 12/21/13.
*/
exports.get = function(req, res){
res.render('frontpage');
}; |
'use strict';
angular.module('ngTextcomplete', [])
/**
* Utils.
*/
.factory('utils', [
function() {
/**
* Exclusive execution control utility.
*/
function lock(func) {
var free, locked, queuedArgsToReplay;
free = function() {
locked = false;
};
return function() {
var args = toArray(arguments);
if (locked) {
queuedArgsToReplay = args;
return;
};
locked = true;
var that = this;
args.unshift(function replayOrFree() {
if (queuedArgsToReplay) {
var replayArgs = queuedArgsToReplay;
queuedArgsToReplay = undefined;
replayArgs.unshift(replayOrFree);
func.apply(that, replayArgs);
} else {
locked = false;
}
});
func.apply(this, args);
};
};
/**
* Convert arguments into a real array.
*/
function toArray(args) {
return Array.prototype.slice.call(args);
};
/**
* Get the styles of any element from property names.
*/
var getStyles = (function() {
var color;
color = $('<div></div>').css(['color']).color;
if (typeof color !== 'undefined') {
return function($el, properties) {
return $el.css(properties);
};
} else { // for jQuery 1.8 or below
return function($el, properties) {
var styles;
styles = {};
angular.forEach(properties, function(property, i) {
styles[property] = $el.css(property);
});
return styles;
};
}
})();
/**
* Memoize a search function.
*/
function memoize(func) {
var memo = {};
return function(term, callback) {
if (memo[term]) {
callback(memo[term]);
} else {
func.call(this, term, function(data) {
memo[term] = (memo[term] || []).concat(data);
callback.apply(null, arguments);
});
}
};
};
/**
* Determine if the array contains a given value.
*/
function include(array, value) {
var i, l;
if (array.indexOf) return array.indexOf(value) != -1;
for (i = 0, l = array.length; i < l; i++) {
if (array[i] === value) return true;
}
return false;
};
return {
lock: lock,
toArray: toArray,
getStyles: getStyles,
memoize: memoize,
include: include
}
}
])
/**
* Textarea manager class.
*/
.factory('Completer', ['ListView', 'utils',
function(ListView, utils) {
var html, css, $baseWrapper, $baseList, _id;
html = {
wrapper: '<div class="textcomplete-wrapper"></div>',
list: '<ul class="dropdown-menu"></ul>'
};
css = {
wrapper: {
position: 'relative'
},
list: {
position: 'absolute',
left: 0,
zIndex: '100',
display: 'none'
}
};
$baseWrapper = $(html.wrapper).css(css.wrapper);
$baseList = $(html.list).css(css.list);
_id = 0;
/**
* Completer manager class.
*/
function Completer($el, strategies) {
var focus;
this.el = $el.get(0); // textarea element
focus = this.el === document.activeElement;
// Cannot wrap $el at initialize method lazily due to Firefox's behavior.
this.$el = wrapElement($el); // Focus is lost
this.id = 'textComplete' + _id++;
this.strategies = [];
if (focus) {
this.initialize();
this.$el.focus();
} else {
this.$el.one('focus.textComplete', $.proxy(this.initialize, this));
}
};
/**
* Completer's public methods
*/
angular.extend(Completer.prototype, {
/**
* Prepare ListView and bind events.
*/
initialize: function() {
var $list, globalEvents;
$list = $baseList.clone();
this.listView = new ListView($list, this);
this.$el
.before($list)
.on({
'keyup.textComplete': $.proxy(this.onKeyup, this),
'keydown.textComplete': $.proxy(this.listView.onKeydown,
this.listView)
});
globalEvents = {};
globalEvents['click.' + this.id] = $.proxy(this.onClickDocument, this);
globalEvents['keyup.' + this.id] = $.proxy(this.onKeyupDocument, this);
$(document).on(globalEvents);
},
/**
* Register strategies to the completer.
*/
register: function (strategies) {
this.strategies = this.strategies.concat(strategies);
},
/**
* Show autocomplete list next to the caret.
*/
renderList: function(data) {
if (this.clearAtNext) {
this.listView.clear();
this.clearAtNext = false;
}
if (data.length) {
if (!this.listView.shown) {
this.listView
.setPosition(this.getCaretPosition())
.clear()
.activate();
this.listView.strategy = this.strategy;
}
data = data.slice(0, this.strategy.maxCount);
this.listView.render(data);
}
if (!this.listView.data.length && this.listView.shown) {
this.listView.deactivate();
}
},
searchCallbackFactory: function(free) {
var self = this;
return function(data, keep) {
self.renderList(data);
if (!keep) {
// This is the last callback for this search.
free();
self.clearAtNext = true;
}
};
},
/**
* Keyup event handler.
*/
onKeyup: function(e) {
var searchQuery, term;
if (this.skipSearch(e)) { return; }
searchQuery = this.extractSearchQuery(this.getTextFromHeadToCaret());
if (searchQuery.length) {
term = searchQuery[1];
if (this.term === term) return; // Ignore shift-key or something.
this.term = term;
this.search(searchQuery);
} else {
this.term = null;
this.listView.deactivate();
}
},
/**
* Suppress searching if it returns true.
*/
skipSearch: function (e) {
switch (e.keyCode) {
case 40:
case 38:
return true;
}
if (e.ctrlKey) switch (e.keyCode) {
case 78: // Ctrl-N
case 80: // Ctrl-P
return true;
}
},
onSelect: function(value) {
var pre, post, newSubStr;
pre = this.getTextFromHeadToCaret();
post = this.el.value.substring(this.el.selectionEnd);
newSubStr = this.strategy.replace(value);
if (angular.isArray(newSubStr)) {
post = newSubStr[1] + post;
newSubStr = newSubStr[0];
}
pre = pre.replace(this.strategy.match, newSubStr);
// if (this.el.contentEditable === 'true') {
// this.el.innerHTML = pre + post;
// this.placeCaretAtEnd();
// } else {
this.$el.val(pre + post);
$(this).trigger('change')
.trigger('textComplete:select', this.$el.val());
this.el.focus();
this.el.selectionStart = this.el.selectionEnd = pre.length;
// }
// this.$el.trigger('input').trigger('change').trigger('textComplete:select', value);
},
/**
* Global click event handler.
*/
onClickDocument: function(e) {
if (e.originalEvent && !e.originalEvent.keepTextCompleteDropdown) {
this.listView.deactivate();
}
},
/**
* Global keyup event handler.
*/
onKeyupDocument: function(e) {
if (this.listView.shown && e.keyCode === 27) { // ESC
this.listView.deactivate();
this.$el.focus();
}
},
/**
* Remove all event handlers and the wrapper element.
*/
destroy: function() {
var $wrapper;
this.$el.off('.textComplete');
$(document).off('.' + this.id);
if (this.listView) {
this.listView.destroy();
}
$wrapper = this.$el.parent();
$wrapper.after(this.$el).remove();
this.$el.data('textComplete', void 0);
this.$el = null;
},
// Helper methods
// ==============
/**
* Returns caret's relative coordinates from textarea's left top corner.
*/
getCaretPosition: function() {
var properties, css, $div, $span, position, dir, scrollbar;
dir = this.$el.attr('dir') || this.$el.css('direction');
properties = ['border-width', 'font-family', 'font-size', 'font-style',
'font-variant', 'font-weight', 'height', 'letter-spacing',
'word-spacing', 'line-height', 'text-decoration', 'text-align',
'width', 'padding-top', 'padding-right', 'padding-bottom',
'padding-left', 'margin-top', 'margin-right', 'margin-bottom',
'margin-left', 'border-style', 'box-sizing'
];
scrollbar = this.$el[0].scrollHeight > this.$el[0].offsetHeight;
css = $.extend({
position: 'absolute',
overflow: scrollbar ? 'scroll' : 'auto',
'white-space': 'pre-wrap',
top: 0,
left: -9999,
direction: dir
}, utils.getStyles(this.$el, properties));
$div = $('<div></div>').css(css).text(this.getTextFromHeadToCaret());
$span = $('<span></span>').text('.').appendTo($div);
this.$el.before($div);
position = $span.position();
position.top += $span.height() - this.$el.scrollTop();
if (dir == 'rtl') {
position.left -= this.listView.$el.width();
}
$div.remove();
return position;
},
getTextFromHeadToCaret: function() {
var text, selectionEnd, range;
selectionEnd = this.el.selectionEnd;
if (typeof selectionEnd === 'number') {
text = this.el.value.substring(0, selectionEnd);
} else if (document.selection) {
range = this.el.createTextRange();
range.moveStart('character', 0);
range.moveEnd('textedit');
text = range.text;
}
return text;
},
/**
* Parse the value of textarea and extract search query.
*/
extractSearchQuery: function(text) {
var i, l, strategy, match;
for (i = 0, l = this.strategies.length; i < l; i++) {
strategy = this.strategies[i];
match = text.match(strategy.match);
if (match) {
return [strategy, match[strategy.index]];
}
}
return [];
},
search: utils.lock(function(free, searchQuery) {
var term;
this.strategy = searchQuery[0];
term = searchQuery[1];
this.strategy.search(term, this.searchCallbackFactory(free));
})
});
/**
* Completer's private functions
*/
var wrapElement = function($el) {
return $el.wrap($baseWrapper.clone().css('display', $el.css('display')));
};
return Completer;
}
])
/**
* Dropdown menu manager class.
*/
.factory('ListView', ['utils',
function(utils) {
function ListView($el, completer) {
this.data = [];
this.$el = $el;
this.index = 0;
this.completer = completer;
this.$el.on('click.textComplete', 'li.textcomplete-item', $.proxy(this.onClick, this));
}
angular.extend(ListView.prototype, {
shown: false,
render: function(data) {
var html, i, l, index, val;
html = '';
for (i = 0, l = data.length; i < l; i++) {
val = data[i];
if (utils.include(this.data, val)) continue;
index = this.data.length;
this.data.push(val);
html += '<li class="textcomplete-item" data-index="' + index + '"><a>';
html += this.strategy.template(val);
html += '</a></li>';
if (this.data.length === this.strategy.maxCount) break;
}
this.$el.append(html)
if (!this.data.length) {
this.deactivate();
} else {
this.activateIndexedItem();
}
},
clear: function() {
this.data = [];
this.$el.html('');
this.index = 0;
return this;
},
activateIndexedItem: function() {
this.$el.find('.active').removeClass('active');
this.getActiveItem().addClass('active');
},
getActiveItem: function() {
return $(this.$el.children().get(this.index));
},
activate: function() {
if (!this.shown) {
this.$el.show();
$(this).trigger('textComplete:show');
// this.completer.$el.trigger('textComplete:show');
this.shown = true;
}
return this;
},
deactivate: function() {
if (this.shown) {
this.$el.hide();
$(this).trigger('textComplete:show');
// this.completer.$el.trigger('textComplete:hide');
this.shown = false;
this.data = [];
this.index = null;
}
return this;
},
setPosition: function(position) {
var fontSize;
// If the strategy has the 'placement' option set to 'top', move the
// position above the element
if(this.completer.strategy.placement === 'top') {
// Move it to be in line with the match character
fontSize = parseInt(this.$el.css('font-size'));
// Overwrite the position object to set the 'bottom' property instead of the top.
position = {
top: 'auto',
bottom: this.$el.parent().height() - position.top + fontSize,
left: position.left
};
this.$el.css(position);
} else if (this.completer.strategy.placement === 'auto') {
this.$el.removeAttr('style');
} else {
// Overwrite 'bottom' property because once `placement: 'top'`
// strategy is shown, $el keeps the property.
position.bottom = 'auto';
this.$el.css(position);
}
return this;
},
select: function(index) {
var self = this;
this.completer.onSelect(this.data[index]);
// Deactive at next tick to allow other event handlers to know whether
// the dropdown has been shown or not.
setTimeout(function() {
self.deactivate();
}, 0);
},
onKeydown: function(e) {
if (!this.shown) return;
if (e.keyCode === 27) { // ESC
this.deactivate();
} else if (e.keyCode === 38 || (e.ctrlKey && e.keyCode === 80)) { // UP
e.preventDefault();
if (this.index === 0) {
this.index = this.data.length - 1;
} else {
this.index -= 1;
}
this.activateIndexedItem();
} else if (e.keyCode === 40 || (e.ctrlKey && e.keyCode === 78)) { // DOWN
e.preventDefault();
if (this.index === this.data.length - 1) {
this.index = 0;
} else {
this.index += 1;
}
this.activateIndexedItem();
} else if (e.keyCode === 13 || e.keyCode === 9) { // ENTER or TAB
e.preventDefault();
this.select(parseInt(this.getActiveItem().data('index'), 10));
}
},
onClick: function(e) {
var $e = $(e.target);
e.originalEvent.keepTextCompleteDropdown = true;
if (!$e.hasClass('textcomplete-item')) {
$e = $e.parents('li.textcomplete-item');
}
this.select(parseInt($e.data('index'), 10));
},
destroy: function() {
this.deactivate();
this.$el.off('click.textComplete').remove();
this.$el = null;
}
});
return ListView;
}])
/**
* Textcomplete class.
*/
.factory('Textcomplete', ['utils', 'Completer',
function(utils, Completer) {
/**
* Default template function.
*/
function identity(obj) {
return obj;
};
/**
* Textcomplete class
* @param {Element} element
* @param {Object} strategies
*/
function Textcomplete(element, strategies) {
var i, l, strategy, dataKey;
dataKey = 'textComplete';
if (strategies === 'destroy') {
return this.each(function () {
var completer = $(this).data(dataKey);
if (completer) { completer.destroy(); }
});
}
for (i = 0, l = strategies.length; i < l; i++) {
strategy = strategies[i];
if (!strategy.template) {
strategy.template = identity;
}
if (strategy.index == null) {
strategy.index = 2;
}
if (strategy.cache) {
strategy.search = memoize(strategy.search);
}
strategy.maxCount || (strategy.maxCount = 10);
}
var completer;
completer = element.data(dataKey);
if (!completer) {
completer = new Completer(element);
element.data(dataKey, completer);
}
completer.register(strategies);
return $(completer);
};
return Textcomplete;
}
])
; |
/**
* @author Toru Nagashima
* @copyright 2017 Toru Nagashima. All rights reserved.
* See LICENSE file in root directory for full license.
*/
'use strict'
/*
This script updates `lib/index.js` file from rule's meta data.
*/
const fs = require('fs')
const path = require('path')
const eslint = require('eslint')
const rules = require('./lib/rules')
const categories = require('./lib/categories')
// Update files.
const filePath = path.resolve(__dirname, '../lib/index.js')
const content = `/*
* IMPORTANT!
* This file has been automatically generated,
* in order to update it's content execute "npm run update"
*/
'use strict'
module.exports = {
rules: {
${rules.map(rule => `'${rule.name}': require('./rules/${rule.name}')`).join(',\n')}
},
configs: {
${categories.map(category => `'${category.categoryId}': require('./configs/${category.categoryId}')`).join(',\n')}
},
processors: {
'.vue': require('./processor')
}
}
`
fs.writeFileSync(filePath, content)
// Format files.
const linter = new eslint.CLIEngine({ fix: true })
const report = linter.executeOnFiles([filePath])
eslint.CLIEngine.outputFixes(report)
|
require("system/application_ext");
require("adapters");
|
version https://git-lfs.github.com/spec/v1
oid sha256:0a181475c9a61a28e1cc32f92a97386ba3176bb08ee096c15d73666f25fe2dd9
size 1038
|
window.addEventListener('load', () => {
setTimeout(() => {
window.location.replace('/pages/level.html');
}, 1000);
});
|
(function () {
'use strict';
angular
.module('cards')
.controller('CardsController', CardsController);
CardsController.$inject = ['$scope', '$state', 'cardResolve', '$window', 'Authentication'];
function CardsController($scope, $state, card, $window, Authentication) {
var vm = this;
vm.card = card;
vm.authentication = Authentication;
vm.error = null;
vm.form = {};
vm.remove = remove;
vm.save = save;
vm.options = {
types: ['Action', 'Asteroid', 'Resource', 'Character', 'Contract']
};
// Remove existing Article
function remove() {
if ($window.confirm('Are you sure you want to delete?')) {
vm.card.$remove($state.go('cards.list'));
}
}
// Save Article
function save(isValid) {
if (!isValid) {
$scope.$broadcast('show-errors-check-validity', 'vm.form.articleForm');
return false;
}
// TODO: move create/update logic to service
if (vm.card._id) {
vm.card.$update(successCallback, errorCallback);
} else {
vm.card.$save(successCallback, errorCallback);
}
function successCallback(res) {
$state.go('cards.view', {
cardId: res._id
});
}
function errorCallback(res) {
vm.error = res.data.message;
}
}
}
}());
|
module.exports = {
env: {
es6: true
},
parserOptions: {
ecmaVersion: 6,
sourceType: 'module'
},
plugins: [
'import'
],
settings: {
'import/resolver': {
node: {
extensions: ['.js', '.json']
}
},
'import/extensions': [
'.js',
'.jsx',
],
'import/core-modules': [
],
'import/ignore': [
'node_modules',
'\\.(coffee|scss|css|less|hbs|svg|json)$',
],
},
rules: {
// Static analysis:
// ensure imports point to files/modules that can be resolved
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-unresolved.md
'import/no-unresolved': ['error', { commonjs: true, caseSensitive: true }],
// ensure named imports coupled with named exports
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/named.md#when-not-to-use-it
'import/named': 'off',
// ensure default import coupled with default export
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/default.md#when-not-to-use-it
'import/default': 'off',
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/namespace.md
'import/namespace': 'off',
// Helpful warnings:
// disallow invalid exports, e.g. multiple defaults
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/export.md
'import/export': 'error',
// do not allow a default import name to match a named export
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-named-as-default.md
'import/no-named-as-default': 'error',
// warn on accessing default export property names that are also named exports
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-named-as-default-member.md
'import/no-named-as-default-member': 'error',
// disallow use of jsdoc-marked-deprecated imports
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-deprecated.md
'import/no-deprecated': 'off',
// Forbid the use of extraneous packages
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-extraneous-dependencies.md
// paths are treated both as absolute paths, and relative to process.cwd()
'import/no-extraneous-dependencies': ['error', {
devDependencies: [
'test/**', // tape, common npm pattern
'tests/**', // also common npm pattern
'spec/**', // mocha, rspec-like pattern
'**/__tests__/**', // jest pattern
'test.{js,jsx}', // repos with a single test file
'test-*.{js,jsx}', // repos with multiple top-level test files
'**/*.{test,spec}.{js,jsx}', // tests where the extension denotes that it is a test
'**/webpack.config.js', // webpack config
'**/webpack.config.*.js', // webpack config
'**/rollup.config.js', // rollup config
'**/rollup.config.*.js', // rollup config
'**/gulpfile.js', // gulp config
'**/gulpfile.*.js', // gulp config
'**/Gruntfile', // grunt config
],
optionalDependencies: false,
}],
// Forbid mutable exports
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-mutable-exports.md
'import/no-mutable-exports': 'error',
// Module systems:
// disallow require()
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-commonjs.md
'import/no-commonjs': 'off',
// disallow AMD require/define
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-amd.md
'import/no-amd': 'error',
// No Node.js builtin modules
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-nodejs-modules.md
// TODO: enable?
'import/no-nodejs-modules': 'off',
// Style guide:
// disallow non-import statements appearing before import statements
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/first.md
'import/first': ['error', 'absolute-first'],
// disallow non-import statements appearing before import statements
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/imports-first.md
// deprecated: use `import/first`
'import/imports-first': 'off',
// disallow duplicate imports
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-duplicates.md
'import/no-duplicates': 'error',
// disallow namespace imports
// TODO: enable?
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-namespace.md
'import/no-namespace': 'off',
// Ensure consistent use of file extension within the import path
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/extensions.md
'import/extensions': ['error', 'always', {
js: 'never',
jsx: 'never',
}],
// Enforce a convention in module import order
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/order.md
// TODO: enable?
'import/order': ['off', {
groups: ['builtin', 'external', 'internal', 'parent', 'sibling', 'index'],
'newlines-between': 'never',
}],
// Require a newline after the last import/require in a group
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/newline-after-import.md
'import/newline-after-import': 'error',
// Require modules with a single export to use a default export
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/prefer-default-export.md
'import/prefer-default-export': 'error',
// Restrict which files can be imported in a given folder
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-restricted-paths.md
'import/no-restricted-paths': 'off',
// Forbid modules to have too many dependencies
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/max-dependencies.md
'import/max-dependencies': ['off', { max: 10 }],
// Forbid import of modules using absolute paths
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-absolute-path.md
'import/no-absolute-path': 'error',
// Forbid require() calls with expressions
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-dynamic-require.md
'import/no-dynamic-require': 'error',
// prevent importing the submodules of other modules
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-internal-modules.md
'import/no-internal-modules': ['off', {
allow: [],
}],
// Warn if a module could be mistakenly parsed as a script by a consumer
// leveraging Unambiguous JavaScript Grammar
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/unambiguous.md
// this should not be enabled until this proposal has at least been *presented* to TC39.
// At the moment, it's not a thing.
'import/unambiguous': 'off',
// Forbid Webpack loader syntax in imports
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-webpack-loader-syntax.md
'import/no-webpack-loader-syntax': 'error',
// Prevent unassigned imports
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-unassigned-import.md
// importing for side effects is perfectly acceptable, if you need side effects.
'import/no-unassigned-import': 'off',
// Prevent importing the default as if it were named
// https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-named-default.md
'import/no-named-default': 'error',
},
};
|
// import {
// createStore,
// compose,
// combineReducers,
// } from 'redux';
// import { routerReducer } from 'react-router-redux';
// import DevTools from 'containers/DevTools';
// import env from 'util/env';
// import reducers from './reducers';
// console.log(env);
// const finalCreateStore = compose(
// // applyMiddleware(...)
// DevTools.instrument() // middleware存在异步,放在之后确保actions都在store中
// )(createStore);
// const store = finalCreateStore(combineReducers({
// ...reducers,
// routing: routerReducer,
// }));
// export default store;
|
import {fetch, Request, Response, Headers, Promise} from '../core/Externals';
import * as utils from '../core/Utils';
/**
* Creates a response
* @param stringBody
* @param init
* @return {Response}
*/
export function createResponse(stringBody, init) {
init = init || {};
var response = new Response(stringBody, init);
//TODO Wait for https://github.com/bitinn/node-fetch/issues/38
if (utils.isNodeJS()) {
response._text = stringBody;
response._decode = function() {
return this._text;
};
}
return response;
}
export function findHeaderName(name, headers) {
name = name.toLowerCase();
return Object.keys(headers).reduce(function(res, key) {
if (res) return res;
if (name == key.toLowerCase()) return key;
return res;
}, null);
} |
var assert = require('assert');
var sinon = require('sinon');
var evently = require('../index');
describe('evently', function () {
describe('Dispatcher', function () {
describe('#once', function () {
it('should fire once', function () {
var dispatcher = new evently.Dispatcher();
var aCounter = sinon.spy();
var bCounter = sinon.spy();
dispatcher.once("a", aCounter);
dispatcher.once("b", bCounter);
dispatcher.trigger("a");
dispatcher.trigger("a");
dispatcher.trigger("b");
dispatcher.trigger("b");
dispatcher.trigger("b");
dispatcher.trigger("a");
dispatcher.trigger("a");
assert(aCounter.calledOnce);
assert(bCounter.calledOnce);
});
});
});
});
|
var nb = require("./");
var server = new nb.VimServer({
debug: false
});
server.on("clientAuthed", function (vim) {
vim.on("newBuffer", function (buffer) {
buffer.startDocumentListen();
buffer.setDot(0);
console.log("Inserting welcome message.");
buffer.insert(0, "Press control-i to insert a timestamp.\n\n");
});
vim.on("insert", function (buffer, offset, text) {
console.log("Inserted text at " + offset + ": " + text);
});
vim.on("remove", function (buffer, offset, length) {
console.log("Removed " + length + " bytes at " + offset);
});
vim.key("C-i", function (buffer, offset, lnum, col) {
// insert a timestamp before the current line
console.log("Inserting timestamp");
var num = new Date().toString();
buffer.insert(offset - col, num);
});
});
server.listen(function () {
console.log("Server started. Connect with vim -nb or :nbs");
});
|
/**
* Swaggy Jenkins
* Jenkins API clients generated from Swagger / Open API specification
*
* The version of the OpenAPI document: 1.1.2-pre.0
* Contact: [email protected]
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*
*/
import ApiClient from '../ApiClient';
import CauseAction from './CauseAction';
import FreeStyleProject from './FreeStyleProject';
/**
* The QueueBlockedItem model module.
* @module model/QueueBlockedItem
* @version 1.1.2-pre.0
*/
class QueueBlockedItem {
/**
* Constructs a new <code>QueueBlockedItem</code>.
* @alias module:model/QueueBlockedItem
*/
constructor() {
QueueBlockedItem.initialize(this);
}
/**
* Initializes the fields of this object.
* This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins).
* Only for internal use.
*/
static initialize(obj) {
}
/**
* Constructs a <code>QueueBlockedItem</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/QueueBlockedItem} obj Optional instance to populate.
* @return {module:model/QueueBlockedItem} The populated <code>QueueBlockedItem</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new QueueBlockedItem();
if (data.hasOwnProperty('_class')) {
obj['_class'] = ApiClient.convertToType(data['_class'], 'String');
}
if (data.hasOwnProperty('actions')) {
obj['actions'] = ApiClient.convertToType(data['actions'], [CauseAction]);
}
if (data.hasOwnProperty('blocked')) {
obj['blocked'] = ApiClient.convertToType(data['blocked'], 'Boolean');
}
if (data.hasOwnProperty('buildable')) {
obj['buildable'] = ApiClient.convertToType(data['buildable'], 'Boolean');
}
if (data.hasOwnProperty('id')) {
obj['id'] = ApiClient.convertToType(data['id'], 'Number');
}
if (data.hasOwnProperty('inQueueSince')) {
obj['inQueueSince'] = ApiClient.convertToType(data['inQueueSince'], 'Number');
}
if (data.hasOwnProperty('params')) {
obj['params'] = ApiClient.convertToType(data['params'], 'String');
}
if (data.hasOwnProperty('stuck')) {
obj['stuck'] = ApiClient.convertToType(data['stuck'], 'Boolean');
}
if (data.hasOwnProperty('task')) {
obj['task'] = FreeStyleProject.constructFromObject(data['task']);
}
if (data.hasOwnProperty('url')) {
obj['url'] = ApiClient.convertToType(data['url'], 'String');
}
if (data.hasOwnProperty('why')) {
obj['why'] = ApiClient.convertToType(data['why'], 'String');
}
if (data.hasOwnProperty('buildableStartMilliseconds')) {
obj['buildableStartMilliseconds'] = ApiClient.convertToType(data['buildableStartMilliseconds'], 'Number');
}
}
return obj;
}
}
/**
* @member {String} _class
*/
QueueBlockedItem.prototype['_class'] = undefined;
/**
* @member {Array.<module:model/CauseAction>} actions
*/
QueueBlockedItem.prototype['actions'] = undefined;
/**
* @member {Boolean} blocked
*/
QueueBlockedItem.prototype['blocked'] = undefined;
/**
* @member {Boolean} buildable
*/
QueueBlockedItem.prototype['buildable'] = undefined;
/**
* @member {Number} id
*/
QueueBlockedItem.prototype['id'] = undefined;
/**
* @member {Number} inQueueSince
*/
QueueBlockedItem.prototype['inQueueSince'] = undefined;
/**
* @member {String} params
*/
QueueBlockedItem.prototype['params'] = undefined;
/**
* @member {Boolean} stuck
*/
QueueBlockedItem.prototype['stuck'] = undefined;
/**
* @member {module:model/FreeStyleProject} task
*/
QueueBlockedItem.prototype['task'] = undefined;
/**
* @member {String} url
*/
QueueBlockedItem.prototype['url'] = undefined;
/**
* @member {String} why
*/
QueueBlockedItem.prototype['why'] = undefined;
/**
* @member {Number} buildableStartMilliseconds
*/
QueueBlockedItem.prototype['buildableStartMilliseconds'] = undefined;
export default QueueBlockedItem;
|
tinymce.PluginManager.add("fullpage", function (e) {
function t() {
var t = n();
e.windowManager.open({title: "Document properties", data: t, defaults: {type: "textbox", size: 40}, body: [
{name: "title", label: "Title"},
{name: "keywords", label: "Keywords"},
{name: "description", label: "Description"},
{name: "robots", label: "Robots"},
{name: "author", label: "Author"},
{name: "docencoding", label: "Encoding"}
], onSubmit: function (e) {
i(tinymce.extend(t, e.data))
}})
}
function n() {
function t(e, t) {
var n = e.attr(t);
return n || ""
}
var n, i, r = a(), o = {};
return o.fontface = e.getParam("fullpage_default_fontface", ""), o.fontsize = e.getParam("fullpage_default_fontsize", ""), n = r.firstChild, 7 == n.type && (o.xml_pi = !0, i = /encoding="([^"]+)"/.exec(n.value), i && (o.docencoding = i[1])), n = r.getAll("#doctype")[0], n && (o.doctype = "<!DOCTYPE" + n.value + ">"), n = r.getAll("title")[0], n && n.firstChild && (o.title = n.firstChild.value), u(r.getAll("meta"), function (e) {
var t, n = e.attr("name"), i = e.attr("http-equiv");
n ? o[n.toLowerCase()] = e.attr("content") : "Content-Type" == i && (t = /charset\s*=\s*(.*)\s*/gi.exec(e.attr("content")), t && (o.docencoding = t[1]))
}), n = r.getAll("html")[0], n && (o.langcode = t(n, "lang") || t(n, "xml:lang")), n = r.getAll("link")[0], n && "stylesheet" == n.attr("rel") && (o.stylesheet = n.attr("href")), n = r.getAll("body")[0], n && (o.langdir = t(n, "dir"), o.style = t(n, "style"), o.visited_color = t(n, "vlink"), o.link_color = t(n, "link"), o.active_color = t(n, "alink")), o
}
function i(t) {
function n(e, t, n) {
e.attr(t, n ? n : void 0)
}
function i(e) {
o.firstChild ? o.insert(e, o.firstChild) : o.append(e)
}
var r, o, l, c, m, f = e.dom;
r = a(), o = r.getAll("head")[0], o || (c = r.getAll("html")[0], o = new d("head", 1), c.firstChild ? c.insert(o, c.firstChild, !0) : c.append(o)), c = r.firstChild, t.xml_pi ? (m = 'version="1.0"', t.docencoding && (m += ' encoding="' + t.docencoding + '"'), 7 != c.type && (c = new d("xml", 7), r.insert(c, r.firstChild, !0)), c.value = m) : c && 7 == c.type && c.remove(), c = r.getAll("#doctype")[0], t.doctype ? (c || (c = new d("#doctype", 10), t.xml_pi ? r.insert(c, r.firstChild) : i(c)), c.value = t.doctype.substring(9, t.doctype.length - 1)) : c && c.remove(), t.docencoding && (c = null, u(r.getAll("meta"), function (e) {
"Content-Type" == e.attr("http-equiv") && (c = e)
}), c || (c = new d("meta", 1), c.attr("http-equiv", "Content-Type"), c.shortEnded = !0, i(c)), c.attr("content", "text/html; charset=" + t.docencoding)), c = r.getAll("title")[0], t.title ? c || (c = new d("title", 1), c.append(new d("#text", 3)).value = t.title, i(c)) : c && c.remove(), u("keywords,description,author,copyright,robots".split(","), function (e) {
var n, a, o = r.getAll("meta"), l = t[e];
for (n = 0; n < o.length; n++)if (a = o[n], a.attr("name") == e)return l ? a.attr("content", l) : a.remove(), void 0;
l && (c = new d("meta", 1), c.attr("name", e), c.attr("content", l), c.shortEnded = !0, i(c))
}), c = r.getAll("link")[0], c && "stylesheet" == c.attr("rel") ? t.stylesheet ? c.attr("href", t.stylesheet) : c.remove() : t.stylesheet && (c = new d("link", 1), c.attr({rel: "stylesheet", text: "text/css", href: t.stylesheet}), c.shortEnded = !0, i(c)), c = r.getAll("body")[0], c && (n(c, "dir", t.langdir), n(c, "style", t.style), n(c, "vlink", t.visited_color), n(c, "link", t.link_color), n(c, "alink", t.active_color), f.setAttribs(e.getBody(), {style: t.style, dir: t.dir, vLink: t.visited_color, link: t.link_color, aLink: t.active_color})), c = r.getAll("html")[0], c && (n(c, "lang", t.langcode), n(c, "xml:lang", t.langcode)), o.firstChild || o.remove(), l = new tinymce.html.Serializer({validate: !1, indent: !0, apply_source_formatting: !0, indent_before: "head,html,body,meta,title,script,link,style", indent_after: "head,html,body,meta,title,script,link,style"}).serialize(r), s = l.substring(0, l.indexOf("</body>"))
}
function a() {
return new tinymce.html.DomParser({validate: !1, root_name: "#document"}).parse(s)
}
function r(t) {
function n(e) {
return e.replace(/<\/?[A-Z]+/g, function (e) {
return e.toLowerCase()
})
}
var i, r, l, d, m = t.content, f = "", g = e.dom;
t.selection || "raw" == t.format && s || t.source_view && e.getParam("fullpage_hide_in_source_view") || (m = m.replace(/<(\/?)BODY/gi, "<$1body"), i = m.indexOf("<body"), -1 != i ? (i = m.indexOf(">", i), s = n(m.substring(0, i + 1)), r = m.indexOf("</body", i), -1 == r && (r = m.length), t.content = m.substring(i + 1, r), c = n(m.substring(r))) : (s = o(), c = "\n</body>\n</html>"), l = a(), u(l.getAll("style"), function (e) {
e.firstChild && (f += e.firstChild.value)
}), d = l.getAll("body")[0], d && g.setAttribs(e.getBody(), {style: d.attr("style") || "", dir: d.attr("dir") || "", vLink: d.attr("vlink") || "", link: d.attr("link") || "", aLink: d.attr("alink") || ""}), g.remove("fullpage_styles"), f && (g.add(e.getDoc().getElementsByTagName("head")[0], "style", {id: "fullpage_styles"}, f), d = g.get("fullpage_styles"), d.styleSheet && (d.styleSheet.cssText = f)))
}
function o() {
var t, n = "", i = "";
return e.getParam("fullpage_default_xml_pi") && (n += '<?xml version="1.0" encoding="' + e.getParam("fullpage_default_encoding", "ISO-8859-1") + '" ?>\n'), n += e.getParam("fullpage_default_doctype", "<!DOCTYPE html>"), n += "\n<html>\n<head>\n", (t = e.getParam("fullpage_default_title")) && (n += "<title>" + t + "</title>\n"), (t = e.getParam("fullpage_default_encoding")) && (n += '<meta http-equiv="Content-Type" content="text/html; charset=' + t + '" />\n'), (t = e.getParam("fullpage_default_font_family")) && (i += "font-family: " + t + ";"), (t = e.getParam("fullpage_default_font_size")) && (i += "font-size: " + t + ";"), (t = e.getParam("fullpage_default_text_color")) && (i += "color: " + t + ";"), n += "</head>\n<body" + (i ? ' style="' + i + '"' : "") + ">\n"
}
function l(t) {
t.selection || t.source_view && e.getParam("fullpage_hide_in_source_view") || (t.content = tinymce.trim(s) + "\n" + tinymce.trim(t.content) + "\n" + tinymce.trim(c))
}
var s, c, u = tinymce.each, d = tinymce.html.Node;
e.addCommand("mceFullPageProperties", t), e.addButton("fullpage", {title: "Document properties", cmd: "mceFullPageProperties"}), e.addMenuItem("fullpage", {text: "Document properties", cmd: "mceFullPageProperties", context: "file"}), e.on("BeforeSetContent", r), e.on("GetContent", l)
}); |
var fs = require('fs');
var https = require('https');
var Moonboots = require('moonboots-express');
var express = require('express');
var helmet = require('helmet');
var xssFilter = require('x-xss-protection');
var frameguard = require('frameguard');
var config = require('getconfig');
var templatizer = require('templatizer');
var async = require('async');
var LDAP = require('ldapjs');
String.prototype.capitalize = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
};
var app = express();
var bodyParser = require('body-parser');
var compression = require('compression');
var serveStatic = require('serve-static');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(compression());
app.use(serveStatic(__dirname + '/public'));
if (!config.isDev) {
app.use(frameguard());
}
app.use(xssFilter({ setOnOldIE: true }));
app.use(helmet.noSniff());
var webappManifest = fs.readFileSync('./public/x-manifest.webapp');
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.get('/login', function (req, res) {
res.render("login", {"config": config.server});
});
app.get('/logout', function (req, res) {
res.render('logout');
});
app.get('/config.js', function (req, res) {
res.type('application/javascript');
res.send("window.SERVER_CONFIG = " + JSON.stringify(config.server) + ";");
});
app.get('/sounds/*', function (req, res) {
res.type('audio/wav');
res.redirect("./public" + req.baseUrl);
});
function connectLDAP(req, cb) {
if (!config.ldap || !config.ldap.address || !config.ldap.base) {
cb(true);
return;
}
var ldapDN = 'uid=' + req.body.uid + ',' + config.ldap.base;
var ldapPW = req.body.password;
var client = LDAP.createClient({ url: 'ldap://' + config.ldap.address });
function closeCb(client) {
client.unbind();
console.log("LDAP: Disconnected");
}
client.bind(ldapDN, ldapPW, function(err) {
if (err) {
console.log("LDAP: Can not connect to server with " + ldapDN);
closeCb(client);
cb(true);
return;
}
console.log("LDAP: Connected on ldap://" + config.ldap.address + " with " + ldapDN);
if (req.body.uid == config.server.admin && config.ldap.user && config.ldap.password) {
console.log("LDAP: " + ldapDN + " is XMPP admin");
client.bind(config.ldap.user, config.ldap.password, function(err) {
if (err) {
console.log("LDAP: Can not connect to server with " + config.ldap.user);
closeCb(client);
cb(true);
return;
}
console.log("LDAP: Connected on ldap://" + config.ldap.address + " with " + config.ldap.user);
cb(false, client, closeCb);
});
return;
}
cb(false, client, closeCb);
});
}
app.post('/ldap/user/:id', function(req, res) {
var dn = 'uid=' + req.params.id.toLowerCase() + ',' + config.ldap.base;
console.log('LDAP: Save user informations (' + dn + ')');
connectLDAP(req, function (err, client, closeCb) {
if (err === false) {
var changes = [];
if (req.body.cn !== undefined) changes.push(new LDAP.Change({ operation: 'replace', modification: {cn: req.body.cn}}));
if (req.body.sn !== undefined) changes.push(new LDAP.Change({ operation: 'replace', modification: {sn: req.body.sn}}));
if (req.body.givenName !== undefined) changes.push(new LDAP.Change({ operation: 'replace', modification: {givenName: req.body.givenName}}));
if (req.body.displayName !== undefined) changes.push(new LDAP.Change({ operation: 'replace', modification: {displayName: req.body.displayName}}));
if (req.body.mail !== undefined) changes.push(new LDAP.Change({ operation: 'replace', modification: {mail: req.body.mail}}));
client.modify(dn, changes, function (err) {
if (err) {
console.log('LDAP: Impossible to change user informations (' + dn + ')');
console.log(err);
res.type('application/javascript');
res.send(false);
closeCb(client);
return;
}
console.log('LDAP: User informations saved (' + dn + ')');
res.type('application/javascript');
res.send(true);
closeCb(client);
});
}
});
});
app.post('/ldap/user/:id/password', function(req, res) {
var dn = 'uid=' + req.params.id.toLowerCase() + ',' + config.ldap.base;
console.log('LDAP: Change user password (' + dn + ')');
connectLDAP(req, function (err, client, closeCb) {
if (err === false) {
var changes = [new LDAP.Change({ operation: 'replace', modification: {userPassword: req.body.newPassword}})];
client.modify(dn, changes, function (err) {
if (err) {
console.log('LDAP: Impossible to change user password (' + dn + ')');
console.log(err);
res.type('application/javascript');
res.send(false);
closeCb(client);
return;
}
console.log('LDAP: User password changed (' + dn + ')');
res.type('application/javascript');
res.send(true);
closeCb(client);
});
}
});
});
app.post('/ldap/users', function (req, res) {
console.log('LDAP: Get users list');
connectLDAP(req, function (err, client, closeCb) {
if (err === false) {
var filter = config.ldap.filter;
if (req.body.uid != config.server.admin) {
var uid = 'uid=' + req.body.uid.toLowerCase();
filter = '(&(' + filter + ')(' + uid + '))';
}
var opts = {
filter: filter,
scope: 'sub',
attributes: ['uid', 'cn', 'sn', 'givenName', 'displayName', 'mail', 'objectClass'],
attrsOnly: true
};
client.search(config.ldap.base, opts, function(err, data) {
var users = [];
if (!err) {
data.on('searchEntry', function(entry) {
var user = {};
entry.attributes.forEach(function(attr) {
user[attr.type] = attr.vals;
if (attr.type !== 'objectClass') {
user[attr.type] = user[attr.type][0];
}
});
users.push(user);
});
data.on('end', function(result) {
res.type('application/javascript');
res.send(JSON.stringify(users));
console.log('LDAP: Users list sent');
closeCb(client);
});
}
else {
console.log(err);
}
});
}
});
});
app.post('/ldap/users/add', function (req, res) {
console.log('LDAP: Add a new user');
connectLDAP(req, function (err, client, closeCb) {
if (err === false || !req.body.newUid) {
var dn = 'uid=' + req.body.newUid.toLowerCase() + ',' + config.ldap.base;
var entry = {
objectClass: [ 'organizationalPerson', 'person', 'inetOrgPerson'],
cn: req.body.newUid.capitalize(),
sn: req.body.newUid.capitalize(),
givenName: req.body.newUid.capitalize(),
displayName: req.body.newUid.capitalize(),
userPassword: req.body.newUid.toLowerCase()
};
client.add(dn, entry, function (err) {
if (err) {
console.log('LDAP: Impossible to add a new user (' + dn + ')');
console.log(err);
res.type('application/javascript');
res.send(false);
closeCb(client);
return;
}
if (config.ldap.group) {
var changes = [
{ operation: 'add',
modification: {member: dn }
}
];
client.modify(config.ldap.group, changes, function (err) {
if (err) console.log(err);
console.log('LDAP: New user added (' + dn + ')');
res.type('application/javascript');
res.send(true);
closeCb(client);
});
}
});
}
});
});
app.post('/ldap/users/delete', function (req, res) {
console.log('LDAP: Remove a user');
connectLDAP(req, function (err, client, closeCb) {
if (err === false || !req.body.removeUid) {
var dn = 'uid=' + req.body.removeUid.toLowerCase() + ',' + config.ldap.base;
client.del(dn, function (err) {
if (err) {
console.log('LDAP: Impossible to remove this user (' + dn + ')');
console.log(err);
res.type('application/javascript');
res.send(false);
closeCb(client);
return;
}
if (config.ldap.group) {
var changes = [
{ operation: 'delete',
modification: {member: dn }
}
];
client.modify(config.ldap.group, changes, function (err) {
if (err) console.log(err);
console.log('LDAP: User removed (' + dn + ')');
res.type('application/javascript');
res.send(true);
closeCb(client);
});
}
});
}
});
});
app.get('/oauth/login', function (req, res) {
res.redirect('https://apps.andyet.com/oauth/authorize?client_id=' + config.andyetAuth.id + '&response_type=token');
});
app.get('/oauth/callback', function (req, res) {
res.render('oauthLogin');
});
app.get('/manifest.webapp', function (req, res, next) {
res.set('Content-Type', 'application/x-web-app-manifest+json');
res.send(webappManifest);
});
app.use(function handleError(err, req, res, next) {
var errorResult = {message: 'Something bad happened :('};
if (config.isDev) {
if (err instanceof Error) {
if (err.message) {
errorResult.message = err.message;
}
if (err.stack) {
errorResult.stack = err.stack;
}
}
}
res.status(500);
res.render('error', errorResult);
});
var clientApp = new Moonboots({
moonboots: {
main: __dirname + '/clientapp/app.js',
developmentMode: config.isDev,
libraries: [
__dirname + '/clientapp/libraries/jquery.js',
__dirname + '/clientapp/libraries/ui.js',
__dirname + '/clientapp/libraries/resampler.js',
__dirname + '/clientapp/libraries/IndexedDBShim.min.js',
__dirname + '/clientapp/libraries/sugar-1.2.1-dates.js',
__dirname + '/clientapp/libraries/jquery.oembed.js',
__dirname + '/clientapp/libraries/jquery-impromptu.js'
],
browserify: {
debug: false
},
stylesheets: [
__dirname + '/public/css/client.css',
__dirname + '/public/css/jquery.oembed.css',
__dirname + '/public/css/jquery-impromptu.css'
],
beforeBuildJS: function () {
if (config.isDev) {
var clientFolder = __dirname + '/clientapp';
templatizer(clientFolder + '/templates', clientFolder + '/templates.js');
}
}
},
server: app,
cachePeriod: 0,
render: function (req, res) {
res.render('index');
}
});
clientApp.on('ready', function () {
console.log('Client app ready');
var pkginfo = JSON.parse(fs.readFileSync(__dirname + '/package.json'));
var manifestTemplate = fs.readFileSync(__dirname + '/clientapp/templates/misc/manifest.cache', 'utf-8');
var cacheManifest = manifestTemplate
.replace('#{version}', pkginfo.version + config.isDev ? ' ' + Date.now() : '')
.replace('#{jsFileName}', clientApp.moonboots.jsFileName())
.replace('#{cssFileName}', clientApp.moonboots.cssFileName());
console.log('Cache manifest generated');
app.get('/manifest.cache', function (req, res, next) {
res.set('Content-Type', 'text/cache-manifest');
res.set('Cache-Control', 'no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0');
res.send(cacheManifest);
});
// serves app on every other url
app.get('*', function (req, res) {
res.render(clientApp.moonboots.htmlSource());
});
});
app.listen(config.http.port, config.http.host, function () {
console.log('Kaiwa running...');
if (config.http.host) {
console.log('Hostname:' + config.http.host);
}
console.log('Port:' + config.http.port);
});
|
$.extend({
replaceTag: function (currentElem, newTagObj, keepProps) {
var $currentElem = $(currentElem);
var $newTag = $(newTagObj).clone(true, true);
if (keepProps) {
$.each($currentElem.prop('attributes'), function () {
$newTag.attr(this.name, this.value);
});
}
$currentElem.wrapAll($newTag);
$currentElem.contents().unwrap();
return this;
}
});
$.fn.extend({
replaceTag: function (newTagObj, keepProps) {
return this.each(function() {
jQuery.replaceTag(this, newTagObj, keepProps);
});
}
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:93cb545a6a3fc34cfc50613fad541fea79e62227c3634af4854fb83bced652e2
size 2203
|
'use strict';
const t = require('@aso/tcomb');
const types = require('../types.js');
describe('types.EnvironmentVariable', () => {
it('is a Type', () => {
t.test(types.EnvironmentVariable, t.Type);
});
it('allows uppercase letters and underscores', () => {
t.test('SOME_VARIABLE', types.EnvironmentVariable);
});
it('rejects lower case strings', () => {
t.test.not('SOME-VARIABLE', types.EnvironmentVariable);
t.test.not('SOME_VARIABLe', types.EnvironmentVariable);
t.test.not('SOME_VARIABL#', types.EnvironmentVariable);
t.test.not('SOME_VARIABL$', types.EnvironmentVariable);
});
});
describe('types.Monitor', () => {
it('is a tcomb Type', () => {
t.test(types.Monitor, t.Type);
});
});
|
import restRouter from '../../dist/restRouter';
import bodyParser from 'body-parser';
import express from 'express';
import supertest from 'supertest';
import {Entity, Model} from './tools';
describe('restRouter', () => {
let req;
let data;
beforeEach(() => {
data = [];
let model = new Model(data);
data.push(new Entity({_id: '1', name: 'Genesis'}, model)),
data.push(new Entity({_id: '2', name: 'Exodus'}, model)),
data.push(new Entity({_id: '3', name: 'Leviticus'}, model));
let app = express();
app.use(bodyParser.json());
app.use('/', restRouter({model}));
req = supertest(app);
});
it('gets one', done => {
req.get('/1')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(200)
.end((err, res) => {
if (err) return done(err);
expect(res.body.name).toBe('Genesis');
done();
});
});
it('gets all', done => {
req.get('/')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(200)
.end((err, res) => {
if (err) return done(err);
expect(res.body[0].name).toBe('Genesis');
expect(res.body[1].name).toBe('Exodus');
expect(res.body[2].name).toBe('Leviticus');
done();
});
});
it('posts', done => {
let record = {name: 'Numeri'};
req.post('/')
.send(record)
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(201)
.end((err, res) => {
if (err) return done(err);
expect(res.body).toEqual(record);
done();
});
});
it('puts', done => {
let name = '1st book of Moses';
req.put('/1')
.send({name})
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(200)
.end((err, res) => {
if (err) return done(err);
expect(res.body).toEqual({_id: '1', name});
done();
});
});
it('deletes', done => {
let name = '1st book of Moses';
req.del('/1')
.set('Accept', 'application/json')
.expect(204)
.end((err, res) => {
if (err) return done(err);
expect(req.body).toBeUndefined();
done();
});
});
});
|
import { createIterator, createIterable } from '../helpers/helpers';
import { STRICT_THIS } from '../helpers/constants';
import AsyncIterator from 'core-js-pure/features/async-iterator';
QUnit.test('AsyncIterator#flatMap', assert => {
assert.expect(15);
const async = assert.async();
const { flatMap } = AsyncIterator.prototype;
assert.isFunction(flatMap);
assert.arity(flatMap, 1);
assert.nonEnumerable(AsyncIterator.prototype, 'flatMap');
flatMap.call(createIterator([1, [], 2, createIterable([3, 4]), [5, 6], 'ab']), it => typeof it == 'number' ? [-it] : it).toArray().then(it => {
assert.arrayEqual(it, [-1, -2, 3, 4, 5, 6, 'a', 'b'], 'basic functionality');
return flatMap.call(createIterator([1]), function (arg) {
assert.same(this, STRICT_THIS, 'this');
assert.same(arguments.length, 1, 'arguments length');
assert.same(arg, 1, 'argument');
return [arg];
}).toArray();
}).then(() => {
return flatMap.call(createIterator([1]), () => { throw 42; }).toArray();
}).catch(error => {
assert.same(error, 42, 'rejection on a callback error');
}).then(() => async());
assert.throws(() => flatMap.call(undefined, () => { /* empty */ }), TypeError);
assert.throws(() => flatMap.call(null, () => { /* empty */ }), TypeError);
assert.throws(() => flatMap.call({}, () => { /* empty */ }), TypeError);
assert.throws(() => flatMap.call([], () => { /* empty */ }), TypeError);
assert.throws(() => flatMap.call(createIterator([1]), undefined), TypeError);
assert.throws(() => flatMap.call(createIterator([1]), null), TypeError);
assert.throws(() => flatMap.call(createIterator([1]), {}), TypeError);
});
|
module.exports = function(schema, options){
var getter = function(v){
return /^mongoose-$/.test(v) ? v += 'mongoosed' : v;
};
var paths = options.paths;
schema.pre('init', function(next, doc){
if (doc){
paths.forEach(function(p){
doc[p] = getter(doc[p]);
})
}
next();
});
};
|
'use strict';
var express = require('express');
var router = new express.Router();
var rootRoute = router.route('foobar');
rootRoute.post(function(req, res) {
problem(req.body);
whileLoop(req.body);
useLengthIndirectly(req.body);
noNullPointer(req.body);
});
function problem(val) {
var ret = [];
for (var i = 0; i < val.length; i++) { // NOT OK!
ret.push(val[i]);
}
}
function whileLoop(val) {
var ret = [];
var i = 0;
while (i < val.length) { // NOT OK!
ret.push(val[i]);
i++;
}
}
function useLengthIndirectly(val) {
var ret = [];
var len = val.length; // NOT OK!
for (var i = 0; i < len; i++) {
ret.push(val[i]);
}
}
// The obvious null-pointer detection should not hit this one.
function noNullPointer(val) {
var ret = [];
const c = 0;
for (var i = 0; i < val.length; i++) { // NOT OK!
// Constantly accessing element 0, therefore not guaranteed null-pointer.
ret.push(val[c].foo);
}
}
|
module.exports = require('./src/transport/websocketBrowser')
|
'use strict';
/* global hexo */
hexo.config.uglify = Object.assign({
mangle: true,
output: {},
compress: {},
exclude: '*.min.js'
}, hexo.config.uglify);
hexo.extend.filter.register('after_render:js', require('./lib/filter'));
|
// @flow
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { ThemeProvider } from 'styled-components'
import defaultTheme from './defaultTheme'
class NiceUIThemeProvider extends Component {
static propTypes = {
children: PropTypes.element.isRequired,
theme: PropTypes.object,
};
static defaultProps = {
theme: defaultTheme,
};
render() {
const { children, theme, ...other } = this.props
return <ThemeProvider theme={theme} {...other}>{children}</ThemeProvider>
}
}
export default NiceUIThemeProvider
|
(function () {
'use strict';
angular.module('blinfo.login.internal', []);
})();
|
var myScroll=false,yy={
sousoukey:'',
resizehei:function(){
var hei= this.getheight();
var ob = this.showobj.css({'height':''+hei+'px'});
return ob;
},
getheight:function(ss){
var hei = 0;if(!ss)ss=0;
if(get('searsearch_bar'))hei+=45;
if(get('header_title'))hei+=50;
if(get('footerdiv'))hei+=50;
return $(window).height()-hei+ss;
},
initScroll:function(){
if(get('searsearch_bar')){
this.touchobj = $('#mainbody').rockdoupull({
upbool:true,
onupbefore:function(){
return yy.onupbefore();
},
upmsgdiv:'showblank',
onupsuccess:function(){
yy.scrollEndevent();
}
});
}
},
init:function(){
this.num = json.num;
this.showobj = $('#mainbody');
$('.weui_navbar').click(function(){return false;});
$('body').click(function(){
$("div[id^='menushoess']").remove();
});
this.initScroll();
this.resizehei();
$(window).resize(function(){
yy.resizehei();
});
},
clickmenu:function(oi,o1){
var sid='menushoess_'+oi+'';
if(get(sid)){
$('#'+sid+'').remove();
return;
}
$("div[id^='menushoess']").remove();
var a = json.menu[oi],slen=a.submenu.length,i,a1;
this.menuname1 = a.name;
this.menuname2 = '';
if(slen<=0){
this.clickmenus(a);
}else{
var o=$(o1),w=1/json.menu.length*100;
var s='<div id="'+sid+'" style="position:fixed;z-index:5;left:'+(o.offset().left)+'px;bottom:50px; background:white;width:'+w+'%" class="menulist r-border-r r-border-l">';
for(i=0;i<slen;i++){
a1=a.submenu[i];
s+='<div onclick="yy.clickmenua('+oi+','+i+')" class="r-border-t" style="color:'+a1.color+';">'+a1.name+'</div>';
}
s+='</div>';
$('body').append(s);
}
},
searchuser:function(){
$('#searsearch_bar').addClass('weui_search_focusing');
$('#search_input').focus();
},
searchcancel:function(){
$('#search_input').blur();
$('#searsearch_bar').removeClass('weui_search_focusing');
},
souclear:function(){
$('#search_input').val('').focus();
},
sousousou:function(){
var key = $('#search_input').blur().val();
this.keysou(key);
},
clickmenua:function(i,j){
var a = json.menu[i].submenu[j];
this.menuname2 = a.name;
this.clickmenus(a);
},
onclickmenu:function(a){
return true;
},
clickmenus:function(a){
$("div[id^='menushoess']").remove();
if(!this.onclickmenu(a))return;
var tit = this.menuname1;
if(this.menuname2!='')tit+='→'+this.menuname2+'';
document.title = tit;
$('#header_title').html(tit);
if(a.type==0){
this.searchcancel();
this.sousoukey='';
this.clickevent(a);return;
}
if(a.type==1){
var url=a.url,amod=this.num;
if(url.substr(0,3)=='add'){
if(url!='add')amod=url.replace('add_','');
url='index.php?a=lum&m=input&d=flow&num='+amod+'&show=we';
}
js.location(url);
}
},
clickevent:function(a){
this.getdata(a.url, 1);
},
data:[],
_showstotal:function(d){
var d1,v,s,o1;
for(d1 in d){
v=d[d1];
if(v==0)v='';
o1= $('#'+d1+'_stotal');
o1.html(v);
}
},
regetdata:function(o,p){
var mo = 'mode';
if(o){
o.innerHTML='<img src="images/loading.gif" align="absmiddle">';
mo = 'none';
}
this.getdata(this.nowevent,p, mo);
},
getdata:function(st,p, mo){
this.nowevent=st;
this.nowpage = p;
if(!mo)mo='mode';
var key = ''+this.sousoukey;
if(key)key='basejm_'+jm.base64encode(key)+'';
js.ajax('index','getyydata',{'page':p,'event':st,'num':this.num,'key':key},function(ret){
yy.showdata(ret);
},mo, false,false, 'get');
},
getfirstnum:function(d){
var dbh = 'def',bh='';
var a = d[0];
if(a){
bh = a.url;
if(a.submenu[0])bh=a.submenu[0].url;
}
if(isempt(bh))bh=dbh;
return bh;
},
reload:function(){
this.getdata(this.nowevent,this.nowpage);
},
keysou:function(key){
if(this.sousoukey == key)return;
this.sousoukey = key;
this.regetdata(false,1);
},
xiang:function(oi){
var d = this.data[oi-1];
var ids = d.id,nus=d.modenum,modne=d.modename;
if(!ids)return;
if(!nus||nus=='undefined')nus = this.num;
var url='task.php?a=x&num='+nus+'&mid='+ids+'&show=we';
js.location(url);
},
suboptmenu:{},
showmenu:function(oi){
var a = this.data[oi-1],ids = a.id,i;
var nus=a.modenum;if(!nus||nus=='undefined')nus = this.num;
if(a.type=='applybill' && nus){
var url='index.php?a=lum&m=input&d=flow&num='+nus+'&show=we';
js.location(url);return;
}
if(!ids)return;
this.tempid = ids;
this.tempnum = nus;
this.temparr = {oi:oi};
var da = [{name:'详情',lx:998,oi:oi}];
var subdata = this.suboptmenu[''+nus+'_'+ids+''];
if(typeof(subdata)=='object'){
for(i=0;i<subdata.length;i++)da.push(subdata[i]);
}else{
da.push({name:'<img src="images/loadings.gif" align="absmiddle"> 加载菜单中...',lx:999});
this.loadoptnum(nus,ids);
}
js.showmenu({
data:da,
width:150,
onclick:function(d){
yy.showmenuclick(d);
}
});
},
loadoptnum:function(nus,id){
js.ajax('agent','getoptnum',{num:nus,mid:id},function(ret){
yy.suboptmenu[''+nus+'_'+id+'']=ret;
yy.showmenu(yy.temparr.oi);
},'none',false,function(estr){
yy.suboptmenu[''+nus+'_'+id+'']=[];
yy.showmenu(yy.temparr.oi);
});
},
showmenuclick:function(d){
d.num=this.num;d.mid=this.tempid;
d.modenum = this.tempnum;
var lx = d.lx;if(!lx)lx=0;
if(lx==999)return;
if(lx==998){this.xiang(d.oi);return;}
if(lx==996){this.xiang(this.temparr.oi);return;}
this.changdatsss = d;
if(lx==2 || lx==3){
var clx='changeuser';if(lx==3)clx='changeusercheck';
$('body').chnageuser({
'changetype':clx,
'titlebool':get('header_title'),
'onselect':function(sna,sid){
yy.xuanuserok(sna,sid);
}
});
return;
}
if(lx==1 || lx==9 || lx==10 || lx==13 || lx==15 || lx==16 || lx==17){
var bts = (d.issm==1)?'必填':'选填';
js.wx.prompt(d.name,'请输入['+d.name+']说明('+bts+'):',function(text){
if(!text && d.issm==1){
js.msg('msg','没有输入['+d.name+']说明');
}else{
yy.showmenuclicks(d, text);
}
});
return;
}
//添加提醒设置
if(lx==14){
var url='index.php?a=lum&m=input&d=flow&num=remind&mid='+d.djmid+'&def_modenum='+d.modenum+'&def_mid='+d.mid+'&def_explain=basejm_'+jm.base64encode(d.smcont)+'&show=we';
js.location(url);
return;
}
if(lx==11){
var url='index.php?a=lum&m=input&d=flow&num='+d.modenum+'&mid='+d.mid+'&show=we';
js.location(url);
return;
}
this.showmenuclicks(d,'');
},
xuanuserok:function(nas,sid){
if(!sid)return;
var d = this.changdatsss,sm='';
d.changename = nas;
d.changenameid = sid;
this.showmenuclicks(d,sm);
},
showmenuclicks:function(d, sm){
if(!sm)sm='';
d.sm = sm;
for(var i in d)if(d[i]==null)d[i]='';
js.ajax('index','yyoptmenu',d,function(ret){
yy.suboptmenu[''+d.modenum+'_'+d.mid+'']=false;
yy.getdata(yy.nowevent, 1);
});
},
showdata:function(a){
this.overend = true;
var s='',i,len=a.rows.length,d,st='',oi;
$('#showblank').remove();
$('#notrecord').remove();
if(typeof(a.stotal)=='object')this._showstotal(a.stotal);
if(a.page==1){
this.showobj.html('');
this.data=[];
}
for(i=0;i<len;i++){
d=a.rows[i];
oi=this.data.push(d);
if(d.showtype=='line' && d.title){
s='<div class="contline">'+d.title+'</div>';
}else{
if(!d.statuscolor)d.statuscolor='';
st='';
if(d.ishui==1)st='color:#aaaaaa;';
s='<div style="'+st+'" class="r-border contlist">';
if(d.title){
if(d.face){
s+='<div onclick="yy.showmenu('+oi+')" class="face"><img src="'+d.face+'" align="absmiddle">'+d.title+'</div>';
}else{
s+='<div onclick="yy.showmenu('+oi+')" class="tit">'+d.title+'</div>';
}
}
if(d.optdt)s+='<div class="dt">'+d.optdt+'</div>';
if(d.picurl)s+='<div onclick="yy.showmenu('+oi+')" class="imgs"><img src="'+d.picurl+'" width="100%"></div>';
if(d.cont)s+='<div onclick="yy.showmenu('+oi+')" class="cont">'+d.cont.replace(/\n/g,'<br>')+'</div>';
if(d.id && d.modenum){
s+='<div class="xq r-border-t"><font onclick="yy.showmenu('+oi+')">操作<i class="icon-angle-down"></i></font><span onclick="yy.xiang('+oi+')">详情>></span>';
s+='</div>';
}
if(d.statustext)s+='<div style="background-color:'+d.statuscolor+';opacity:0.7" class="zt">'+d.statustext+'</div>';
s+='</div>';
}
this.showobj.append(s);
}
var count=a.count;
if(count==0)count=len;
if(count>0){
this.nowpage = a.page;
s = '<div class="showblank" id="showblank">共'+count+'条记录';
if(a.maxpage>1)s+=',当前'+a.maxpage+'/'+a.page+'页';
if(a.page<a.maxpage){
s+=', <a id="showblankss" onclick="yy.regetdata(this,'+(a.page+1)+')" href="javascript:;">点击加载</a>';
this.overend = false;
}
s+= '</div>';
this.showobj.append(s);
if(a.count==0)$('#showblank').html('');
}else{
this.showobj.html('<div class="notrecord" id="notrecord">暂无记录</div>');
}
if(this.touchobj)this.touchobj.onupok();
},
onupbefore:function(){
if(this.overend)return false;
var a={
'msg':'↑ 继续上拉加载第'+(this.nowpage+1)+'页',
'msgok' : '<a id="showblankss">↓ 释放后</a>加载第'+(yy.nowpage+1)+'页...'
};
return a;
},
scrollEndevent:function(){
yy.regetdata(get('showblankss'),yy.nowpage+1);
}
} |
var Q = require('../libs/q'),
Marker = require('./map/Marker'),
dataManager = require('../core/DataManager'),
domSelector = require('../utils/domSelector'),
mapContainerEl = domSelector.first(document, 'mapContainer'),
hasMarkers = false,
body = document.body,
calculator,
markers,
map;
var MAP_STYLE = [
{
'stylers': [
{ 'visibility': 'off' }
]
},
{
'featureType': 'water',
'stylers': [
{ 'color': '#1a181a' },
{ 'visibility': 'on' }
]
},
{
'featureType': 'landscape',
'stylers': [
{ 'visibility': 'simplified' },
{ 'color': '#272427' }
]
},
{
'featureType': 'road',
'stylers': [
{ 'visibility': 'simplified' },
{ 'color': '#312e32' }
]
},
{
'elementType': 'labels',
'stylers': [
{ 'visibility': 'off' }
]
}
],
MAP_OPTIONS = {
maxZoom:18,
minZoom:3,
zoom: 14,
center: new google.maps.LatLng(0,0),
mapTypeId: google.maps.MapTypeId.ROADMAP,
backgroundColor: '#1a181a',
disableDefaultUI: true,
noClear:true
};
exports.getMap = function() { return map; };
exports.init = function() {
var deferred = Q.defer();
map = new google.maps.Map(mapContainerEl,MAP_OPTIONS);
calculator = new Calculator(map);
//styling the map
var styleOptions = {
name: 'SCP'
};
var mapType = new google.maps.StyledMapType(MAP_STYLE, styleOptions);
map.mapTypes.set('SCP', mapType);
map.setMapTypeId('SCP');
// ugly hack to improve Google logo positioning
var idleListener = google.maps.event.addListener(map, 'idle', function() {
var anchorEls = mapContainerEl.getElementsByTagName('a'),
logoParent,
anchorImageEls,
logoEl;
if(anchorEls && anchorEls.length > 0) {
logoParent = anchorEls[0];
anchorImageEls = logoParent.getElementsByTagName('img');
if(anchorImageEls && anchorImageEls.length > 0) {
logoEl = anchorImageEls[0];
logoEl.classList.add('js-scrubEl', 'is-googleLogo');
google.maps.event.removeListener(idleListener);
}
}
var gmnoprintEls = domSelector.all(mapContainerEl, 'gmnoprint');
if(gmnoprintEls.length > 0) {
gmnoprintEls.forEach(function(gmnoprintEl){
gmnoprintEl.classList.add('js-scrubEl');
});
}
if(hasMarkers === false) {
hasMarkers = true;
addMarkers(dataManager.getLocationList('all'));
}
deferred.resolve();
});
return deferred.promise;
};
exports.hide = function() {
body.appendChild(mapContainerEl);
};
exports.show = function(parentEl) {
parentEl.appendChild(mapContainerEl);
};
exports.zoomIn = function() {
map.setZoom(map.getZoom()+1);
};
exports.zoomOut = function() {
map.setZoom(map.getZoom()-1);
};
exports.centerMap = function(location, isPrimaryView, isAnimated) {
var position = location.position,
latLng = new google.maps.LatLng(position[0],position[1]);
var projection = calculator.getProjection(),
containerPixel = projection.fromLatLngToDivPixel(latLng);
if(isPrimaryView) {
containerPixel.x += 90;
} else {
var width = mapContainerEl.offsetWidth,
center = width/ 2,
centerTarget = 270 + 90,
centerOffset = center - centerTarget;
containerPixel.x += centerOffset;
}
var offsetLatLng = projection.fromDivPixelToLatLng(containerPixel);
if(isAnimated) {
map.panTo(offsetLatLng);
} else {
map.setCenter(offsetLatLng);
}
};
function addMarkers(locations) {
var currentLocation = dataManager.getCurrentLocation(),
marker,position,latLng;
markers = [];
var sortedLocations = locations.sort(function(a, b){
if (a.position[0] > b.position[0]) {
return -1;
}
if (a.position[0] < b.position[0]) {
return 1;
}
return 0;
});
sortedLocations.forEach(function(location){
position = location.position;
latLng = new google.maps.LatLng(position[0],position[1]);
marker = new Marker(location.index, location.number, latLng, map);
if(currentLocation.index === location.index) {
marker.activate();
} else {
marker.deactivate();
}
markers.push(marker);
});
}
function Calculator(map) {
this.div_ = null;
this.setMap(map);
}
Calculator.prototype = new google.maps.OverlayView();
Calculator.prototype.onAdd = function(){};
Calculator.prototype.draw = function(){}; |
(function () {
"use strict";
var pageItems = [{ title: 'page 1 item 1' }, { title: 'page 1 item 2' }, { title: 'page 1 item 2' }];
WinJS.UI.Pages.define("./demos/navigation/childviewflyout/picker/page1/page1.html", {
ready: function (element, options) {
var page = this;
this.listitems = element.querySelector('#listitems').winControl;
this.listitems.itemDataSource = new WinJS.Binding.List(pageItems).dataSource;
this.listitems.oniteminvoked = function (arg) {
arg.detail.itemPromise.done(function (item) {
page.close(item.data);
});
}
},
openPage: function () {
var page = this;
//parent navigator can be fetched
var nav = WinJSContrib.UI.parentChildView(this.element);
nav.pick('./demos/navigation/childviewflyout/picker/page2/page2.html').done(function (arg) {
if (arg.completed) {
$('#pickResult', page.element).text('you picked ' + arg.data.title);
} else {
$('#pickResult', page.element).text('picking cancled');
}
});
},
cancelPicking: function () {
//cancel picking
this.cancel()
}
});
})();
|
define(['underscore'],function(_){
'use strict';
var Tasks;
Tasks = (function(){
var MIN_AGE = 18,
MAX_AGE = 24;
function filterStudentsByName(studnets){
var result = _.chain(studnets)
.filter(function(student){return student.firstName.toLowerCase() < student.lastName.toLowerCase()})
.sortBy(function(student){return student.fullName();})
.value()
.reverse();
return result;
}
function filterStudentsByAge(students){
var result = _.chain(students)
.filter(function(student){return student.age >=MIN_AGE && student.age<=MAX_AGE})
.map(function(student) { return {firstName : student.firstName , lastName : student.lastName}})
.value()
return result;
}
function getStudentWithHighestMarks(students){
var result = _.max(students,function(student){
var totalMarks;
totalMarks = _.reduce(student.marks,function(memo,mark){
return memo+mark;
},0);
return totalMarks;
})
return result;
}
function groupAnimalsBySpeciesAndSortByLegs(animals){
var result = _.chain(animals)
.groupBy('species')
.sortBy(function(group){
return group[0].legs;
})
.value();
return result;
}
function totalNumberOfLegs(animals){
var result = _.reduce(animals,function(memo,animal){
return memo+animal.legs;
},0);
return result;
}
function mostPopularAuthor(books){
var result,
counts,
max;
counts = _.countBy(books,'author');
max = _.max(counts);
// This way it works if there are more than one author with the max number of books;
result = _.chain(counts)
.pairs()
.filter(function(author){
return author[1] == max;
})
.map(function(author){
return {
name: author[0],
books: author[1]
}
})
.value();
return result;
}
function findMostCommonNames(people,nameType){
var nameGroup,
maxNameCount,
mostCommonName;
nameGroup = _.groupBy(people,nameType);
maxNameCount= _.max(nameGroup,function(sameName){return sameName.length}).length;
mostCommonName = _.chain(nameGroup)
.filter(function(name){return name.length===maxNameCount })
.map(function(name){return {
nameType : nameType,
name: name[0][nameType],
count: 2
}})
.value();
return mostCommonName;
}
function mostCommonNames(people){
return _.union(findMostCommonNames(people,'lastName'),findMostCommonNames(people,'firstName'));
}
return {
filterStudentsByName : filterStudentsByName,
filterStudentsByAge : filterStudentsByAge,
getStudentWithHighestMarks : getStudentWithHighestMarks,
groupAnimalsBySpeciesAndSortByLegs: groupAnimalsBySpeciesAndSortByLegs,
totalNumberOfLegs: totalNumberOfLegs,
mostPopularAuthor: mostPopularAuthor,
mostCommonNames: mostCommonNames,
}
}());
return Tasks;
}); |
var Type = require("@kaoscript/runtime").Type;
module.exports = function() {
class Foo {
constructor() {
this.__ks_init();
this.__ks_cons(arguments);
}
__ks_init() {
}
__ks_cons_0(foo) {
if(arguments.length < 2) {
throw new SyntaxError("Wrong number of arguments (" + arguments.length + " for 2)");
}
if(foo === void 0 || foo === null) {
throw new TypeError("'foo' is not nullable");
}
let __ks_i = 0;
let __ks__;
let bar = arguments.length > 2 && (__ks__ = arguments[++__ks_i]) !== void 0 ? __ks__ : null;
let qux = arguments[++__ks_i];
if(qux === void 0 || qux === null) {
throw new TypeError("'qux' is not nullable");
}
}
__ks_cons_1(foo) {
if(arguments.length < 3) {
throw new SyntaxError("Wrong number of arguments (" + arguments.length + " for 3)");
}
if(foo === void 0 || foo === null) {
throw new TypeError("'foo' is not nullable");
}
let __ks_i = 0;
let __ks__;
let bar = arguments.length > 3 && (__ks__ = arguments[++__ks_i]) !== void 0 ? __ks__ : null;
let qux = arguments[++__ks_i];
if(qux === void 0 || qux === null) {
throw new TypeError("'qux' is not nullable");
}
else if(!Type.isString(qux)) {
throw new TypeError("'qux' is not of type 'String'");
}
let corge = arguments[++__ks_i];
if(corge === void 0 || corge === null) {
throw new TypeError("'corge' is not nullable");
}
}
__ks_cons(args) {
if(args.length === 2) {
Foo.prototype.__ks_cons_0.apply(this, args);
}
else if(args.length === 3) {
if(Type.isString(args[1])) {
Foo.prototype.__ks_cons_1.apply(this, args);
}
else {
Foo.prototype.__ks_cons_0.apply(this, args);
}
}
else if(args.length === 4) {
Foo.prototype.__ks_cons_1.apply(this, args);
}
else {
throw new SyntaxError("Wrong number of arguments");
}
}
}
}; |
var io = require('socket.io')(8008);
var TwitterStreamChannels = require('twitter-stream-channels');
var credentials = require('./twitter.credentials.json');
var timeout = 500000;
var client = new TwitterStreamChannels(credentials);
var connected = false;
var channels = {
"dev" : ['javascript','nodejs','jquery','backbone','emberjs','meteorjs','html5','css','angularjs'],
"wow" : ['warcraft','wowselfie'],
"siroop" : ['siroop','siropmeeting'],
"twd" : ['TWDbeiRTL2'],
"traumfraugesucht": ['Traumfraugesucht'],
};
var stream = client.streamChannels({track:channels});
var count = 0;
var tweetdata;
var tweeturl;
var isRetweeted;
var imagelink;
stream.on('connect', function() {
console.log('> attempting to connect to twitter');
});
stream.on('connected', function() {
if(connected === false){
console.log('> twitter emit : client connected ');
connected = true;
}
});
stream.on('disconnect', function() {
console.log('> twitter emit : disconnect');
connected = false;
});
stream.on('reconnect', function() {
console.log('> twitter emit : reconnect');
});
stream.on('warning', function() {
console.log('> twitter emit : warning');
});
/*stream.on('channels/languages',function(tweet){
console.log('>languages ',tweet.$channels,tweet.$keywords,tweet.text);//any tweet with 'javascript','php','java','python','perl'
count++;
});
stream.on('channels/js-frameworks',function(tweet){
console.log('>frameworks ',tweet.$channels,tweet.$keywords,tweet.text);//any tweet with 'angularjs','jquery','backbone','emberjs'
count++;
});
stream.on('channels/web',function(tweet){
console.log('>web: ',tweet.$channels,tweet.$keywords,tweet.text);//any tweet with 'javascript','nodejs','html5','css','angularjs'
count++;
});*/
stream.on('channels/wow',function(tweet){
isRetweeted=false;
//console.log('>wow: ',tweet.$channels,tweet.$keywords,tweet.text);//any tweet with 'warcraft','wowselfie'
if (tweet.entities.media){
tweeturl="https://www.twitter.com/"+tweet.user.screen_name+"/status/"+tweet.id_str;
if (tweet.retweeted_status){
isRetweeted=true;
}
tweetdata = {
"picture":tweet.entities.media[0].media_url,
"user": tweet.user.screen_name,
"tweettext": tweet.text,
"retweeted": isRetweeted,
"tweetlink": tweeturl
};
//console.log('Id of the media');
//console.log(tweet.entities.media[0].id);
//console.log('Here comes the url to the picture');
//console.log(tweet.entities.media[0].media_url);
//console.log(tweetdata);
io.emit('wow',tweetdata);
}
/*count++;*/
});
stream.on('channels/siroop',function(tweet){
if (tweet.entities.media){
imagelink = tweet.entities.media[0].media_url
}else{
imagelink = 'http://www.rttweets.gate107.com/img/twitterlogo.png';
}
tweeturl="https://www.twitter.com/"+tweet.user.screen_name+"/status/"+tweet.id_str;
tweetdata = {
"picture":imagelink,
"user": tweet.user.screen_name,
"tweettext": tweet.text,
"retweeted": isRetweeted,
"tweetlink": tweeturl
};
io.emit('siroop',tweetdata);
});
stream.on('channels/dev',function(tweet){
if (tweet.entities.media){
imagelink = tweet.entities.media[0].media_url
}else{
imagelink = 'http://www.rttweets.gate107.com/img/twitterlogo.png';
}
tweeturl="https://www.twitter.com/"+tweet.user.screen_name+"/status/"+tweet.id_str;
tweetdata = {
"picture":imagelink,
"user": tweet.user.screen_name,
"tweettext": tweet.text,
"retweeted": isRetweeted,
"tweetlink": tweeturl
};
io.emit('dev',tweetdata);
});
stream.on('channels/twd',function(tweet){
if (tweet.entities.media){
imagelink = tweet.entities.media[0].media_url
}else{
imagelink = 'http://www.rttweets.gate107.com/img/twitterlogo.png';
}
tweeturl="https://www.twitter.com/"+tweet.user.screen_name+"/status/"+tweet.id_str;
tweetdata = {
"picture":imagelink,
"user": tweet.user.screen_name,
"tweettext": tweet.text,
"retweeted": isRetweeted,
"tweetlink": tweeturl
};
io.emit('twd',tweetdata);
});
stream.on('channels/traumfraugesucht',function(tweet){
if (tweet.entities.media){
imagelink = tweet.entities.media[0].media_url
}else{
imagelink = 'http://www.rttweets.gate107.com/img/twitterlogo.png';
}
tweeturl="https://www.twitter.com/"+tweet.user.screen_name+"/status/"+tweet.id_str;
tweetdata = {
"picture":imagelink,
"user": tweet.user.screen_name,
"tweettext": tweet.text,
"retweeted": isRetweeted,
"tweetlink": tweeturl
};
io.emit('traumfraugesucht',tweetdata);
});
/*setTimeout(function() {
stream.stop();
console.log('> stopped stream '+count+' tweets captured in '+timeout+'ms');
process.exit();
}, timeout);*/
|
define(['app', 'text!./resource-mobilisation.html', "lodash"], function(app, template, _){
app.directive('viewResourceMobilisation', [function () {
return {
restrict : 'E',
template : template,
replace : true,
transclude : false,
scope: {
document: "=ngModel",
locale : "=",
target : "@linkTarget",
allowDrafts : "@"
},
link : function ($scope)
{
$scope.options = {
multipliers : [{identifier:'units', title: {en:'in units'}}, {identifier:'thousands', title: {en:'in thousands'}}, {identifier:'millions', title: {en:'in millions'}}],
methodology : [{identifier:'oecd_dac', title: {en:'OECD DAC Rio markers'}}, {identifier:'other', title: {en:'Other' }}],
measures : [{identifier:'no', title: {en:'No' }}, {identifier:'some', title: {en:'Some measures taken'}}, {identifier:'comprehensive', title: {en:'Comprehensive measures taken'}}],
inclusions : [{identifier:'notyet', title: {en:'Not yet stared'}},
{identifier:'some', title: {en:'Some inclusion achieved'}},
{identifier:'comprehensive', title: {en:'Comprehensive inclusion'}}],
assessments : [{identifier:'notnecessary', title: {en:'No such assessment necessary'}},
{identifier:'notyet', title: {en:'Not yet started'}},
{identifier:'some', title: {en:'Some assessments undertaken'}},
{identifier:'comprehensive', title: {en:'Comprehensive assessments undertaken'}}],
domesticMethodology:[{identifier:'cmfeccabc', title: {en:'Conceptual and Methodological Framework for Evaluating the Contribution of Collective Action to Biodiversity Conservation'}},
{identifier:'other', title: {en:'Other'}}],
yesNo : [{identifier:false, title: {en:'No' } },{identifier:true, title: {en:'Yes'}}]
};
//==================================
//
//==================================
$scope.totalAverageAmount = function(){
var odaAverage = 0;
var oofAverage = 0;
var otherAverage = 0;
if($scope.document && $scope.document.internationalResources && $scope.document.internationalResources.baselineData && $scope.document.internationalResources.baselineData.baselineFlows)
{
odaAverage = $scope.typeAverageAmount($scope.document.internationalResources.baselineData.baselineFlows,'odaAmount');
oofAverage = $scope.typeAverageAmount($scope.document.internationalResources.baselineData.baselineFlows,'oofAmount');
otherAverage = $scope.typeAverageAmount($scope.document.internationalResources.baselineData.baselineFlows,'otherAmount');
}
return parseInt(odaAverage)+parseInt(oofAverage)+parseInt(otherAverage);
};
//==================================
//
//==================================
$scope.typeAverageAmount = function(flows, type){
if(!flows) return 0;
var items;
if(_.isEmpty(_.last(flows)) || !_.last(flows))
items = _.initial(_.pluck(flows, type));
else
items = _.pluck(flows, type);
if(items.length===0)
return 0;
var sum = _.reduce(_.compact(items), function(memo, num){ return memo + parseInt(num || 0); }, 0);
return Math.round(sum/items.length);
};
//==================================
//
//==================================
$scope.confidenceAverage = function (resources) {
var values = _.compact(_.map(resources, function (resource) {
if (resource && resource.confidenceLevel && resource.confidenceLevel.identifier == "D8BC6348-D1F9-4DA4-A8C0-7AE149939ABE") return 3; //high
if (resource && resource.confidenceLevel && resource.confidenceLevel.identifier == "42526EE6-68F3-4E8A-BC2B-3BE60DA2EB32") return 2; //medium
if (resource && resource.confidenceLevel && resource.confidenceLevel.identifier == "6FBEDE59-88DB-45FB-AACB-13C68406BD67") return 1; //low
return 0;
}));
var value = 0;
if(values.length) {
value = Math.round(_.reduce(values, function(memo, value) { return memo + value; }) / values.length);
}
if ( value == 3) return "High";
if ( value == 2) return "Medium";
if ( value == 1) return "Low";
return "No value selected";
};
//==================================
//
//==================================
$scope.getFundingGapYear = function(year){
if(!year) return 0;
if($scope.document && $scope.document.fundingNeedsData && $scope.document.fundingNeedsData.annualEstimates){
var estimates = $scope.document.fundingNeedsData.annualEstimates;
var estimate = _.findWhere(estimates, {year:year});
if(estimate && estimate.fundingGapAmount)
return estimate.fundingGapAmount;
}
return 0;
};
//==================================
//
//==================================
$scope.isEmpty = function (item) {
return _.isEmpty(item);
};
//==================================
//
//==================================
$scope.getNationalPlansSourcesTotal = function(member, year){
if(!year || !member) return 0;
if($scope.document && $scope.document.nationalPlansData && $scope.document.nationalPlansData[member]){
var prop = "amount"+year;
var items;
var sources = angular.fromJson($scope.document.nationalPlansData[member]);//jshint ignore:line
if(_.isEmpty(_.last(sources)))
items = _.initial(sources);
items = _.pluck(sources, prop);
var sum = 0;
_.map(_.compact(items), function(num){
sum = sum + parseInt(num)||0;
});
return sum;
}
return 0;
};
//==================================
//
//==================================
$scope.getNationalPlansRemainingGapByYear = function(year){
if(!year) return 0;
return $scope.getFundingGapYear(year) - ($scope.getNationalPlansSourcesTotal('domesticSources', year) + $scope.getNationalPlansSourcesTotal('internationalSources', year)) ;
};
//==================================
//
//==================================
$scope.annualEstimatesHasYear = function (year) {
if(!year) return false;
if($scope.document && $scope.document.fundingNeedsData && $scope.document.fundingNeedsData.annualEstimates){
var estimates = $scope.document.fundingNeedsData.annualEstimates;
var estimate = _.findWhere(estimates, {year:year});
if(estimate)
return true;
}
return false;
};
//==================================
//
//==================================
$scope.hasValue = function(val){
if(val === false || val === true)
return true;
return false;
};
}
};
}]);
});
|
/// <reference path='./Scripts/DlhSoft.ProjectData.PertChart.HTML.Controls.d.ts'/>
var NetworkDiagramView = DlhSoft.Controls.Pert.NetworkDiagramView;
// Query string syntax: ?theme
// Supported themes: Default, Generic-bright, Generic-blue, DlhSoft-gray, Purple-green, Steel-blue, Dark-black, Cyan-green, Blue-navy, Orange-brown, Teal-green, Purple-beige, Gray-blue, Aero.
var queryString = window.location.search;
var theme = queryString ? queryString.substr(1) : null;
// Retrieve and store the control element for reference purposes.
var networkDiagramViewElement = document.querySelector('#networkDiagramView');
var date = new Date(), year = date.getFullYear(), month = date.getMonth(), secondDuration = 1000, minuteDuration = 60 * secondDuration, hourDuration = 60 * minuteDuration;
var items = [
{ content: 'Start milestone', displayedText: 'Start', isMilestone: true, earlyStart: new Date(year, month, 2, 8, 0, 0), earlyFinish: new Date(year, month, 2, 8, 0, 0), lateStart: new Date(year, month, 2, 8, 0, 0), lateFinish: new Date(year, month, 2, 8, 0, 0) },
{ content: 'First task', displayedText: 'Task 1', effort: 8 * hourDuration, earlyStart: new Date(year, month, 2, 8, 0, 0), earlyFinish: new Date(year, month, 2, 16, 0, 0), lateStart: new Date(year, month, 2, 8, 0, 0), lateFinish: new Date(year, month, 2, 8, 0, 0), slack: 0 },
{ content: 'Second task', displayedText: 'Task 2', effort: 4 * hourDuration, earlyStart: new Date(year, month, 2, 8, 0, 0), earlyFinish: new Date(year, month, 2, 12, 0, 0), lateStart: new Date(year, month, 2, 12, 0, 0), lateFinish: new Date(year, month, 2, 8, 0, 0), slack: 4 * hourDuration },
{ content: 'Third task', displayedText: 'Task 3', effort: 16 * hourDuration, earlyStart: new Date(year, month, 3, 8, 0, 0), earlyFinish: new Date(year, month, 4, 16, 0, 0), lateStart: new Date(year, month, 3, 8, 0, 0), lateFinish: new Date(year, month, 4, 16, 0, 0), slack: 0 },
{ content: 'Fourth task', displayedText: 'Task 4', effort: 4 * hourDuration, earlyStart: new Date(year, month, 3, 8, 0, 0), earlyFinish: new Date(year, month, 3, 12, 0, 0), lateStart: new Date(year, month, 4, 12, 0, 0), lateFinish: new Date(year, month, 4, 16, 0, 0), slack: 12 * hourDuration },
{ content: 'Fifth task (middle milestone)', displayedText: 'Task 5', isMilestone: true, effort: 12 * hourDuration, earlyStart: new Date(year, month, 5, 8, 0, 0), earlyFinish: new Date(year, month, 6, 12, 0, 0), lateStart: new Date(year, month, 5, 8, 0, 0), lateFinish: new Date(year, month, 6, 12, 0, 0), slack: 0 },
{ content: 'Sixth task', displayedText: 'Task 6', effort: 48 * hourDuration, earlyStart: new Date(year, month, 6, 12, 0, 0), earlyFinish: new Date(year, month, 12, 12, 0, 0), lateStart: new Date(year, month, 6, 12, 0, 0), lateFinish: new Date(year, month, 12, 12, 0, 0), slack: 0 },
{ content: 'Seventh task', displayedText: 'Task 7', effort: 20 * hourDuration, earlyStart: new Date(year, month, 6, 12, 0, 0), earlyFinish: new Date(year, month, 8, 16, 0, 0), lateStart: new Date(year, month, 10, 8, 0, 0), lateFinish: new Date(year, month, 12, 12, 0, 0), slack: 28 * hourDuration },
{ content: 'Finish milestone', displayedText: 'Finish', isMilestone: true, earlyStart: new Date(year, month, 12, 12, 0, 0), earlyFinish: new Date(year, month, 12, 12, 0, 0), lateStart: new Date(year, month, 12, 12, 0, 0), lateFinish: new Date(year, month, 12, 12, 0, 0) }];
items[1].predecessors = [{ item: items[0] }];
items[2].predecessors = [{ item: items[0] }];
items[3].predecessors = [{ item: items[1] }, { item: items[2] }];
items[4].predecessors = [{ item: items[1] }];
items[5].predecessors = [{ item: items[3] }, { item: items[4] }];
items[6].predecessors = [{ item: items[5] }];
items[7].predecessors = [{ item: items[5] }];
items[8].predecessors = [{ item: items[6] }, { item: items[7] }];
// Set up appearance and style settings.
var settings = {
containerClass: 'container',
shapeClass: 'shape',
milestoneClass: 'milestone',
dependencyLineClass: 'dependencyLine'
};
// Optionally, initialize custom theme and templates (themes.js, templates.js).
initializePertChartTheme(settings, theme);
initializePertChartTemplates(settings, theme);
// Initialize the component.
var networkDiagramView = DlhSoft.Controls.Pert.NetworkDiagramView.initialize(networkDiagramViewElement, items, settings);
//# sourceMappingURL=app.js.map |
/**
* React Static Boilerplate
* https://github.com/kriasoft/react-static-boilerplate
*
* Copyright © 2015-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import recommendedPages from '../../relatedPages.json';
import Layout from '../../../components/Layout';
import About from '../../../components/About';
import Link from '../../../components/Link';
import LinkExternal from '../../../components/LinkExternal';
import HorizontalScroll from '../../../components/HorizontalScroll';
import ImageCompare from '../../../components/ImageCompare';
import Iphone from '../../../components/Iphone';
import UpNext from '../../../components/UpNext';
import LazyLoader from '../../../components/LazyLoader';
import s from './styles.css';
import b from '../../styles/variables.css'
import g from '../../styles/grid.css';
import v from '../../styles/aesthetics.css';
import {title, html} from './index.md';
/* Images for this Page */
import before2796w from '../../assets/images/kit-pdp-desktop-before-2796w.jpg';
import before1440w from '../../assets/images/kit-pdp-desktop-before-1440w.jpg';
import before960w from '../../assets/images/kit-pdp-desktop-before-960w.jpg';
import before494w from '../../assets/images/kit-pdp-desktop-before-494w.jpg';
import before320w from '../../assets/images/kit-pdp-desktop-before-320w.jpg';
import beforePlaceholder from '../../assets/images/kit-pdp-desktop-before-20w.jpg';
import after2796w from '../../assets/images/kit-pdp-desktop-after-2796w.jpg';
import after1440w from '../../assets/images/kit-pdp-desktop-after-1440w.jpg';
import after960w from '../../assets/images/kit-pdp-desktop-after-960w.jpg';
import after494w from '../../assets/images/kit-pdp-desktop-after-494w.jpg';
import after320w from '../../assets/images/kit-pdp-desktop-after-320w.jpg';
import afterPlaceholder from '../../assets/images/kit-pdp-desktop-after-20w.jpg';
import flowAllClasses from '../../assets/images/flow-all-classes.svg';
import flowAllKits from '../../assets/images/flow-all-kits.svg';
import flowArrow from '../../assets/images/flow-arrow-right.svg';
import flowSingleClass from '../../assets/images/flow-single-class.svg';
import flowSingleKit from '../../assets/images/flow-single-Kit.svg';
import wireframeKit from '../../assets/images/kit-wireframe.svg';
import calloutPanel from '../../assets/images/callout-panel.svg';
import wireframeClass from '../../assets/images/class-wireframe.svg';
import addToCartPanel from '../../assets/images/add-to-cart.svg';
import userTestPlaceholder from '../../assets/images/user-test-20w.jpg';
import userTestPoster from '../../assets/images/user-test-928w.jpg';
import userTestWebm from '../../assets/images/user-test.webm';
import userTestMp4 from '../../assets/images/user-test.mp4';
import iphoneImage from '../../assets/images/[email protected]';
class ImprovingPurchaseProcessPage extends React.Component {
static defaultProps = {
title: recommendedPages[0].title,
recommendedPageFirst: {title: ''},
recommendedPageSecond: {}
};
componentDidMount() {
document.title = recommendedPages[0].title + ' | Zane Riley';
}
render() {
const {title, about, role, result, readingLength} = recommendedPages[0];
const after = {
placeholder: afterPlaceholder,
images: after320w + ' 320w,' + after494w + ' 494w,' + after960w + ' 960w,' + after1440w + ' 1440w,' + after2796w + ' 2796w',
url: after2796w,
alt: "The updated kit web page showing a cleaner and more simple user interface.",
}
const before = {
placeholder: beforePlaceholder,
images: before320w + ' 320w,' + before494w + ' 494w,' + before960w + ' 960w,' + before1440w + ' 1440w,' + before2796w + ' 2796w',
url: before2796w,
alt: "The original kit web page showing a busier layout with an unclear visual hierachy.",
}
return (
<Layout className={`${g.gPaddingTopLarge}`} breadCrumbs="Case Study" recommendedPageFirst={recommendedPages[1]} recommendedPageSecond={recommendedPages[2]}>
<About title={title} about={about} role={role} result={result} readingLength={readingLength}/>
<figure className={`${g.maxWidth} ${g.gMarginTopLarge}`}>
<ImageCompare before={before} after={after}/>
<figcaption>Before and after designs of the <span className={`${g.noWrap}`}>Kit page.</span></figcaption>
</figure>
<div className={`${g.maxWidth} ${g.gMarginTopLarge}`}>
<p className={`${g.g9m} ${g.g6l} ${g.center} ${v.dropCap}`}>I was asked to increase the attach rate between
Brit + Co’s two main products – Classes, offering instruction on topics like calligraphy, and Kits, supplies for projects <span className={`${g.noWrap}`}>and Classes.</span></p>
<p className={`${g.g9m} ${g.g6l} ${g.center} `}>When measuring the attach rate, it’s usually clear which product is primary and which is secondary. For example, smart phones are a primary product. Phone accessories, like cases, would be secondary. For Classes and Kits, however, the primary product wasn’t quite <span className={`${g.noWrap}`}>so obvious.</span></p>
<p className={`${g.g9m} ${g.g6l} ${g.center}`}>To increase the attach rate, we first had to understand which of our products was primary, and which one <span className={`${g.noWrap}`}>was secondary.</span></p>
<p className={`${g.g9m} ${g.g6l} ${g.center}`}>The relationship between specific Classes and Kits varied wildly. Some products worked together seamlessly, like the Calligraphy Class and Calligraphy Kit. Other pairings were less straightforward. Some classes had no kit, and some Kits had no <span className={`${g.noWrap}`}>matching class.</span></p>
<blockquote className={`${g.g5l} ${g.center} ${g.floatRightM}`}>To increase the attach rate, we first had to understand which of our products was primary and which one was secondary.
</blockquote>
<p className={`${g.g9m} ${g.g6l} ${g.center}`}>We couldn’t lock ourselves into a single pricing strategy while the company was exploring product/market fit. We would need to increase the attach rate without simplifying pricing or changing products.</p>
<p className={`${g.g9m} ${g.g6l} ${g.center}`}>One interesting piece of data helped shape our solution: How users viewed each product.</p>
</div>
<div className={`${g.maxWidth}`}>
<h2 className={`${g.g9m} ${g.g6l} ${g.center}`}>User Flows</h2>
<p className={`${g.g9m} ${g.g6l} ${g.center}`}>Users took different paths through the site depending on which product they were initially looking at. Take a look at the two flows below:
</p>
</div>
<div className={`${g.maxWidth}`}>
<h3 className={`${g.g9m} ${g.g6l} ${g.center}`}>How People View Classes</h3>
</div>
<figure className={`${g.gMarginTopSmall}`}>
<HorizontalScroll>
<div className={`${g.g3Max} ${g.textCenter} ${g.gNoMarginTop} ${g.gMarginLeftSmallest}`}>
<p>All Classes</p>
<div className={`${g.gMarginTopSmall} ${g.thrashPreventerSquare}`}>
<img src={flowAllClasses} className={`${g.gPositionAbsolute}`} />
</div>
</div>
<div className={`${g.textCenter} ${g.gMarginLeftSmallest}`}>
<img src={flowArrow} />
</div>
<div className={`${g.g3Max} ${g.textCenter} ${g.gNoMarginTop} ${g.gMarginLeftSmallest}`}>
<p>Single Class</p>
<div className={`${g.gMarginTopSmall} ${g.thrashPreventerSquare}`}>
<img src={flowSingleClass} className={`${g.gPositionAbsolute}`} />
</div>
</div>
<div className={`${g.textCenter} ${g.gMarginLeftSmallest}`}>
<img src={flowArrow} />
</div>
<div className={`${g.g3Max} ${g.textCenter} ${g.gNoMarginTop} ${g.gMarginLeftSmallest}`}>
<p>Single Kit</p>
<div className={`${g.gMarginTopSmall} ${g.thrashPreventerSquare}`}>
<img src={flowSingleKit} className={`${g.gPositionAbsolute}`} />
</div>
</div>
<div className={`${g.textCenter} ${g.gMarginLeftSmallest}`}>
<img src={flowArrow} />
</div>
<div className={`${g.g3Max} ${g.textCenter} ${g.gNoMarginTop} ${g.gMarginLeftSmallest}`}>
<p>Buys Kit</p>
<div className={`${g.gMarginTopSmall} ${g.thrashPreventerSquare} ${s.overlayRed}`}>
<img src={flowSingleKit} className={`${g.gPositionAbsolute}`} />
</div>
</div>
<div className={`${g.textCenter} ${g.gMarginLeftSmallest}`}>
<img src={flowArrow} />
</div>
<div className={`${g.g3Max} ${g.textCenter} ${g.gNoMarginTop} ${g.gMarginLeftSmaller}`}>
<p>Buys Class</p>
<div className={`${g.gMarginTopSmall} ${s.overlayBlue} ${g.thrashPreventerSquare} `} >
<img src={flowSingleClass} className={`${g.gPositionAbsolute}`} />
</div>
</div>
</HorizontalScroll>
</figure>
<div className={`${g.maxWidth}`}>
<p className={`${g.g9m} ${g.g6l} ${g.center}`}>Users viewing Classes were likely to view and purchase Kits, but users viewing Kits were not likely to view or purchase Classes. They were unlikely to look outside the Kits page.</p>
</div>
<div className={`${g.maxWidth}`}>
<h3 className={`${g.g9m} ${g.g6l} ${g.center}`}><strong>How People View Kits</strong></h3>
</div>
<figure className={`${g.gMarginTopSmall}`}>
<HorizontalScroll>
<div className={`${g.g3Max} ${g.textCenter} ${g.gNoMarginTop} ${g.gMarginLeftSmallest}`}>
<p>All Classes</p>
<div className={`${g.gMarginTopSmall} ${g.thrashPreventerSquare} `} >
<img src={flowAllKits} className={`${g.gPositionAbsolute}`} />
</div>
</div>
<div className={`${g.textCenter} ${g.gMarginLeftSmallest}`}>
<img src={flowArrow} />
</div>
<div className={`${g.g3Max} ${g.textCenter} ${g.gNoMarginTop} ${g.gMarginLeftSmallest}`}>
<p>Single Kit</p>
<div className={`${g.gMarginTopSmall} ${g.thrashPreventerSquare} `} >
<img src={flowSingleKit} className={`${g.gPositionAbsolute}`} />
</div>
</div>
<div className={`${g.textCenter} ${g.gMarginLeftSmallest}`}>
<img src={flowArrow} />
</div>
<div className={`${g.g3Max} ${g.textCenter} ${g.gNoMarginTop} ${g.gMarginLeftSmallest}`}>
<p>Purchase Kit</p>
<div className={`${g.gMarginTopSmall} ${s.overlayRed} ${g.thrashPreventerSquare} `} >
<img src={flowSingleKit} className={`${g.gPositionAbsolute}`} />
</div>
</div>
</HorizontalScroll>
</figure>
<div className={`${g.maxWidth} ${g.gMarginTopSmall}`}>
<p className={`${g.g9m} ${g.g6l} ${g.center}`}>People seeking Kits may not need or want instruction; they could simply want supplies for their projects. People interested in Classes, on the other hand, seemed to also want all the supplies they need to begin learning that craft. We needed to make it easier for those viewing Classes to purchase related Kits, and we needed to convince those looking at Kits to view Classes as well.</p>
<h2 className={`${g.g9m} ${g.g6l} ${g.center}`}>Alerting Users About Classes</h2>
<p className={`${g.g9m} ${g.g6l} ${g.center} `}>For Kits that had a matching class, we added a callout that encourages users to view the class. Messaging was focused on making sure a user’s project turned <span className={`${g.noWrap}`}>out well.</span></p>
</div>
<figure className={`${g.maxWidth}`}>
<div className={`${g.gFlexContainer} ${g.gFlexEnd} ${s.kitWrapper}`}>
<div className={`${s.wireframeKit} ${g.g9m} ${g.g7l} ${v.shadow1}`}>
<LazyLoader height="96%" placeholderColor="#e3e3e3">
<img src={wireframeKit} />
</LazyLoader>
</div>
<div className={`${s.calloutPanel} ${g.z1} ${g.g7m} ${v.shadow2}`}>
<LazyLoader height="32%" placeholderColor="#fdf1ff">
<img src={calloutPanel} />
</LazyLoader>
</div>
</div>
<figcaption>A callout panel that notifies users that there's a class associated with <span className={`${g.noWrap}`}>this Kit.</span></figcaption>
</figure>
<div className={`${g.maxWidth}`}>
<h2 className={`${g.g9m} ${g.g6l} ${g.center}`}>Bundling Both Products</h2>
<p className={`${g.g9m} ${g.g6l} ${g.center}`}>The Class page was designed by Krystle Cho.<sup>1</sup> It allows users to purchase both Kits and classes in a <span className={`${g.noWrap}`}>single click.</span></p>
<p className={`${g.g9m} ${g.g6l} ${g.center}`}>On both pages, we removed content from the right rail so that only the add-to-cart <span className={`${g.noWrap}`}>module remained.</span></p>
</div>
<figure className={`${g.maxWidth}`}>
<div className={`${g.gFlexContainer} ${g.gFlexStart} ${s.classWrapper}`}>
<div className={`${s.wireframeClass} ${g.g9m} ${g.g7l} ${v.shadow1}`} >
<LazyLoader height="96%" placeholderColor="#e3e3e3">
<img src={wireframeClass} />
</LazyLoader>
</div>
<div className={`${s.addToCartPanel} ${g.g6m} ${g.g4l} ${g.gAlignSelfCenter} ${g.z1} ${v.shadow2}`}>
<LazyLoader height="85%" placeholderColor="#dbf3f2">
<img src={addToCartPanel} />
</LazyLoader>
</div>
</div>
<figcaption>A new add-to-cart module that allows for purchasing <span className={`${g.noWrap}`}>both products.</span></figcaption>
</figure>
<div className={`${g.maxWidth}`}>
<h2 className={`${g.g9m} ${g.g6l} ${g.center}`}>User Testing</h2>
<p className={`${g.g9m} ${g.g6l} ${g.center}`}>
This was a clear direction, but we still needed to validate it with users, so I conducted a round of in-person user tests with 5 people.</p>
<blockquote className={`${g.g5l} ${g.center} ${g.floatRightM}`}>“Okay, Class and Kit… well that’s confusing, because it looks like it’s <span className={`${g.noWrap}`}>a price</span> range, not <span className={`${g.noWrap}`}>a choice.</span>”
</blockquote>
<p className={`${g.g9m} ${g.g6l} ${g.center}`}>The results showed we still needed to communicate our pricing structure more effectively. For instance, in the first user test below, Sophie couldn't understand the price range until she selected the drop down menu.</p>
<p className={`${g.g9m} ${g.g6l} ${g.center}`}>
While I reported these findings to the team, Krystle revised the class page to better communicate the pricing structure. We tested again using a toggle instead of a dropdown menu, with much better results.</p>
</div>
<figure className={`${g.maxWidth}`}>
<div className={`${g.gFlexContainer} ${g.gFlexCenter} ${s.userTestingWrapper}`}>
<div className={`${g.g5m}`}>
<LazyLoader height="132%" placeholderImage={userTestPlaceholder}>
<video autoPlay playsInline loop muted poster={userTestPoster}>
<source src={userTestWebm} type="video/webm" />
<source src={userTestMp4} type="video/mp4" />
</video>
</LazyLoader>
</div>
<div className={`${g.g4m}`}>
<Iphone image={iphoneImage} />
</div>
</div>
<figcaption className={`${g.textCenter}`}>On the left, user testing the initial design. The revised design <span className={`${g.noWrap}`}>on right.</span></figcaption>
</figure>
<div className={`${g.maxWidth}`}>
<p className={`${g.g9m} ${g.g9m} ${g.g6l} ${g.center}`}>Simplifying the product pages and removing friction to purchase both the class and kit increased the attachment rate by 3.5%. We did it without inhibiting new strategy exploration for the rest of the
team, and we saved engineering resources
by building and deploying our own
prototype.</p>
<h2 className={`${g.g9m} ${g.g6l} ${g.center}`}>Credits</h2>
<p className={`${g.g9m} ${g.g6l} ${g.center}`}>
<LinkExternal href="https://www.linkedin.com/in/ericarios">Erica Rios</LinkExternal> – Project Manager
<br />
<LinkExternal href="https://angel.co/mskrys" >Krystle Cho</LinkExternal> – Product Designer
<br />
<LinkExternal href="https://twitter.com/monokrome">Bailey Stoner</LinkExternal> – Engineer
</p>
</div>
</Layout>
);
}
}
export default ImprovingPurchaseProcessPage;
|
/**
* Created by 9simezi on 2017/08/29.
*/
import firebase from 'firebase';
export async function getIdols() {
const db = firebase.database();
const idolRef = db.ref('/idols/');
const idolsObj = await idolRef.once('value');
const temp = [];
idolsObj.forEach((idol) => {
temp.push(idol.val());
});
return temp;
}
export async function getIdolSongs(idol) {
const db = firebase.database();
const songRef = db.ref('/idolSongs/').child(idol);
const obj = await songRef.once('value');
return obj.val();
}
|
import React from 'react';
import styles from './folderTreeCSS.css'
class EditableName extends React.Component {
static propTypes = {
filename: React.PropTypes.string.isRequired,
setMyName: React.PropTypes.func.isRequired,
selected: React.PropTypes.number.isRequired,
};
constructor(props) {
super(props);
this.toggleEditing = this.toggleEditing.bind(this);
this.handleChangeName = this.handleChangeName.bind(this);
this.state = {
editing: false,
selected: false,
};
}
componentWillReceiveProps(nextProps) {
if (nextProps.selected === 1)
this.setState({selected: 1});
else
this.setState({selected: 0});
}
toggleEditing() {
this.setState(prevState => ({editing: !prevState.editing}));
if (this.state.editing) { // TODO: this doesn't work
this.textInput.focus();
}
}
handleChangeName() {
this.props.setMyName(this.textInput.value);
this.toggleEditing();
}
render() {
const input = (
<span>
<input type="text" defaultValue={this.props.filename} ref={ input => { this.textInput = input; } } />
<i className={styles.OKIcon} onClick={this.handleChangeName} />
<i className={styles.NoIcon} onClick={this.toggleEditing} />
</span>
);
const name = (
<span>
{' ' + this.props.filename + ' '}
{ this.state.selected === 1 && <i className={styles.pencilIcon} onClick={this.toggleEditing} /> }
</span>
);
return (
<span>
{ this.state.editing? input : name }
</span>
);
}
}
export default EditableName; |
'use strict';
/**
* app.js
*
* Use `app.js` to run your app without `sails lift`.
* To start the server, run: `node app.js`.
*
* This is handy in situations where the sails CLI is not relevant or useful.
*
* For example:
* => `node app.js`
* => `forever start app.js`
* => `node debug app.js`
* => `modulus deploy`
* => `heroku scale`
*
*
* The same command-line arguments are supported, e.g.:
* `node app.js --silent --port=80 --prod`
*/
// Ensure a "sails" can be located:
(function() {
var sails;
try {
sails = require('sails');
} catch (e) {
console.error('To run an app using `node app.js`, you usually need to have a version of `sails` installed in the same directory as your app.');
console.error('To do that, run `npm install sails`');
console.error('');
console.error('Alternatively, if you have sails installed globally (i.e. you did `npm install -g sails`), you can use `sails lift`.');
console.error('When you run `sails lift`, your app will still use a local `./node_modules/sails` dependency if it exists,');
console.error('but if it doesn\'t, the app will run with the global sails instead!');
return;
}
// Try to get `rc` dependency
var rc;
try {
rc = require('rc');
} catch (e0) {
try {
rc = require('sails/node_modules/rc');
} catch (e1) {
console.error('Could not find dependency: `rc`.');
console.error('Your `.sailsrc` file(s) will be ignored.');
console.error('To resolve this, run:');
console.error('npm install rc --save');
rc = function () { return {}; };
}
}
// Start server
sails.lift(rc('sails'));
})();
|
/*
* angular-ui-bootstrap
* http://angular-ui.github.io/bootstrap/
* Version: 0.13.1-SNAPSHOT - 2015-07-13
* License: MIT
*/
angular.module("ui.bootstrap", ["ui.bootstrap.collapse","ui.bootstrap.accordion","ui.bootstrap.alert","ui.bootstrap.bindHtml","ui.bootstrap.buttons","ui.bootstrap.carousel","ui.bootstrap.dateparser","ui.bootstrap.position","ui.bootstrap.datepicker","ui.bootstrap.dropdown","ui.bootstrap.modal","ui.bootstrap.pagination","ui.bootstrap.tooltip","ui.bootstrap.popover","ui.bootstrap.progressbar","ui.bootstrap.rating","ui.bootstrap.tabs","ui.bootstrap.timepicker","ui.bootstrap.transition","ui.bootstrap.typeahead"]);
angular.module('ui.bootstrap.collapse', [])
.directive('collapse', ['$animate', function ($animate) {
return {
link: function (scope, element, attrs) {
function expand() {
element.removeClass('collapse').addClass('collapsing');
$animate.addClass(element, 'in', {
to: { height: element[0].scrollHeight + 'px' }
}).then(expandDone);
}
function expandDone() {
element.removeClass('collapsing');
element.css({height: 'auto'});
}
function collapse() {
element
// IMPORTANT: The height must be set before adding "collapsing" class.
// Otherwise, the browser attempts to animate from height 0 (in
// collapsing class) to the given height here.
.css({height: element[0].scrollHeight + 'px'})
// initially all panel collapse have the collapse class, this removal
// prevents the animation from jumping to collapsed state
.removeClass('collapse')
.addClass('collapsing');
$animate.removeClass(element, 'in', {
to: {height: '0'}
}).then(collapseDone);
}
function collapseDone() {
element.css({height: '0'}); // Required so that collapse works when animation is disabled
element.removeClass('collapsing');
element.addClass('collapse');
}
scope.$watch(attrs.collapse, function (shouldCollapse) {
if (shouldCollapse) {
collapse();
} else {
expand();
}
});
}
};
}]);
angular.module('ui.bootstrap.accordion', ['ui.bootstrap.collapse'])
.constant('accordionConfig', {
closeOthers: true
})
.controller('AccordionController', ['$scope', '$attrs', 'accordionConfig', function ($scope, $attrs, accordionConfig) {
// This array keeps track of the accordion groups
this.groups = [];
// Ensure that all the groups in this accordion are closed, unless close-others explicitly says not to
this.closeOthers = function(openGroup) {
var closeOthers = angular.isDefined($attrs.closeOthers) ? $scope.$eval($attrs.closeOthers) : accordionConfig.closeOthers;
if ( closeOthers ) {
angular.forEach(this.groups, function (group) {
if ( group !== openGroup ) {
group.isOpen = false;
}
});
}
};
// This is called from the accordion-group directive to add itself to the accordion
this.addGroup = function(groupScope) {
var that = this;
this.groups.push(groupScope);
groupScope.$on('$destroy', function (event) {
that.removeGroup(groupScope);
});
};
// This is called from the accordion-group directive when to remove itself
this.removeGroup = function(group) {
var index = this.groups.indexOf(group);
if ( index !== -1 ) {
this.groups.splice(index, 1);
}
};
}])
// The accordion directive simply sets up the directive controller
// and adds an accordion CSS class to itself element.
.directive('accordion', function () {
return {
restrict:'EA',
controller:'AccordionController',
transclude: true,
replace: false,
templateUrl: 'template/accordion/accordion.html'
};
})
// The accordion-group directive indicates a block of html that will expand and collapse in an accordion
.directive('accordionGroup', function() {
return {
require:'^accordion', // We need this directive to be inside an accordion
restrict:'EA',
transclude:true, // It transcludes the contents of the directive into the template
replace: true, // The element containing the directive will be replaced with the template
templateUrl:'template/accordion/accordion-group.html',
scope: {
heading: '@', // Interpolate the heading attribute onto this scope
isOpen: '=?',
isDisabled: '=?'
},
controller: function() {
this.setHeading = function(element) {
this.heading = element;
};
},
link: function(scope, element, attrs, accordionCtrl) {
accordionCtrl.addGroup(scope);
scope.$watch('isOpen', function(value) {
if ( value ) {
accordionCtrl.closeOthers(scope);
}
});
scope.toggleOpen = function() {
if ( !scope.isDisabled ) {
scope.isOpen = !scope.isOpen;
}
};
}
};
})
// Use accordion-heading below an accordion-group to provide a heading containing HTML
// <accordion-group>
// <accordion-heading>Heading containing HTML - <img src="..."></accordion-heading>
// </accordion-group>
.directive('accordionHeading', function() {
return {
restrict: 'EA',
transclude: true, // Grab the contents to be used as the heading
template: '', // In effect remove this element!
replace: true,
require: '^accordionGroup',
link: function(scope, element, attr, accordionGroupCtrl, transclude) {
// Pass the heading to the accordion-group controller
// so that it can be transcluded into the right place in the template
// [The second parameter to transclude causes the elements to be cloned so that they work in ng-repeat]
accordionGroupCtrl.setHeading(transclude(scope, angular.noop));
}
};
})
// Use in the accordion-group template to indicate where you want the heading to be transcluded
// You must provide the property on the accordion-group controller that will hold the transcluded element
// <div class="accordion-group">
// <div class="accordion-heading" ><a ... accordion-transclude="heading">...</a></div>
// ...
// </div>
.directive('accordionTransclude', function() {
return {
require: '^accordionGroup',
link: function(scope, element, attr, controller) {
scope.$watch(function() { return controller[attr.accordionTransclude]; }, function(heading) {
if ( heading ) {
element.html('');
element.append(heading);
}
});
}
};
})
;
angular.module('ui.bootstrap.alert', [])
.controller('AlertController', ['$scope', '$attrs', function ($scope, $attrs) {
$scope.closeable = !!$attrs.close;
this.close = $scope.close;
}])
.directive('alert', function () {
return {
restrict:'EA',
controller:'AlertController',
templateUrl:'template/alert/alert.html',
transclude:true,
replace:true,
scope: {
type: '@',
close: '&'
}
};
})
.directive('dismissOnTimeout', ['$timeout', function($timeout) {
return {
require: 'alert',
link: function(scope, element, attrs, alertCtrl) {
$timeout(function(){
alertCtrl.close();
}, parseInt(attrs.dismissOnTimeout, 10));
}
};
}]);
angular.module('ui.bootstrap.bindHtml', [])
.directive('bindHtmlUnsafe', function () {
return function (scope, element, attr) {
element.addClass('ng-binding').data('$binding', attr.bindHtmlUnsafe);
scope.$watch(attr.bindHtmlUnsafe, function bindHtmlUnsafeWatchAction(value) {
element.html(value || '');
});
};
});
angular.module('ui.bootstrap.buttons', [])
.constant('buttonConfig', {
activeClass: 'active',
toggleEvent: 'click'
})
.controller('ButtonsController', ['buttonConfig', function(buttonConfig) {
this.activeClass = buttonConfig.activeClass || 'active';
this.toggleEvent = buttonConfig.toggleEvent || 'click';
}])
.directive('btnRadio', function () {
return {
require: ['btnRadio', 'ngModel'],
controller: 'ButtonsController',
link: function (scope, element, attrs, ctrls) {
var buttonsCtrl = ctrls[0], ngModelCtrl = ctrls[1];
//model -> UI
ngModelCtrl.$render = function () {
element.toggleClass(buttonsCtrl.activeClass, angular.equals(ngModelCtrl.$modelValue, scope.$eval(attrs.btnRadio)));
};
//ui->model
element.bind(buttonsCtrl.toggleEvent, function () {
var isActive = element.hasClass(buttonsCtrl.activeClass);
if (!isActive || angular.isDefined(attrs.uncheckable)) {
scope.$apply(function () {
ngModelCtrl.$setViewValue(isActive ? null : scope.$eval(attrs.btnRadio));
ngModelCtrl.$render();
});
}
});
}
};
})
.directive('btnCheckbox', function () {
return {
require: ['btnCheckbox', 'ngModel'],
controller: 'ButtonsController',
link: function (scope, element, attrs, ctrls) {
var buttonsCtrl = ctrls[0], ngModelCtrl = ctrls[1];
function getTrueValue() {
return getCheckboxValue(attrs.btnCheckboxTrue, true);
}
function getFalseValue() {
return getCheckboxValue(attrs.btnCheckboxFalse, false);
}
function getCheckboxValue(attributeValue, defaultValue) {
var val = scope.$eval(attributeValue);
return angular.isDefined(val) ? val : defaultValue;
}
//model -> UI
ngModelCtrl.$render = function () {
element.toggleClass(buttonsCtrl.activeClass, angular.equals(ngModelCtrl.$modelValue, getTrueValue()));
};
//ui->model
element.bind(buttonsCtrl.toggleEvent, function () {
scope.$apply(function () {
ngModelCtrl.$setViewValue(element.hasClass(buttonsCtrl.activeClass) ? getFalseValue() : getTrueValue());
ngModelCtrl.$render();
});
});
}
};
});
/**
* @ngdoc overview
* @name ui.bootstrap.carousel
*
* @description
* AngularJS version of an image carousel.
*
*/
angular.module('ui.bootstrap.carousel', [])
.controller('CarouselController', ['$scope', '$element', '$interval', '$animate', function ($scope, $element, $interval, $animate) {
var self = this,
slides = self.slides = $scope.slides = [],
NO_TRANSITION = 'uib-noTransition',
SLIDE_DIRECTION = 'uib-slideDirection',
currentIndex = -1,
currentInterval, isPlaying;
self.currentSlide = null;
var destroyed = false;
/* direction: "prev" or "next" */
self.select = $scope.select = function(nextSlide, direction) {
var nextIndex = self.indexOfSlide(nextSlide);
//Decide direction if it's not given
if (direction === undefined) {
direction = nextIndex > self.getCurrentIndex() ? 'next' : 'prev';
}
//Prevent this user-triggered transition from occurring if there is already one in progress
if (nextSlide && nextSlide !== self.currentSlide && !$scope.$currentTransition) {
goNext(nextSlide, nextIndex, direction);
}
};
function goNext(slide, index, direction) {
// Scope has been destroyed, stop here.
if (destroyed) { return; }
angular.extend(slide, {direction: direction, active: true});
angular.extend(self.currentSlide || {}, {direction: direction, active: false});
if ($animate.enabled() && !$scope.noTransition && !$scope.$currentTransition &&
slide.$element) {
slide.$element.data(SLIDE_DIRECTION, slide.direction);
$scope.$currentTransition = true;
slide.$element.one('$animate:close', function closeFn() {
$scope.$currentTransition = null;
});
}
self.currentSlide = slide;
currentIndex = index;
//every time you change slides, reset the timer
restartTimer();
}
$scope.$on('$destroy', function () {
destroyed = true;
});
function getSlideByIndex(index) {
if (angular.isUndefined(slides[index].index)) {
return slides[index];
}
var i, len = slides.length;
for (i = 0; i < slides.length; ++i) {
if (slides[i].index == index) {
return slides[i];
}
}
}
self.getCurrentIndex = function() {
if (self.currentSlide && angular.isDefined(self.currentSlide.index)) {
return +self.currentSlide.index;
}
return currentIndex;
};
/* Allow outside people to call indexOf on slides array */
self.indexOfSlide = function(slide) {
return angular.isDefined(slide.index) ? +slide.index : slides.indexOf(slide);
};
$scope.next = function() {
var newIndex = (self.getCurrentIndex() + 1) % slides.length;
if (newIndex === 0 && $scope.noWrap()) {
$scope.pause();
return;
}
return self.select(getSlideByIndex(newIndex), 'next');
};
$scope.prev = function() {
var newIndex = self.getCurrentIndex() - 1 < 0 ? slides.length - 1 : self.getCurrentIndex() - 1;
if ($scope.noWrap() && newIndex === slides.length - 1){
$scope.pause();
return;
}
return self.select(getSlideByIndex(newIndex), 'prev');
};
$scope.isActive = function(slide) {
return self.currentSlide === slide;
};
$scope.$watch('interval', restartTimer);
$scope.$on('$destroy', resetTimer);
function restartTimer() {
resetTimer();
var interval = +$scope.interval;
if (!isNaN(interval) && interval > 0) {
currentInterval = $interval(timerFn, interval);
}
}
function resetTimer() {
if (currentInterval) {
$interval.cancel(currentInterval);
currentInterval = null;
}
}
function timerFn() {
var interval = +$scope.interval;
if (isPlaying && !isNaN(interval) && interval > 0 && slides.length) {
$scope.next();
} else {
$scope.pause();
}
}
$scope.play = function() {
if (!isPlaying) {
isPlaying = true;
restartTimer();
}
};
$scope.pause = function() {
if (!$scope.noPause) {
isPlaying = false;
resetTimer();
}
};
self.addSlide = function(slide, element) {
slide.$element = element;
slides.push(slide);
//if this is the first slide or the slide is set to active, select it
if(slides.length === 1 || slide.active) {
self.select(slides[slides.length-1]);
if (slides.length == 1) {
$scope.play();
}
} else {
slide.active = false;
}
};
self.removeSlide = function(slide) {
if (angular.isDefined(slide.index)) {
slides.sort(function(a, b) {
return +a.index > +b.index;
});
}
//get the index of the slide inside the carousel
var index = slides.indexOf(slide);
slides.splice(index, 1);
if (slides.length > 0 && slide.active) {
if (index >= slides.length) {
self.select(slides[index-1]);
} else {
self.select(slides[index]);
}
} else if (currentIndex > index) {
currentIndex--;
}
};
$scope.$watch('noTransition', function(noTransition) {
$element.data(NO_TRANSITION, noTransition);
});
}])
/**
* @ngdoc directive
* @name ui.bootstrap.carousel.directive:carousel
* @restrict EA
*
* @description
* Carousel is the outer container for a set of image 'slides' to showcase.
*
* @param {number=} interval The time, in milliseconds, that it will take the carousel to go to the next slide.
* @param {boolean=} noTransition Whether to disable transitions on the carousel.
* @param {boolean=} noPause Whether to disable pausing on the carousel (by default, the carousel interval pauses on hover).
*
* @example
<example module="ui.bootstrap">
<file name="index.html">
<carousel>
<slide>
<img src="http://placekitten.com/150/150" style="margin:auto;">
<div class="carousel-caption">
<p>Beautiful!</p>
</div>
</slide>
<slide>
<img src="http://placekitten.com/100/150" style="margin:auto;">
<div class="carousel-caption">
<p>D'aww!</p>
</div>
</slide>
</carousel>
</file>
<file name="demo.css">
.carousel-indicators {
top: auto;
bottom: 15px;
}
</file>
</example>
*/
.directive('carousel', [function() {
return {
restrict: 'EA',
transclude: true,
replace: true,
controller: 'CarouselController',
require: 'carousel',
templateUrl: 'template/carousel/carousel.html',
scope: {
interval: '=',
noTransition: '=',
noPause: '=',
noWrap: '&'
}
};
}])
/**
* @ngdoc directive
* @name ui.bootstrap.carousel.directive:slide
* @restrict EA
*
* @description
* Creates a slide inside a {@link ui.bootstrap.carousel.directive:carousel carousel}. Must be placed as a child of a carousel element.
*
* @param {boolean=} active Model binding, whether or not this slide is currently active.
* @param {number=} index The index of the slide. The slides will be sorted by this parameter.
*
* @example
<example module="ui.bootstrap">
<file name="index.html">
<div ng-controller="CarouselDemoCtrl">
<carousel>
<slide ng-repeat="slide in slides" active="slide.active" index="$index">
<img ng-src="{{slide.image}}" style="margin:auto;">
<div class="carousel-caption">
<h4>Slide {{$index}}</h4>
<p>{{slide.text}}</p>
</div>
</slide>
</carousel>
Interval, in milliseconds: <input type="number" ng-model="myInterval">
<br />Enter a negative number to stop the interval.
</div>
</file>
<file name="script.js">
function CarouselDemoCtrl($scope) {
$scope.myInterval = 5000;
}
</file>
<file name="demo.css">
.carousel-indicators {
top: auto;
bottom: 15px;
}
</file>
</example>
*/
.directive('slide', function() {
return {
require: '^carousel',
restrict: 'EA',
transclude: true,
replace: true,
templateUrl: 'template/carousel/slide.html',
scope: {
active: '=?',
index: '=?'
},
link: function (scope, element, attrs, carouselCtrl) {
carouselCtrl.addSlide(scope, element);
//when the scope is destroyed then remove the slide from the current slides array
scope.$on('$destroy', function() {
carouselCtrl.removeSlide(scope);
});
scope.$watch('active', function(active) {
if (active) {
carouselCtrl.select(scope);
}
});
}
};
})
.animation('.item', [
'$animate',
function ($animate) {
var NO_TRANSITION = 'uib-noTransition',
SLIDE_DIRECTION = 'uib-slideDirection';
return {
beforeAddClass: function (element, className, done) {
// Due to transclusion, noTransition property is on parent's scope
if (className == 'active' && element.parent() &&
!element.parent().data(NO_TRANSITION)) {
var stopped = false;
var direction = element.data(SLIDE_DIRECTION);
var directionClass = direction == 'next' ? 'left' : 'right';
element.addClass(direction);
$animate.addClass(element, directionClass).then(function () {
if (!stopped) {
element.removeClass(directionClass + ' ' + direction);
}
done();
});
return function () {
stopped = true;
};
}
done();
},
beforeRemoveClass: function (element, className, done) {
// Due to transclusion, noTransition property is on parent's scope
if (className == 'active' && element.parent() &&
!element.parent().data(NO_TRANSITION)) {
var stopped = false;
var direction = element.data(SLIDE_DIRECTION);
var directionClass = direction == 'next' ? 'left' : 'right';
$animate.addClass(element, directionClass).then(function () {
if (!stopped) {
element.removeClass(directionClass);
}
done();
});
return function () {
stopped = true;
};
}
done();
}
};
}])
;
angular.module('ui.bootstrap.dateparser', [])
.service('dateParser', ['$locale', 'orderByFilter', function($locale, orderByFilter) {
// Pulled from https://github.com/mbostock/d3/blob/master/src/format/requote.js
var SPECIAL_CHARACTERS_REGEXP = /[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g;
this.parsers = {};
var formatCodeToRegex = {
'yyyy': {
regex: '\\d{4}',
apply: function(value) { this.year = +value; }
},
'yy': {
regex: '\\d{2}',
apply: function(value) { this.year = +value + 2000; }
},
'y': {
regex: '\\d{1,4}',
apply: function(value) { this.year = +value; }
},
'MMMM': {
regex: $locale.DATETIME_FORMATS.MONTH.join('|'),
apply: function(value) { this.month = $locale.DATETIME_FORMATS.MONTH.indexOf(value); }
},
'MMM': {
regex: $locale.DATETIME_FORMATS.SHORTMONTH.join('|'),
apply: function(value) { this.month = $locale.DATETIME_FORMATS.SHORTMONTH.indexOf(value); }
},
'MM': {
regex: '0[1-9]|1[0-2]',
apply: function(value) { this.month = value - 1; }
},
'M': {
regex: '[1-9]|1[0-2]',
apply: function(value) { this.month = value - 1; }
},
'dd': {
regex: '[0-2][0-9]{1}|3[0-1]{1}',
apply: function(value) { this.date = +value; }
},
'd': {
regex: '[1-2]?[0-9]{1}|3[0-1]{1}',
apply: function(value) { this.date = +value; }
},
'EEEE': {
regex: $locale.DATETIME_FORMATS.DAY.join('|')
},
'EEE': {
regex: $locale.DATETIME_FORMATS.SHORTDAY.join('|')
},
'HH': {
regex: '(?:0|1)[0-9]|2[0-3]',
apply: function(value) { this.hours = +value; }
},
'H': {
regex: '1?[0-9]|2[0-3]',
apply: function(value) { this.hours = +value; }
},
'mm': {
regex: '[0-5][0-9]',
apply: function(value) { this.minutes = +value; }
},
'm': {
regex: '[0-9]|[1-5][0-9]',
apply: function(value) { this.minutes = +value; }
},
'sss': {
regex: '[0-9][0-9][0-9]',
apply: function(value) { this.milliseconds = +value; }
},
'ss': {
regex: '[0-5][0-9]',
apply: function(value) { this.seconds = +value; }
},
's': {
regex: '[0-9]|[1-5][0-9]',
apply: function(value) { this.seconds = +value; }
}
};
function createParser(format) {
var map = [], regex = format.split('');
angular.forEach(formatCodeToRegex, function(data, code) {
var index = format.indexOf(code);
if (index > -1) {
format = format.split('');
regex[index] = '(' + data.regex + ')';
format[index] = '$'; // Custom symbol to define consumed part of format
for (var i = index + 1, n = index + code.length; i < n; i++) {
regex[i] = '';
format[i] = '$';
}
format = format.join('');
map.push({ index: index, apply: data.apply });
}
});
return {
regex: new RegExp('^' + regex.join('') + '$'),
map: orderByFilter(map, 'index')
};
}
this.parse = function(input, format, baseDate) {
if ( !angular.isString(input) || !format ) {
return input;
}
format = $locale.DATETIME_FORMATS[format] || format;
format = format.replace(SPECIAL_CHARACTERS_REGEXP, '\\$&');
if ( !this.parsers[format] ) {
this.parsers[format] = createParser(format);
}
var parser = this.parsers[format],
regex = parser.regex,
map = parser.map,
results = input.match(regex);
if ( results && results.length ) {
var fields, dt;
if (baseDate) {
fields = {
year: baseDate.getFullYear(),
month: baseDate.getMonth(),
date: baseDate.getDate(),
hours: baseDate.getHours(),
minutes: baseDate.getMinutes(),
seconds: baseDate.getSeconds(),
milliseconds: baseDate.getMilliseconds()
};
} else {
fields = { year: 1900, month: 0, date: 1, hours: 0, minutes: 0, seconds: 0, milliseconds: 0 };
}
for( var i = 1, n = results.length; i < n; i++ ) {
var mapper = map[i-1];
if ( mapper.apply ) {
mapper.apply.call(fields, results[i]);
}
}
if ( isValid(fields.year, fields.month, fields.date) ) {
dt = new Date(fields.year, fields.month, fields.date, fields.hours, fields.minutes, fields.seconds,
fields.milliseconds || 0);
}
return dt;
}
};
// Check if date is valid for specific month (and year for February).
// Month: 0 = Jan, 1 = Feb, etc
function isValid(year, month, date) {
if (date < 1) {
return false;
}
if ( month === 1 && date > 28) {
return date === 29 && ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0);
}
if ( month === 3 || month === 5 || month === 8 || month === 10) {
return date < 31;
}
return true;
}
}]);
angular.module('ui.bootstrap.position', [])
/**
* A set of utility methods that can be use to retrieve position of DOM elements.
* It is meant to be used where we need to absolute-position DOM elements in
* relation to other, existing elements (this is the case for tooltips, popovers,
* typeahead suggestions etc.).
*/
.factory('$position', ['$document', '$window', function ($document, $window) {
function getStyle(el, cssprop) {
if (el.currentStyle) { //IE
return el.currentStyle[cssprop];
} else if ($window.getComputedStyle) {
return $window.getComputedStyle(el)[cssprop];
}
// finally try and get inline style
return el.style[cssprop];
}
/**
* Checks if a given element is statically positioned
* @param element - raw DOM element
*/
function isStaticPositioned(element) {
return (getStyle(element, 'position') || 'static' ) === 'static';
}
/**
* returns the closest, non-statically positioned parentOffset of a given element
* @param element
*/
var parentOffsetEl = function (element) {
var docDomEl = $document[0];
var offsetParent = element.offsetParent || docDomEl;
while (offsetParent && offsetParent !== docDomEl && isStaticPositioned(offsetParent) ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || docDomEl;
};
return {
/**
* Provides read-only equivalent of jQuery's position function:
* http://api.jquery.com/position/
*/
position: function (element) {
var elBCR = this.offset(element);
var offsetParentBCR = { top: 0, left: 0 };
var offsetParentEl = parentOffsetEl(element[0]);
if (offsetParentEl != $document[0]) {
offsetParentBCR = this.offset(angular.element(offsetParentEl));
offsetParentBCR.top += offsetParentEl.clientTop - offsetParentEl.scrollTop;
offsetParentBCR.left += offsetParentEl.clientLeft - offsetParentEl.scrollLeft;
}
var boundingClientRect = element[0].getBoundingClientRect();
return {
width: boundingClientRect.width || element.prop('offsetWidth'),
height: boundingClientRect.height || element.prop('offsetHeight'),
top: elBCR.top - offsetParentBCR.top,
left: elBCR.left - offsetParentBCR.left
};
},
/**
* Provides read-only equivalent of jQuery's offset function:
* http://api.jquery.com/offset/
*/
offset: function (element) {
var boundingClientRect = element[0].getBoundingClientRect();
return {
width: boundingClientRect.width || element.prop('offsetWidth'),
height: boundingClientRect.height || element.prop('offsetHeight'),
top: boundingClientRect.top + ($window.pageYOffset || $document[0].documentElement.scrollTop),
left: boundingClientRect.left + ($window.pageXOffset || $document[0].documentElement.scrollLeft)
};
},
/**
* Provides coordinates for the targetEl in relation to hostEl
*/
positionElements: function (hostEl, targetEl, positionStr, appendToBody) {
var positionStrParts = positionStr.split('-');
var pos0 = positionStrParts[0], pos1 = positionStrParts[1] || 'center';
var hostElPos,
targetElWidth,
targetElHeight,
targetElPos;
hostElPos = appendToBody ? this.offset(hostEl) : this.position(hostEl);
targetElWidth = targetEl.prop('offsetWidth');
targetElHeight = targetEl.prop('offsetHeight');
var shiftWidth = {
center: function () {
return hostElPos.left + hostElPos.width / 2 - targetElWidth / 2;
},
left: function () {
return hostElPos.left;
},
right: function () {
return hostElPos.left + hostElPos.width;
}
};
var shiftHeight = {
center: function () {
return hostElPos.top + hostElPos.height / 2 - targetElHeight / 2;
},
top: function () {
return hostElPos.top;
},
bottom: function () {
return hostElPos.top + hostElPos.height;
}
};
switch (pos0) {
case 'right':
targetElPos = {
top: shiftHeight[pos1](),
left: shiftWidth[pos0]()
};
break;
case 'left':
targetElPos = {
top: shiftHeight[pos1](),
left: hostElPos.left - targetElWidth
};
break;
case 'bottom':
targetElPos = {
top: shiftHeight[pos0](),
left: shiftWidth[pos1]()
};
break;
default:
targetElPos = {
top: hostElPos.top - targetElHeight,
left: shiftWidth[pos1]()
};
break;
}
return targetElPos;
}
};
}]);
angular.module('ui.bootstrap.datepicker', ['ui.bootstrap.dateparser', 'ui.bootstrap.position'])
.constant('datepickerConfig', {
formatDay: 'dd',
formatMonth: 'MMMM',
formatYear: 'yyyy',
formatDayHeader: 'EEE',
formatDayTitle: 'MMMM yyyy',
formatMonthTitle: 'yyyy',
datepickerMode: 'day',
minMode: 'day',
maxMode: 'year',
showWeeks: true,
startingDay: 0,
yearRange: 20,
minDate: null,
maxDate: null,
shortcutPropagation: false
})
.controller('DatepickerController', ['$scope', '$attrs', '$parse', '$interpolate', '$timeout', '$log', 'dateFilter', 'datepickerConfig', function($scope, $attrs, $parse, $interpolate, $timeout, $log, dateFilter, datepickerConfig) {
var self = this,
ngModelCtrl = { $setViewValue: angular.noop }; // nullModelCtrl;
// Modes chain
this.modes = ['day', 'month', 'year'];
// Configuration attributes
angular.forEach(['formatDay', 'formatMonth', 'formatYear', 'formatDayHeader', 'formatDayTitle', 'formatMonthTitle',
'minMode', 'maxMode', 'showWeeks', 'startingDay', 'yearRange', 'shortcutPropagation'], function( key, index ) {
self[key] = angular.isDefined($attrs[key]) ? (index < 8 ? $interpolate($attrs[key])($scope.$parent) : $scope.$parent.$eval($attrs[key])) : datepickerConfig[key];
});
// Watchable date attributes
angular.forEach(['minDate', 'maxDate'], function( key ) {
if ( $attrs[key] ) {
$scope.$parent.$watch($parse($attrs[key]), function(value) {
self[key] = value ? new Date(value) : null;
self.refreshView();
});
} else {
self[key] = datepickerConfig[key] ? new Date(datepickerConfig[key]) : null;
}
});
$scope.datepickerMode = $scope.datepickerMode || datepickerConfig.datepickerMode;
$scope.maxMode = self.maxMode;
$scope.uniqueId = 'datepicker-' + $scope.$id + '-' + Math.floor(Math.random() * 10000);
if(angular.isDefined($attrs.initDate)) {
this.activeDate = $scope.$parent.$eval($attrs.initDate) || new Date();
$scope.$parent.$watch($attrs.initDate, function(initDate){
if(initDate && (ngModelCtrl.$isEmpty(ngModelCtrl.$modelValue) || ngModelCtrl.$invalid)){
self.activeDate = initDate;
self.refreshView();
}
});
} else {
this.activeDate = new Date();
}
$scope.isActive = function(dateObject) {
if (self.compare(dateObject.date, self.activeDate) === 0) {
$scope.activeDateId = dateObject.uid;
return true;
}
return false;
};
this.init = function( ngModelCtrl_ ) {
ngModelCtrl = ngModelCtrl_;
ngModelCtrl.$render = function() {
self.render();
};
};
this.render = function() {
if ( ngModelCtrl.$viewValue ) {
var date = new Date( ngModelCtrl.$viewValue ),
isValid = !isNaN(date);
if ( isValid ) {
this.activeDate = date;
} else {
$log.error('Datepicker directive: "ng-model" value must be a Date object, a number of milliseconds since 01.01.1970 or a string representing an RFC2822 or ISO 8601 date.');
}
ngModelCtrl.$setValidity('date', isValid);
}
this.refreshView();
};
this.refreshView = function() {
if ( this.element ) {
this._refreshView();
var date = ngModelCtrl.$viewValue ? new Date(ngModelCtrl.$viewValue) : null;
ngModelCtrl.$setValidity('date-disabled', !date || (this.element && !this.isDisabled(date)));
}
};
this.createDateObject = function(date, format) {
var model = ngModelCtrl.$viewValue ? new Date(ngModelCtrl.$viewValue) : null;
return {
date: date,
label: dateFilter(date, format),
selected: model && this.compare(date, model) === 0,
disabled: this.isDisabled(date),
current: this.compare(date, new Date()) === 0,
customClass: this.customClass(date)
};
};
this.isDisabled = function( date ) {
return ((this.minDate && this.compare(date, this.minDate) < 0) || (this.maxDate && this.compare(date, this.maxDate) > 0) || ($attrs.dateDisabled && $scope.dateDisabled({date: date, mode: $scope.datepickerMode})));
};
this.customClass = function( date ) {
return $scope.customClass({date: date, mode: $scope.datepickerMode});
};
// Split array into smaller arrays
this.split = function(arr, size) {
var arrays = [];
while (arr.length > 0) {
arrays.push(arr.splice(0, size));
}
return arrays;
};
$scope.select = function( date ) {
if ( $scope.datepickerMode === self.minMode ) {
var dt = ngModelCtrl.$viewValue ? new Date( ngModelCtrl.$viewValue ) : new Date(0, 0, 0, 0, 0, 0, 0);
dt.setFullYear( date.getFullYear(), date.getMonth(), date.getDate() );
ngModelCtrl.$setViewValue( dt );
ngModelCtrl.$render();
} else {
self.activeDate = date;
$scope.datepickerMode = self.modes[ self.modes.indexOf( $scope.datepickerMode ) - 1 ];
}
};
$scope.move = function( direction ) {
var year = self.activeDate.getFullYear() + direction * (self.step.years || 0),
month = self.activeDate.getMonth() + direction * (self.step.months || 0);
self.activeDate.setFullYear(year, month, 1);
self.refreshView();
};
$scope.toggleMode = function( direction ) {
direction = direction || 1;
if (($scope.datepickerMode === self.maxMode && direction === 1) || ($scope.datepickerMode === self.minMode && direction === -1)) {
return;
}
$scope.datepickerMode = self.modes[ self.modes.indexOf( $scope.datepickerMode ) + direction ];
};
// Key event mapper
$scope.keys = { 13:'enter', 32:'space', 33:'pageup', 34:'pagedown', 35:'end', 36:'home', 37:'left', 38:'up', 39:'right', 40:'down' };
var focusElement = function() {
$timeout(function() {
self.element[0].focus();
}, 0 , false);
};
// Listen for focus requests from popup directive
$scope.$on('datepicker.focus', focusElement);
$scope.keydown = function( evt ) {
var key = $scope.keys[evt.which];
if ( !key || evt.shiftKey || evt.altKey ) {
return;
}
evt.preventDefault();
if(!self.shortcutPropagation){
evt.stopPropagation();
}
if (key === 'enter' || key === 'space') {
if ( self.isDisabled(self.activeDate)) {
return; // do nothing
}
$scope.select(self.activeDate);
focusElement();
} else if (evt.ctrlKey && (key === 'up' || key === 'down')) {
$scope.toggleMode(key === 'up' ? 1 : -1);
focusElement();
} else {
self.handleKeyDown(key, evt);
self.refreshView();
}
};
}])
.directive( 'datepicker', function () {
return {
restrict: 'EA',
replace: true,
templateUrl: 'template/datepicker/datepicker.html',
scope: {
datepickerMode: '=?',
dateDisabled: '&',
customClass: '&',
shortcutPropagation: '&?'
},
require: ['datepicker', '?^ngModel'],
controller: 'DatepickerController',
link: function(scope, element, attrs, ctrls) {
var datepickerCtrl = ctrls[0], ngModelCtrl = ctrls[1];
if ( ngModelCtrl ) {
datepickerCtrl.init( ngModelCtrl );
}
}
};
})
.directive('daypicker', ['dateFilter', function (dateFilter) {
return {
restrict: 'EA',
replace: true,
templateUrl: 'template/datepicker/day.html',
require: '^datepicker',
link: function(scope, element, attrs, ctrl) {
scope.showWeeks = ctrl.showWeeks;
ctrl.step = { months: 1 };
ctrl.element = element;
var DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
function getDaysInMonth( year, month ) {
return ((month === 1) && (year % 4 === 0) && ((year % 100 !== 0) || (year % 400 === 0))) ? 29 : DAYS_IN_MONTH[month];
}
function getDates(startDate, n) {
var dates = new Array(n), current = new Date(startDate), i = 0;
current.setHours(12); // Prevent repeated dates because of timezone bug
while ( i < n ) {
dates[i++] = new Date(current);
current.setDate( current.getDate() + 1 );
}
return dates;
}
ctrl._refreshView = function() {
var year = ctrl.activeDate.getFullYear(),
month = ctrl.activeDate.getMonth(),
firstDayOfMonth = new Date(year, month, 1),
difference = ctrl.startingDay - firstDayOfMonth.getDay(),
numDisplayedFromPreviousMonth = (difference > 0) ? 7 - difference : - difference,
firstDate = new Date(firstDayOfMonth);
if ( numDisplayedFromPreviousMonth > 0 ) {
firstDate.setDate( - numDisplayedFromPreviousMonth + 1 );
}
// 42 is the number of days on a six-month calendar
var days = getDates(firstDate, 42);
for (var i = 0; i < 42; i ++) {
days[i] = angular.extend(ctrl.createDateObject(days[i], ctrl.formatDay), {
secondary: days[i].getMonth() !== month,
uid: scope.uniqueId + '-' + i
});
}
scope.labels = new Array(7);
for (var j = 0; j < 7; j++) {
scope.labels[j] = {
abbr: dateFilter(days[j].date, ctrl.formatDayHeader),
full: dateFilter(days[j].date, 'EEEE')
};
}
scope.title = dateFilter(ctrl.activeDate, ctrl.formatDayTitle);
scope.rows = ctrl.split(days, 7);
if ( scope.showWeeks ) {
scope.weekNumbers = [];
var thursdayIndex = (4 + 7 - ctrl.startingDay) % 7,
numWeeks = scope.rows.length;
for (var curWeek = 0; curWeek < numWeeks; curWeek++) {
scope.weekNumbers.push(
getISO8601WeekNumber( scope.rows[curWeek][thursdayIndex].date ));
}
}
};
ctrl.compare = function(date1, date2) {
return (new Date( date1.getFullYear(), date1.getMonth(), date1.getDate() ) - new Date( date2.getFullYear(), date2.getMonth(), date2.getDate() ) );
};
function getISO8601WeekNumber(date) {
var checkDate = new Date(date);
checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7)); // Thursday
var time = checkDate.getTime();
checkDate.setMonth(0); // Compare with Jan 1
checkDate.setDate(1);
return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1;
}
ctrl.handleKeyDown = function( key, evt ) {
var date = ctrl.activeDate.getDate();
if (key === 'left') {
date = date - 1; // up
} else if (key === 'up') {
date = date - 7; // down
} else if (key === 'right') {
date = date + 1; // down
} else if (key === 'down') {
date = date + 7;
} else if (key === 'pageup' || key === 'pagedown') {
var month = ctrl.activeDate.getMonth() + (key === 'pageup' ? - 1 : 1);
ctrl.activeDate.setMonth(month, 1);
date = Math.min(getDaysInMonth(ctrl.activeDate.getFullYear(), ctrl.activeDate.getMonth()), date);
} else if (key === 'home') {
date = 1;
} else if (key === 'end') {
date = getDaysInMonth(ctrl.activeDate.getFullYear(), ctrl.activeDate.getMonth());
}
ctrl.activeDate.setDate(date);
};
ctrl.refreshView();
}
};
}])
.directive('monthpicker', ['dateFilter', function (dateFilter) {
return {
restrict: 'EA',
replace: true,
templateUrl: 'template/datepicker/month.html',
require: '^datepicker',
link: function(scope, element, attrs, ctrl) {
ctrl.step = { years: 1 };
ctrl.element = element;
ctrl._refreshView = function() {
var months = new Array(12),
year = ctrl.activeDate.getFullYear();
for ( var i = 0; i < 12; i++ ) {
months[i] = angular.extend(ctrl.createDateObject(new Date(year, i, 1), ctrl.formatMonth), {
uid: scope.uniqueId + '-' + i
});
}
scope.title = dateFilter(ctrl.activeDate, ctrl.formatMonthTitle);
scope.rows = ctrl.split(months, 3);
};
ctrl.compare = function(date1, date2) {
return new Date( date1.getFullYear(), date1.getMonth() ) - new Date( date2.getFullYear(), date2.getMonth() );
};
ctrl.handleKeyDown = function( key, evt ) {
var date = ctrl.activeDate.getMonth();
if (key === 'left') {
date = date - 1; // up
} else if (key === 'up') {
date = date - 3; // down
} else if (key === 'right') {
date = date + 1; // down
} else if (key === 'down') {
date = date + 3;
} else if (key === 'pageup' || key === 'pagedown') {
var year = ctrl.activeDate.getFullYear() + (key === 'pageup' ? - 1 : 1);
ctrl.activeDate.setFullYear(year);
} else if (key === 'home') {
date = 0;
} else if (key === 'end') {
date = 11;
}
ctrl.activeDate.setMonth(date);
};
ctrl.refreshView();
}
};
}])
.directive('yearpicker', ['dateFilter', function (dateFilter) {
return {
restrict: 'EA',
replace: true,
templateUrl: 'template/datepicker/year.html',
require: '^datepicker',
link: function(scope, element, attrs, ctrl) {
var range = ctrl.yearRange;
ctrl.step = { years: range };
ctrl.element = element;
function getStartingYear( year ) {
return parseInt((year - 1) / range, 10) * range + 1;
}
ctrl._refreshView = function() {
var years = new Array(range);
for ( var i = 0, start = getStartingYear(ctrl.activeDate.getFullYear()); i < range; i++ ) {
years[i] = angular.extend(ctrl.createDateObject(new Date(start + i, 0, 1), ctrl.formatYear), {
uid: scope.uniqueId + '-' + i
});
}
scope.title = [years[0].label, years[range - 1].label].join(' - ');
scope.rows = ctrl.split(years, 5);
};
ctrl.compare = function(date1, date2) {
return date1.getFullYear() - date2.getFullYear();
};
ctrl.handleKeyDown = function( key, evt ) {
var date = ctrl.activeDate.getFullYear();
if (key === 'left') {
date = date - 1; // up
} else if (key === 'up') {
date = date - 5; // down
} else if (key === 'right') {
date = date + 1; // down
} else if (key === 'down') {
date = date + 5;
} else if (key === 'pageup' || key === 'pagedown') {
date += (key === 'pageup' ? - 1 : 1) * ctrl.step.years;
} else if (key === 'home') {
date = getStartingYear( ctrl.activeDate.getFullYear() );
} else if (key === 'end') {
date = getStartingYear( ctrl.activeDate.getFullYear() ) + range - 1;
}
ctrl.activeDate.setFullYear(date);
};
ctrl.refreshView();
}
};
}])
.constant('datepickerPopupConfig', {
datepickerPopup: 'yyyy-MM-dd',
html5Types: {
date: 'yyyy-MM-dd',
'datetime-local': 'yyyy-MM-ddTHH:mm:ss.sss',
'month': 'yyyy-MM'
},
currentText: 'Today',
clearText: 'Clear',
closeText: 'Done',
closeOnDateSelection: true,
appendToBody: false,
showButtonBar: true
})
.directive('datepickerPopup', ['$compile', '$parse', '$document', '$position', 'dateFilter', 'dateParser', 'datepickerPopupConfig',
function ($compile, $parse, $document, $position, dateFilter, dateParser, datepickerPopupConfig) {
return {
restrict: 'EA',
require: 'ngModel',
scope: {
isOpen: '=?',
currentText: '@',
clearText: '@',
closeText: '@',
dateDisabled: '&',
customClass: '&'
},
link: function(scope, element, attrs, ngModel) {
var dateFormat,
closeOnDateSelection = angular.isDefined(attrs.closeOnDateSelection) ? scope.$parent.$eval(attrs.closeOnDateSelection) : datepickerPopupConfig.closeOnDateSelection,
appendToBody = angular.isDefined(attrs.datepickerAppendToBody) ? scope.$parent.$eval(attrs.datepickerAppendToBody) : datepickerPopupConfig.appendToBody;
scope.showButtonBar = angular.isDefined(attrs.showButtonBar) ? scope.$parent.$eval(attrs.showButtonBar) : datepickerPopupConfig.showButtonBar;
scope.getText = function( key ) {
return scope[key + 'Text'] || datepickerPopupConfig[key + 'Text'];
};
var isHtml5DateInput = false;
if (datepickerPopupConfig.html5Types[attrs.type]) {
dateFormat = datepickerPopupConfig.html5Types[attrs.type];
isHtml5DateInput = true;
} else {
dateFormat = attrs.datepickerPopup || datepickerPopupConfig.datepickerPopup;
attrs.$observe('datepickerPopup', function(value, oldValue) {
var newDateFormat = value || datepickerPopupConfig.datepickerPopup;
// Invalidate the $modelValue to ensure that formatters re-run
// FIXME: Refactor when PR is merged: https://github.com/angular/angular.js/pull/10764
if (newDateFormat !== dateFormat) {
dateFormat = newDateFormat;
ngModel.$modelValue = null;
if (!dateFormat) {
throw new Error('datepickerPopup must have a date format specified.');
}
}
});
}
if (!dateFormat) {
throw new Error('datepickerPopup must have a date format specified.');
}
if (isHtml5DateInput && attrs.datepickerPopup) {
throw new Error('HTML5 date input types do not support custom formats.');
}
// popup element used to display calendar
var popupEl = angular.element('<div datepicker-popup-wrap><div datepicker></div></div>');
popupEl.attr({
'ng-model': 'date',
'ng-change': 'dateSelection()'
});
function cameltoDash( string ){
return string.replace(/([A-Z])/g, function($1) { return '-' + $1.toLowerCase(); });
}
// datepicker element
var datepickerEl = angular.element(popupEl.children()[0]);
if (isHtml5DateInput) {
if (attrs.type == 'month') {
datepickerEl.attr('datepicker-mode', '"month"');
datepickerEl.attr('min-mode', 'month');
}
}
if ( attrs.datepickerOptions ) {
var options = scope.$parent.$eval(attrs.datepickerOptions);
if(options.initDate) {
scope.initDate = options.initDate;
datepickerEl.attr( 'init-date', 'initDate' );
delete options.initDate;
}
angular.forEach(options, function( value, option ) {
datepickerEl.attr( cameltoDash(option), value );
});
}
scope.watchData = {};
angular.forEach(['minDate', 'maxDate', 'datepickerMode', 'initDate', 'shortcutPropagation'], function( key ) {
if ( attrs[key] ) {
var getAttribute = $parse(attrs[key]);
scope.$parent.$watch(getAttribute, function(value){
scope.watchData[key] = value;
});
datepickerEl.attr(cameltoDash(key), 'watchData.' + key);
// Propagate changes from datepicker to outside
if ( key === 'datepickerMode' ) {
var setAttribute = getAttribute.assign;
scope.$watch('watchData.' + key, function(value, oldvalue) {
if ( angular.isFunction(setAttribute) && value !== oldvalue ) {
setAttribute(scope.$parent, value);
}
});
}
}
});
if (attrs.dateDisabled) {
datepickerEl.attr('date-disabled', 'dateDisabled({ date: date, mode: mode })');
}
if (attrs.showWeeks) {
datepickerEl.attr('show-weeks', attrs.showWeeks);
}
if (attrs.customClass){
datepickerEl.attr('custom-class', 'customClass({ date: date, mode: mode })');
}
function parseDate(viewValue) {
if (angular.isNumber(viewValue)) {
// presumably timestamp to date object
viewValue = new Date(viewValue);
}
if (!viewValue) {
return null;
} else if (angular.isDate(viewValue) && !isNaN(viewValue)) {
return viewValue;
} else if (angular.isString(viewValue)) {
var date = dateParser.parse(viewValue, dateFormat, scope.date) || new Date(viewValue);
if (isNaN(date)) {
return undefined;
} else {
return date;
}
} else {
return undefined;
}
}
function validator(modelValue, viewValue) {
var value = modelValue || viewValue;
if (angular.isNumber(value)) {
value = new Date(value);
}
if (!value) {
return true;
} else if (angular.isDate(value) && !isNaN(value)) {
return true;
} else if (angular.isString(value)) {
var date = dateParser.parse(value, dateFormat) || new Date(value);
return !isNaN(date);
} else {
return false;
}
}
if (!isHtml5DateInput) {
// Internal API to maintain the correct ng-invalid-[key] class
ngModel.$$parserName = 'date';
ngModel.$validators.date = validator;
ngModel.$parsers.unshift(parseDate);
ngModel.$formatters.push(function (value) {
scope.date = value;
return ngModel.$isEmpty(value) ? value : dateFilter(value, dateFormat);
});
}
else {
ngModel.$formatters.push(function (value) {
scope.date = value;
return value;
});
}
// Inner change
scope.dateSelection = function(dt) {
if (angular.isDefined(dt)) {
scope.date = dt;
}
var date = scope.date ? dateFilter(scope.date, dateFormat) : '';
element.val(date);
ngModel.$setViewValue(date);
if ( closeOnDateSelection ) {
scope.isOpen = false;
element[0].focus();
}
};
// Detect changes in the view from the text box
ngModel.$viewChangeListeners.push(function () {
scope.date = dateParser.parse(ngModel.$viewValue, dateFormat, scope.date) || new Date(ngModel.$viewValue);
});
var documentClickBind = function(event) {
if (scope.isOpen && event.target !== element[0]) {
scope.$apply(function() {
scope.isOpen = false;
});
}
};
var keydown = function(evt, noApply) {
scope.keydown(evt);
};
element.bind('keydown', keydown);
scope.keydown = function(evt) {
if (evt.which === 27) {
evt.preventDefault();
if (scope.isOpen) {
evt.stopPropagation();
}
scope.close();
} else if (evt.which === 40 && !scope.isOpen) {
scope.isOpen = true;
}
};
scope.$watch('isOpen', function(value) {
if (value) {
scope.$broadcast('datepicker.focus');
scope.position = appendToBody ? $position.offset(element) : $position.position(element);
scope.position.top = scope.position.top + element.prop('offsetHeight');
$document.bind('click', documentClickBind);
} else {
$document.unbind('click', documentClickBind);
}
});
scope.select = function( date ) {
if (date === 'today') {
var today = new Date();
if (angular.isDate(scope.date)) {
date = new Date(scope.date);
date.setFullYear(today.getFullYear(), today.getMonth(), today.getDate());
} else {
date = new Date(today.setHours(0, 0, 0, 0));
}
}
scope.dateSelection( date );
};
scope.close = function() {
scope.isOpen = false;
element[0].focus();
};
var $popup = $compile(popupEl)(scope);
// Prevent jQuery cache memory leak (template is now redundant after linking)
popupEl.remove();
if ( appendToBody ) {
$document.find('body').append($popup);
} else {
element.after($popup);
}
scope.$on('$destroy', function() {
$popup.remove();
element.unbind('keydown', keydown);
$document.unbind('click', documentClickBind);
});
}
};
}])
.directive('datepickerPopupWrap', function() {
return {
restrict:'EA',
replace: true,
transclude: true,
templateUrl: 'template/datepicker/popup.html',
link:function (scope, element, attrs) {
element.bind('click', function(event) {
event.preventDefault();
event.stopPropagation();
});
}
};
});
angular.module('ui.bootstrap.dropdown', ['ui.bootstrap.position'])
.constant('dropdownConfig', {
openClass: 'open'
})
.service('dropdownService', ['$document', '$rootScope', function($document, $rootScope) {
var openScope = null;
this.open = function( dropdownScope ) {
if ( !openScope ) {
$document.bind('click', closeDropdown);
$document.bind('keydown', keybindFilter);
}
if ( openScope && openScope !== dropdownScope ) {
openScope.isOpen = false;
}
openScope = dropdownScope;
};
this.close = function( dropdownScope ) {
if ( openScope === dropdownScope ) {
openScope = null;
$document.unbind('click', closeDropdown);
$document.unbind('keydown', keybindFilter);
}
};
var closeDropdown = function( evt ) {
// This method may still be called during the same mouse event that
// unbound this event handler. So check openScope before proceeding.
if (!openScope) { return; }
if( evt && openScope.getAutoClose() === 'disabled' ) { return ; }
var toggleElement = openScope.getToggleElement();
if ( evt && toggleElement && toggleElement[0].contains(evt.target) ) {
return;
}
var $element = openScope.getElement();
if( evt && openScope.getAutoClose() === 'outsideClick' && $element && $element[0].contains(evt.target) ) {
return;
}
openScope.isOpen = false;
if (!$rootScope.$$phase) {
openScope.$apply();
}
};
var keybindFilter = function( evt ) {
if ( evt.which === 27 ) {
openScope.focusToggleElement();
closeDropdown();
}
else if ( openScope.isKeynavEnabled() && /(38|40)/.test(evt.which) && openScope.isOpen ) {
evt.preventDefault();
evt.stopPropagation();
openScope.focusDropdownEntry(evt.which);
}
};
}])
.controller('DropdownController', ['$scope', '$attrs', '$parse', 'dropdownConfig', 'dropdownService', '$animate', '$position', '$document', '$compile', '$templateRequest', function($scope, $attrs, $parse, dropdownConfig, dropdownService, $animate, $position, $document, $compile, $templateRequest) {
var self = this,
scope = $scope.$new(), // create a child scope so we are not polluting original one
templateScope,
openClass = dropdownConfig.openClass,
getIsOpen,
setIsOpen = angular.noop,
toggleInvoker = $attrs.onToggle ? $parse($attrs.onToggle) : angular.noop,
appendToBody = false,
keynavEnabled =false,
selectedOption = null;
this.init = function( element ) {
self.$element = element;
if ( $attrs.isOpen ) {
getIsOpen = $parse($attrs.isOpen);
setIsOpen = getIsOpen.assign;
$scope.$watch(getIsOpen, function(value) {
scope.isOpen = !!value;
});
}
appendToBody = angular.isDefined($attrs.dropdownAppendToBody);
keynavEnabled = angular.isDefined($attrs.keyboardNav);
if ( appendToBody && self.dropdownMenu ) {
$document.find('body').append( self.dropdownMenu );
element.on('$destroy', function handleDestroyEvent() {
self.dropdownMenu.remove();
});
}
};
this.toggle = function( open ) {
return scope.isOpen = arguments.length ? !!open : !scope.isOpen;
};
// Allow other directives to watch status
this.isOpen = function() {
return scope.isOpen;
};
scope.getToggleElement = function() {
return self.toggleElement;
};
scope.getAutoClose = function() {
return $attrs.autoClose || 'always'; //or 'outsideClick' or 'disabled'
};
scope.getElement = function() {
return self.$element;
};
scope.isKeynavEnabled = function() {
return keynavEnabled;
};
scope.focusDropdownEntry = function(keyCode) {
var elems = self.dropdownMenu ? //If append to body is used.
(angular.element(self.dropdownMenu).find('a')) :
(angular.element(self.$element).find('ul').eq(0).find('a'));
switch (keyCode) {
case (40): {
if ( !angular.isNumber(self.selectedOption)) {
self.selectedOption = 0;
} else {
self.selectedOption = (self.selectedOption === elems.length -1 ?
self.selectedOption :
self.selectedOption + 1);
}
break;
}
case (38): {
if ( !angular.isNumber(self.selectedOption)) {
return;
} else {
self.selectedOption = (self.selectedOption === 0 ?
0 :
self.selectedOption - 1);
}
break;
}
}
elems[self.selectedOption].focus();
};
scope.focusToggleElement = function() {
if ( self.toggleElement ) {
self.toggleElement[0].focus();
}
};
scope.$watch('isOpen', function( isOpen, wasOpen ) {
if ( appendToBody && self.dropdownMenu ) {
var pos = $position.positionElements(self.$element, self.dropdownMenu, 'bottom-left', true);
self.dropdownMenu.css({
top: pos.top + 'px',
left: pos.left + 'px',
display: isOpen ? 'block' : 'none'
});
}
$animate[isOpen ? 'addClass' : 'removeClass'](self.$element, openClass);
if ( isOpen ) {
if (self.dropdownMenuTemplateUrl) {
$templateRequest(self.dropdownMenuTemplateUrl).then(function(tplContent) {
templateScope = scope.$new();
$compile(tplContent.trim())(templateScope, function(dropdownElement) {
var newEl = dropdownElement;
self.dropdownMenu.replaceWith(newEl);
self.dropdownMenu = newEl;
});
});
}
scope.focusToggleElement();
dropdownService.open( scope );
} else {
if (self.dropdownMenuTemplateUrl) {
if (templateScope) {
templateScope.$destroy();
}
var newEl = angular.element('<ul class="dropdown-menu"></ul>');
self.dropdownMenu.replaceWith(newEl);
self.dropdownMenu = newEl;
}
dropdownService.close( scope );
self.selectedOption = null;
}
setIsOpen($scope, isOpen);
if (angular.isDefined(isOpen) && isOpen !== wasOpen) {
toggleInvoker($scope, { open: !!isOpen });
}
});
$scope.$on('$locationChangeSuccess', function() {
if (scope.getAutoClose() !== 'disabled') {
scope.isOpen = false;
}
});
$scope.$on('$destroy', function() {
scope.$destroy();
});
}])
.directive('dropdown', function() {
return {
controller: 'DropdownController',
link: function(scope, element, attrs, dropdownCtrl) {
dropdownCtrl.init( element );
}
};
})
.directive('dropdownMenu', function() {
return {
restrict: 'AC',
require: '?^dropdown',
link: function(scope, element, attrs, dropdownCtrl) {
if (!dropdownCtrl) {
return;
}
var tplUrl = attrs.templateUrl;
if (tplUrl) {
dropdownCtrl.dropdownMenuTemplateUrl = tplUrl;
}
if (!dropdownCtrl.dropdownMenu) {
dropdownCtrl.dropdownMenu = element;
}
}
};
})
.directive('keyboardNav', function() {
return {
restrict: 'A',
require: '?^dropdown',
link: function (scope, element, attrs, dropdownCtrl) {
element.bind('keydown', function(e) {
if ( /(38|40)/.test(e.which)) {
e.preventDefault();
e.stopPropagation();
var elems = angular.element(element).find('a');
switch (e.keyCode) {
case (40): { // Down
if ( !angular.isNumber(dropdownCtrl.selectedOption)) {
dropdownCtrl.selectedOption = 0;
} else {
dropdownCtrl.selectedOption = (dropdownCtrl.selectedOption === elems.length -1 ? dropdownCtrl.selectedOption : dropdownCtrl.selectedOption+1);
}
}
break;
case (38): { // Up
dropdownCtrl.selectedOption = (dropdownCtrl.selectedOption === 0 ? 0 : dropdownCtrl.selectedOption-1);
}
break;
}
elems[dropdownCtrl.selectedOption].focus();
}
});
}
};
})
.directive('dropdownToggle', function() {
return {
require: '?^dropdown',
link: function(scope, element, attrs, dropdownCtrl) {
if ( !dropdownCtrl ) {
return;
}
dropdownCtrl.toggleElement = element;
var toggleDropdown = function(event) {
event.preventDefault();
if ( !element.hasClass('disabled') && !attrs.disabled ) {
scope.$apply(function() {
dropdownCtrl.toggle();
});
}
};
element.bind('click', toggleDropdown);
// WAI-ARIA
element.attr({ 'aria-haspopup': true, 'aria-expanded': false });
scope.$watch(dropdownCtrl.isOpen, function( isOpen ) {
element.attr('aria-expanded', !!isOpen);
});
scope.$on('$destroy', function() {
element.unbind('click', toggleDropdown);
});
}
};
});
angular.module('ui.bootstrap.modal', [])
/**
* A helper, internal data structure that acts as a map but also allows getting / removing
* elements in the LIFO order
*/
.factory('$$stackedMap', function () {
return {
createNew: function () {
var stack = [];
return {
add: function (key, value) {
stack.push({
key: key,
value: value
});
},
get: function (key) {
for (var i = 0; i < stack.length; i++) {
if (key == stack[i].key) {
return stack[i];
}
}
},
keys: function() {
var keys = [];
for (var i = 0; i < stack.length; i++) {
keys.push(stack[i].key);
}
return keys;
},
top: function () {
return stack[stack.length - 1];
},
remove: function (key) {
var idx = -1;
for (var i = 0; i < stack.length; i++) {
if (key == stack[i].key) {
idx = i;
break;
}
}
return stack.splice(idx, 1)[0];
},
removeTop: function () {
return stack.splice(stack.length - 1, 1)[0];
},
length: function () {
return stack.length;
}
};
}
};
})
/**
* A helper directive for the $modal service. It creates a backdrop element.
*/
.directive('modalBackdrop', [
'$animate', '$modalStack',
function ($animate , $modalStack) {
return {
restrict: 'EA',
replace: true,
templateUrl: 'template/modal/backdrop.html',
compile: function (tElement, tAttrs) {
tElement.addClass(tAttrs.backdropClass);
return linkFn;
}
};
function linkFn(scope, element, attrs) {
if (attrs.modalInClass) {
$animate.addClass(element, attrs.modalInClass);
scope.$on($modalStack.NOW_CLOSING_EVENT, function (e, setIsAsync) {
var done = setIsAsync();
$animate.removeClass(element, attrs.modalInClass).then(done);
});
}
scope.close = function (evt) {
var modal = $modalStack.getTop();
if (modal && modal.value.backdrop && modal.value.backdrop != 'static' && (evt.target === evt.currentTarget)) {
evt.preventDefault();
evt.stopPropagation();
$modalStack.dismiss(modal.key, 'backdrop click');
}
};
}
}])
.directive('modalWindow', [
'$modalStack', '$q', '$animate',
function ($modalStack , $q , $animate) {
return {
restrict: 'EA',
scope: {
index: '@'
},
replace: true,
transclude: true,
templateUrl: function(tElement, tAttrs) {
return tAttrs.templateUrl || 'template/modal/window.html';
},
link: function (scope, element, attrs) {
element.addClass(attrs.windowClass || '');
scope.size = attrs.size;
scope.close = function (evt) {
var modal = $modalStack.getTop();
if (modal && modal.value.backdrop && modal.value.backdrop != 'static' && (evt.target === evt.currentTarget)) {
evt.preventDefault();
evt.stopPropagation();
$modalStack.dismiss(modal.key, 'backdrop click');
}
};
// This property is only added to the scope for the purpose of detecting when this directive is rendered.
// We can detect that by using this property in the template associated with this directive and then use
// {@link Attribute#$observe} on it. For more details please see {@link TableColumnResize}.
scope.$isRendered = true;
// Deferred object that will be resolved when this modal is render.
var modalRenderDeferObj = $q.defer();
// Observe function will be called on next digest cycle after compilation, ensuring that the DOM is ready.
// In order to use this way of finding whether DOM is ready, we need to observe a scope property used in modal's template.
attrs.$observe('modalRender', function (value) {
if (value == 'true') {
modalRenderDeferObj.resolve();
}
});
modalRenderDeferObj.promise.then(function () {
if (attrs.modalInClass) {
$animate.addClass(element, attrs.modalInClass);
scope.$on($modalStack.NOW_CLOSING_EVENT, function (e, setIsAsync) {
var done = setIsAsync();
$animate.removeClass(element, attrs.modalInClass).then(done);
});
}
var inputsWithAutofocus = element[0].querySelectorAll('[autofocus]');
/**
* Auto-focusing of a freshly-opened modal element causes any child elements
* with the autofocus attribute to lose focus. This is an issue on touch
* based devices which will show and then hide the onscreen keyboard.
* Attempts to refocus the autofocus element via JavaScript will not reopen
* the onscreen keyboard. Fixed by updated the focusing logic to only autofocus
* the modal element if the modal does not contain an autofocus element.
*/
if (inputsWithAutofocus.length) {
inputsWithAutofocus[0].focus();
} else {
element[0].focus();
}
// Notify {@link $modalStack} that modal is rendered.
var modal = $modalStack.getTop();
if (modal) {
$modalStack.modalRendered(modal.key);
}
});
}
};
}])
.directive('modalAnimationClass', [
function () {
return {
compile: function (tElement, tAttrs) {
if (tAttrs.modalAnimation) {
tElement.addClass(tAttrs.modalAnimationClass);
}
}
};
}])
.directive('modalTransclude', function () {
return {
link: function($scope, $element, $attrs, controller, $transclude) {
$transclude($scope.$parent, function(clone) {
$element.empty();
$element.append(clone);
});
}
};
})
.factory('$modalStack', [
'$animate', '$timeout', '$document', '$compile', '$rootScope',
'$q',
'$$stackedMap',
function ($animate , $timeout , $document , $compile , $rootScope ,
$q,
$$stackedMap) {
var OPENED_MODAL_CLASS = 'modal-open';
var backdropDomEl, backdropScope;
var openedWindows = $$stackedMap.createNew();
var $modalStack = {
NOW_CLOSING_EVENT: 'modal.stack.now-closing'
};
function backdropIndex() {
var topBackdropIndex = -1;
var opened = openedWindows.keys();
for (var i = 0; i < opened.length; i++) {
if (openedWindows.get(opened[i]).value.backdrop) {
topBackdropIndex = i;
}
}
return topBackdropIndex;
}
$rootScope.$watch(backdropIndex, function(newBackdropIndex){
if (backdropScope) {
backdropScope.index = newBackdropIndex;
}
});
function removeModalWindow(modalInstance, elementToReceiveFocus) {
// var modalWindow = openedWindows.get(modalInstance).value;
// IW CUSTOM
// we only work with 1 modal
var modalWindow = openedWindows.top().value;
var body = $document.find('body').eq(0);
//clean up the stack
// openedWindows.remove(modalInstance);
// only deal with the 1 modal
openedWindows.removeTop();
//remove window DOM element
removeAfterAnimate(modalWindow.modalDomEl, modalWindow.modalScope, function() {
body.toggleClass(OPENED_MODAL_CLASS, openedWindows.length() > 0);
checkRemoveBackdrop();
});
//move focus to specified element if available, or else to body
if (elementToReceiveFocus && elementToReceiveFocus.focus) {
elementToReceiveFocus.focus();
} else {
body.focus();
}
}
function checkRemoveBackdrop() {
//remove backdrop if no longer needed
if (backdropDomEl && backdropIndex() == -1) {
var backdropScopeRef = backdropScope;
removeAfterAnimate(backdropDomEl, backdropScope, function () {
backdropScopeRef = null;
});
backdropDomEl = undefined;
backdropScope = undefined;
}
}
function removeAfterAnimate(domEl, scope, done) {
var asyncDeferred;
var asyncPromise = null;
var setIsAsync = function () {
if (!asyncDeferred) {
asyncDeferred = $q.defer();
asyncPromise = asyncDeferred.promise;
}
return function asyncDone() {
asyncDeferred.resolve();
};
};
scope.$broadcast($modalStack.NOW_CLOSING_EVENT, setIsAsync);
// Note that it's intentional that asyncPromise might be null.
// That's when setIsAsync has not been called during the
// NOW_CLOSING_EVENT broadcast.
return $q.when(asyncPromise).then(afterAnimating);
function afterAnimating() {
if (afterAnimating.done) {
return;
}
afterAnimating.done = true;
domEl.remove();
scope.$destroy();
if (done) {
done();
}
}
}
$document.bind('keydown', function (evt) {
var modal;
if (evt.which === 27) {
// IW CUSTOM
// block esc close if modal is forcing user action
if (!$rootScope.modalForceAction){
modal = openedWindows.top();
if (modal && modal.value.keyboard) {
evt.preventDefault();
$rootScope.$apply(function () {
$modalStack.dismiss(modal.key, 'escape key press');
});
}
}
}
});
$modalStack.open = function (modalInstance, modal) {
// IW CUSTOM
// modified to support breadcrumb titled modals
if (openedWindows.length() === 0) {
openedWindows.add(modalInstance, {
deferred: modal.deferred,
renderDeferred: modal.renderDeferred,
modalScope: modal.scope,
backdrop: modal.backdrop,
keyboard: modal.keyboard
});
var modalOpener = $document[0].activeElement;
var body = $document.find('body').eq(0),
currBackdropIndex = backdropIndex();
if (currBackdropIndex >= 0 && !backdropDomEl) {
backdropScope = $rootScope.$new(true);
backdropScope.index = currBackdropIndex;
var angularBackgroundDomEl = angular.element('<div modal-backdrop="modal-backdrop"></div>');
angularBackgroundDomEl.attr('backdrop-class', modal.backdropClass);
if (modal.animation) {
angularBackgroundDomEl.attr('modal-animation', 'true');
}
backdropDomEl = $compile(angularBackgroundDomEl)(backdropScope);
body.append(backdropDomEl);
}
var angularDomEl = angular.element('<div modal-window="modal-window"></div>');
angularDomEl.attr({
'template-url': modal.windowTemplateUrl,
'window-class': modal.windowClass,
'size': modal.size,
'index': openedWindows.length() - 1,
'animate': 'animate'
}).html(modal.content);
if (modal.animation) {
angularDomEl.attr('modal-animation', 'true');
}
var modalDomEl = $compile(angularDomEl)(modal.scope);
openedWindows.top().value.modalDomEl = modalDomEl;
openedWindows.top().value.modalOpener = modalOpener;
body.append(modalDomEl);
body.addClass(OPENED_MODAL_CLASS);
} else {
// destroy current modal-body scope before inserting new content modal
var modalWindow = openedWindows.top().value;
var modalBody = angular.element('.modal .modal-body');
// destroy current content scope
var modalContentScope = modalBody.find('> div[data-ng-transclude] > div');
if (modalContentScope.length === 0) {
// was not a root modal window (first crumb)
modalContentScope = modalBody.find('> div').scope();
} else {
modalContentScope = modalContentScope.scope();
}
if (modalContentScope) {
modalContentScope.$destroy();
}
// insert new body
var modalContent = $compile(angular.element(modal.content))(modal.scope);
modalBody.html(modalContent);
// update windowClass
modalWindow.modalScope.windowClass = modal.windowClass;
}
};
function broadcastClosing(modalWindow, resultOrReason, closing) {
return !modalWindow.value.modalScope.$broadcast('modal.closing', resultOrReason, closing).defaultPrevented;
}
$modalStack.close = function (modalInstance, result) {
// var modalWindow = openedWindows.get(modalInstance);
// IW CUSTOM
// always grab top window, since we only want one 1 modal ever
var modalWindow = openedWindows.top();
if (modalWindow && broadcastClosing(modalWindow, result, true)) {
modalWindow.value.deferred.resolve(result);
removeModalWindow(modalInstance, modalWindow.value.modalOpener);
return true;
}
return !modalWindow;
};
$modalStack.dismiss = function (modalInstance, reason) {
// var modalWindow = openedWindows.get(modalInstance);
// IW CUSTOM
// always grab top window, since we only want one 1 modal ever
var modalWindow = openedWindows.top();
if (modalWindow && broadcastClosing(modalWindow, reason, false)) {
modalWindow.value.deferred.reject(reason);
removeModalWindow(modalInstance, modalWindow.value.modalOpener);
return true;
}
return !modalWindow;
};
$modalStack.dismissAll = function (reason) {
var topModal = this.getTop();
while (topModal && this.dismiss(topModal.key, reason)) {
topModal = this.getTop();
}
};
$modalStack.getTop = function () {
return openedWindows.top();
};
$modalStack.modalRendered = function (modalInstance) {
var modalWindow = openedWindows.get(modalInstance);
if (modalWindow) {
modalWindow.value.renderDeferred.resolve();
}
};
return $modalStack;
}])
.provider('$modal', function () {
var $modalProvider = {
options: {
animation: true,
backdrop: true, //can also be false or 'static'
keyboard: true
},
$get: ['$injector', '$rootScope', '$q', '$templateRequest', '$controller', '$modalStack',
function ($injector, $rootScope, $q, $templateRequest, $controller, $modalStack) {
var $modal = {};
function getTemplatePromise(options) {
return options.template ? $q.when(options.template) :
$templateRequest(angular.isFunction(options.templateUrl) ? (options.templateUrl)() : options.templateUrl);
}
function getResolvePromises(resolves) {
var promisesArr = [];
angular.forEach(resolves, function (value) {
if (angular.isFunction(value) || angular.isArray(value)) {
promisesArr.push($q.when($injector.invoke(value)));
}
});
return promisesArr;
}
$modal.open = function (modalOptions) {
var modalResultDeferred = $q.defer();
var modalOpenedDeferred = $q.defer();
var modalRenderDeferred = $q.defer();
//prepare an instance of a modal to be injected into controllers and returned to a caller
var modalInstance = {
result: modalResultDeferred.promise,
opened: modalOpenedDeferred.promise,
rendered: modalRenderDeferred.promise,
close: function (result) {
return $modalStack.close(modalInstance, result);
},
dismiss: function (reason) {
return $modalStack.dismiss(modalInstance, reason);
}
};
//merge and clean up options
modalOptions = angular.extend({}, $modalProvider.options, modalOptions);
modalOptions.resolve = modalOptions.resolve || {};
//verify options
if (!modalOptions.template && !modalOptions.templateUrl) {
throw new Error('One of template or templateUrl options is required.');
}
var templateAndResolvePromise =
$q.all([getTemplatePromise(modalOptions)].concat(getResolvePromises(modalOptions.resolve)));
templateAndResolvePromise.then(function resolveSuccess(tplAndVars) {
var modalScope = (modalOptions.scope || $rootScope).$new();
modalScope.$close = modalInstance.close;
modalScope.$dismiss = modalInstance.dismiss;
var ctrlInstance, ctrlLocals = {};
var resolveIter = 1;
//controllers
if (modalOptions.controller) {
ctrlLocals.$scope = modalScope;
ctrlLocals.$modalInstance = modalInstance;
angular.forEach(modalOptions.resolve, function (value, key) {
ctrlLocals[key] = tplAndVars[resolveIter++];
});
ctrlInstance = $controller(modalOptions.controller, ctrlLocals);
if (modalOptions.controllerAs) {
modalScope[modalOptions.controllerAs] = ctrlInstance;
}
}
$modalStack.open(modalInstance, {
scope: modalScope,
deferred: modalResultDeferred,
renderDeferred: modalRenderDeferred,
content: tplAndVars[0],
animation: modalOptions.animation,
backdrop: modalOptions.backdrop,
keyboard: modalOptions.keyboard,
backdropClass: modalOptions.backdropClass,
windowClass: modalOptions.windowClass,
windowTemplateUrl: modalOptions.windowTemplateUrl,
size: modalOptions.size
});
}, function resolveError(reason) {
modalResultDeferred.reject(reason);
});
templateAndResolvePromise.then(function () {
modalOpenedDeferred.resolve(true);
}, function (reason) {
modalOpenedDeferred.reject(reason);
});
return modalInstance;
};
return $modal;
}]
};
return $modalProvider;
});
angular.module('ui.bootstrap.pagination', [])
.controller('PaginationController', ['$scope', '$attrs', '$parse', function ($scope, $attrs, $parse) {
var self = this,
ngModelCtrl = { $setViewValue: angular.noop }, // nullModelCtrl
setNumPages = $attrs.numPages ? $parse($attrs.numPages).assign : angular.noop;
this.init = function(ngModelCtrl_, config) {
ngModelCtrl = ngModelCtrl_;
this.config = config;
ngModelCtrl.$render = function() {
self.render();
};
if ($attrs.itemsPerPage) {
$scope.$parent.$watch($parse($attrs.itemsPerPage), function(value) {
self.itemsPerPage = parseInt(value, 10);
$scope.totalPages = self.calculateTotalPages();
});
} else {
this.itemsPerPage = config.itemsPerPage;
}
$scope.$watch('totalItems', function() {
$scope.totalPages = self.calculateTotalPages();
});
$scope.$watch('totalPages', function(value) {
setNumPages($scope.$parent, value); // Readonly variable
if ( $scope.page > value ) {
$scope.selectPage(value);
} else {
ngModelCtrl.$render();
}
});
};
this.calculateTotalPages = function() {
var totalPages = this.itemsPerPage < 1 ? 1 : Math.ceil($scope.totalItems / this.itemsPerPage);
return Math.max(totalPages || 0, 1);
};
this.render = function() {
$scope.page = parseInt(ngModelCtrl.$viewValue, 10) || 1;
};
$scope.selectPage = function(page, evt) {
if ( $scope.page !== page && page > 0 && page <= $scope.totalPages) {
if (evt && evt.target) {
evt.target.blur();
}
ngModelCtrl.$setViewValue(page);
ngModelCtrl.$render();
}
};
$scope.getText = function( key ) {
return $scope[key + 'Text'] || self.config[key + 'Text'];
};
$scope.noPrevious = function() {
return $scope.page === 1;
};
$scope.noNext = function() {
return $scope.page === $scope.totalPages;
};
}])
.constant('paginationConfig', {
itemsPerPage: 10,
boundaryLinks: false,
directionLinks: true,
firstText: 'First',
previousText: 'Previous',
nextText: 'Next',
lastText: 'Last',
rotate: true
})
.directive('pagination', ['$parse', 'paginationConfig', function($parse, paginationConfig) {
return {
restrict: 'EA',
scope: {
totalItems: '=',
firstText: '@',
previousText: '@',
nextText: '@',
lastText: '@'
},
require: ['pagination', '?ngModel'],
controller: 'PaginationController',
templateUrl: 'template/pagination/pagination.html',
replace: true,
link: function(scope, element, attrs, ctrls) {
var paginationCtrl = ctrls[0], ngModelCtrl = ctrls[1];
if (!ngModelCtrl) {
return; // do nothing if no ng-model
}
// Setup configuration parameters
var maxSize = angular.isDefined(attrs.maxSize) ? scope.$parent.$eval(attrs.maxSize) : paginationConfig.maxSize,
rotate = angular.isDefined(attrs.rotate) ? scope.$parent.$eval(attrs.rotate) : paginationConfig.rotate;
scope.boundaryLinks = angular.isDefined(attrs.boundaryLinks) ? scope.$parent.$eval(attrs.boundaryLinks) : paginationConfig.boundaryLinks;
scope.directionLinks = angular.isDefined(attrs.directionLinks) ? scope.$parent.$eval(attrs.directionLinks) : paginationConfig.directionLinks;
paginationCtrl.init(ngModelCtrl, paginationConfig);
if (attrs.maxSize) {
scope.$parent.$watch($parse(attrs.maxSize), function(value) {
maxSize = parseInt(value, 10);
paginationCtrl.render();
});
}
// Create page object used in template
function makePage(number, text, isActive) {
return {
number: number,
text: text,
active: isActive
};
}
function getPages(currentPage, totalPages) {
var pages = [];
// Default page limits
var startPage = 1, endPage = totalPages;
var isMaxSized = ( angular.isDefined(maxSize) && maxSize < totalPages );
// recompute if maxSize
if ( isMaxSized ) {
if ( rotate ) {
// Current page is displayed in the middle of the visible ones
startPage = Math.max(currentPage - Math.floor(maxSize/2), 1);
endPage = startPage + maxSize - 1;
// Adjust if limit is exceeded
if (endPage > totalPages) {
endPage = totalPages;
startPage = endPage - maxSize + 1;
}
} else {
// Visible pages are paginated with maxSize
startPage = ((Math.ceil(currentPage / maxSize) - 1) * maxSize) + 1;
// Adjust last page if limit is exceeded
endPage = Math.min(startPage + maxSize - 1, totalPages);
}
}
// Add page number links
for (var number = startPage; number <= endPage; number++) {
var page = makePage(number, number, number === currentPage);
pages.push(page);
}
// Add links to move between page sets
if ( isMaxSized && ! rotate ) {
if ( startPage > 1 ) {
var previousPageSet = makePage(startPage - 1, '...', false);
pages.unshift(previousPageSet);
}
if ( endPage < totalPages ) {
var nextPageSet = makePage(endPage + 1, '...', false);
pages.push(nextPageSet);
}
}
return pages;
}
var originalRender = paginationCtrl.render;
paginationCtrl.render = function() {
originalRender();
if (scope.page > 0 && scope.page <= scope.totalPages) {
scope.pages = getPages(scope.page, scope.totalPages);
}
};
}
};
}])
.constant('pagerConfig', {
itemsPerPage: 10,
previousText: '« Previous',
nextText: 'Next »',
align: true
})
.directive('pager', ['pagerConfig', function(pagerConfig) {
return {
restrict: 'EA',
scope: {
totalItems: '=',
previousText: '@',
nextText: '@'
},
require: ['pager', '?ngModel'],
controller: 'PaginationController',
templateUrl: 'template/pagination/pager.html',
replace: true,
link: function(scope, element, attrs, ctrls) {
var paginationCtrl = ctrls[0], ngModelCtrl = ctrls[1];
if (!ngModelCtrl) {
return; // do nothing if no ng-model
}
scope.align = angular.isDefined(attrs.align) ? scope.$parent.$eval(attrs.align) : pagerConfig.align;
paginationCtrl.init(ngModelCtrl, pagerConfig);
}
};
}]);
/**
* The following features are still outstanding: animation as a
* function, placement as a function, inside, support for more triggers than
* just mouse enter/leave, html tooltips, and selector delegation.
*/
angular.module( 'ui.bootstrap.tooltip', [ 'ui.bootstrap.position', 'ui.bootstrap.bindHtml' ] )
/**
* The $tooltip service creates tooltip- and popover-like directives as well as
* houses global options for them.
*/
.provider( '$tooltip', function () {
// The default options tooltip and popover.
var defaultOptions = {
placement: 'top',
animation: true,
popupDelay: 0,
useContentExp: false
};
// Default hide triggers for each show trigger
var triggerMap = {
'mouseenter': 'mouseleave',
'click': 'click',
'focus': 'blur'
};
// The options specified to the provider globally.
var globalOptions = {};
/**
* `options({})` allows global configuration of all tooltips in the
* application.
*
* var app = angular.module( 'App', ['ui.bootstrap.tooltip'], function( $tooltipProvider ) {
* // place tooltips left instead of top by default
* $tooltipProvider.options( { placement: 'left' } );
* });
*/
this.options = function( value ) {
angular.extend( globalOptions, value );
};
/**
* This allows you to extend the set of trigger mappings available. E.g.:
*
* $tooltipProvider.setTriggers( 'openTrigger': 'closeTrigger' );
*/
this.setTriggers = function setTriggers ( triggers ) {
angular.extend( triggerMap, triggers );
};
/**
* This is a helper function for translating camel-case to snake-case.
*/
function snake_case(name){
var regexp = /[A-Z]/g;
var separator = '-';
return name.replace(regexp, function(letter, pos) {
return (pos ? separator : '') + letter.toLowerCase();
});
}
/**
* Returns the actual instance of the $tooltip service.
* TODO support multiple triggers
*/
this.$get = [ '$window', '$compile', '$timeout', '$document', '$position', '$interpolate', function ( $window, $compile, $timeout, $document, $position, $interpolate ) {
return function $tooltip ( type, prefix, defaultTriggerShow, options ) {
options = angular.extend( {}, defaultOptions, globalOptions, options );
/**
* Returns an object of show and hide triggers.
*
* If a trigger is supplied,
* it is used to show the tooltip; otherwise, it will use the `trigger`
* option passed to the `$tooltipProvider.options` method; else it will
* default to the trigger supplied to this directive factory.
*
* The hide trigger is based on the show trigger. If the `trigger` option
* was passed to the `$tooltipProvider.options` method, it will use the
* mapped trigger from `triggerMap` or the passed trigger if the map is
* undefined; otherwise, it uses the `triggerMap` value of the show
* trigger; else it will just use the show trigger.
*/
function getTriggers ( trigger ) {
var show = trigger || options.trigger || defaultTriggerShow;
var hide = triggerMap[show] || show;
return {
show: show,
hide: hide
};
}
var directiveName = snake_case( type );
var startSym = $interpolate.startSymbol();
var endSym = $interpolate.endSymbol();
var template =
'<div '+ directiveName +'-popup '+
'title="'+startSym+'title'+endSym+'" '+
(options.useContentExp ?
'content-exp="contentExp()" ' :
'content="'+startSym+'content'+endSym+'" ') +
'placement="'+startSym+'placement'+endSym+'" '+
'popup-class="'+startSym+'popupClass'+endSym+'" '+
'animation="animation" '+
'is-open="isOpen"'+
'origin-scope="origScope" '+
'>'+
'</div>';
return {
restrict: 'EA',
compile: function (tElem, tAttrs) {
var tooltipLinker = $compile( template );
return function link ( scope, element, attrs, tooltipCtrl ) {
var tooltip;
var tooltipLinkedScope;
var transitionTimeout;
var popupTimeout;
var appendToBody = angular.isDefined( options.appendToBody ) ? options.appendToBody : false;
var triggers = getTriggers( undefined );
var hasEnableExp = angular.isDefined(attrs[prefix+'Enable']);
var ttScope = scope.$new(true);
var positionTooltip = function () {
if (!tooltip) { return; }
var ttPosition = $position.positionElements(element, tooltip, ttScope.placement, appendToBody);
ttPosition.top += 'px';
ttPosition.left += 'px';
// Now set the calculated positioning.
tooltip.css( ttPosition );
};
// Set up the correct scope to allow transclusion later
ttScope.origScope = scope;
// By default, the tooltip is not open.
// TODO add ability to start tooltip opened
ttScope.isOpen = false;
function toggleTooltipBind () {
if ( ! ttScope.isOpen ) {
showTooltipBind();
} else {
hideTooltipBind();
}
}
// Show the tooltip with delay if specified, otherwise show it immediately
function showTooltipBind() {
if(hasEnableExp && !scope.$eval(attrs[prefix+'Enable'])) {
return;
}
prepareTooltip();
if ( ttScope.popupDelay ) {
// Do nothing if the tooltip was already scheduled to pop-up.
// This happens if show is triggered multiple times before any hide is triggered.
if (!popupTimeout) {
popupTimeout = $timeout( show, ttScope.popupDelay, false );
popupTimeout.then(function(reposition){reposition();});
}
} else {
show()();
}
}
function hideTooltipBind () {
scope.$apply(function () {
hide();
});
}
// Show the tooltip popup element.
function show() {
popupTimeout = null;
// If there is a pending remove transition, we must cancel it, lest the
// tooltip be mysteriously removed.
if ( transitionTimeout ) {
$timeout.cancel( transitionTimeout );
transitionTimeout = null;
}
// Don't show empty tooltips.
if ( !(options.useContentExp ? ttScope.contentExp() : ttScope.content) ) {
return angular.noop;
}
createTooltip();
// Set the initial positioning.
tooltip.css({ top: 0, left: 0, display: 'block' });
ttScope.$digest();
positionTooltip();
// And show the tooltip.
ttScope.isOpen = true;
ttScope.$apply(); // digest required as $apply is not called
// Return positioning function as promise callback for correct
// positioning after draw.
return positionTooltip;
}
// Hide the tooltip popup element.
function hide() {
// First things first: we don't show it anymore.
ttScope.isOpen = false;
//if tooltip is going to be shown after delay, we must cancel this
$timeout.cancel( popupTimeout );
popupTimeout = null;
// And now we remove it from the DOM. However, if we have animation, we
// need to wait for it to expire beforehand.
// FIXME: this is a placeholder for a port of the transitions library.
if ( ttScope.animation ) {
if (!transitionTimeout) {
transitionTimeout = $timeout(removeTooltip, 500);
}
} else {
removeTooltip();
}
}
function createTooltip() {
// There can only be one tooltip element per directive shown at once.
if (tooltip) {
removeTooltip();
}
tooltipLinkedScope = ttScope.$new();
tooltip = tooltipLinker(tooltipLinkedScope, function (tooltip) {
if ( appendToBody ) {
$document.find( 'body' ).append( tooltip );
} else {
element.after( tooltip );
}
});
tooltipLinkedScope.$watch(function () {
$timeout(positionTooltip, 0, false);
});
if (options.useContentExp) {
tooltipLinkedScope.$watch('contentExp()', function (val) {
if (!val && ttScope.isOpen ) {
hide();
}
});
}
}
function removeTooltip() {
transitionTimeout = null;
if (tooltip) {
tooltip.remove();
tooltip = null;
}
if (tooltipLinkedScope) {
tooltipLinkedScope.$destroy();
tooltipLinkedScope = null;
}
}
function prepareTooltip() {
prepPopupClass();
prepPlacement();
prepPopupDelay();
}
ttScope.contentExp = function () {
return scope.$eval(attrs[type]);
};
/**
* Observe the relevant attributes.
*/
if (!options.useContentExp) {
attrs.$observe( type, function ( val ) {
ttScope.content = val;
if (!val && ttScope.isOpen ) {
hide();
}
});
}
attrs.$observe( 'disabled', function ( val ) {
if (val && ttScope.isOpen ) {
hide();
}
});
attrs.$observe( prefix+'Title', function ( val ) {
ttScope.title = val;
});
function prepPopupClass() {
ttScope.popupClass = attrs[prefix + 'Class'];
}
function prepPlacement() {
var val = attrs[ prefix + 'Placement' ];
ttScope.placement = angular.isDefined( val ) ? val : options.placement;
}
function prepPopupDelay() {
var val = attrs[ prefix + 'PopupDelay' ];
var delay = parseInt( val, 10 );
ttScope.popupDelay = ! isNaN(delay) ? delay : options.popupDelay;
}
var unregisterTriggers = function () {
element.unbind(triggers.show, showTooltipBind);
element.unbind(triggers.hide, hideTooltipBind);
};
function prepTriggers() {
var val = attrs[ prefix + 'Trigger' ];
unregisterTriggers();
triggers = getTriggers( val );
if ( triggers.show === triggers.hide ) {
element.bind( triggers.show, toggleTooltipBind );
} else {
element.bind( triggers.show, showTooltipBind );
element.bind( triggers.hide, hideTooltipBind );
}
}
prepTriggers();
var animation = scope.$eval(attrs[prefix + 'Animation']);
ttScope.animation = angular.isDefined(animation) ? !!animation : options.animation;
var appendToBodyVal = scope.$eval(attrs[prefix + 'AppendToBody']);
appendToBody = angular.isDefined(appendToBodyVal) ? appendToBodyVal : appendToBody;
// if a tooltip is attached to <body> we need to remove it on
// location change as its parent scope will probably not be destroyed
// by the change.
if ( appendToBody ) {
scope.$on('$locationChangeSuccess', function closeTooltipOnLocationChangeSuccess () {
if ( ttScope.isOpen ) {
hide();
}
});
}
// Make sure tooltip is destroyed and removed.
scope.$on('$destroy', function onDestroyTooltip() {
$timeout.cancel( transitionTimeout );
$timeout.cancel( popupTimeout );
unregisterTriggers();
removeTooltip();
ttScope = null;
});
};
}
};
};
}];
})
// This is mostly ngInclude code but with a custom scope
.directive( 'tooltipTemplateTransclude', [
'$animate', '$sce', '$compile', '$templateRequest',
function ($animate , $sce , $compile , $templateRequest) {
return {
link: function ( scope, elem, attrs ) {
var origScope = scope.$eval(attrs.tooltipTemplateTranscludeScope);
var changeCounter = 0,
currentScope,
previousElement,
currentElement;
var cleanupLastIncludeContent = function() {
if (previousElement) {
previousElement.remove();
previousElement = null;
}
if (currentScope) {
currentScope.$destroy();
currentScope = null;
}
if (currentElement) {
$animate.leave(currentElement).then(function() {
previousElement = null;
});
previousElement = currentElement;
currentElement = null;
}
};
scope.$watch($sce.parseAsResourceUrl(attrs.tooltipTemplateTransclude), function (src) {
var thisChangeId = ++changeCounter;
if (src) {
//set the 2nd param to true to ignore the template request error so that the inner
//contents and scope can be cleaned up.
$templateRequest(src, true).then(function(response) {
if (thisChangeId !== changeCounter) { return; }
var newScope = origScope.$new();
var template = response;
var clone = $compile(template)(newScope, function(clone) {
cleanupLastIncludeContent();
$animate.enter(clone, elem);
});
currentScope = newScope;
currentElement = clone;
currentScope.$emit('$includeContentLoaded', src);
}, function() {
if (thisChangeId === changeCounter) {
cleanupLastIncludeContent();
scope.$emit('$includeContentError', src);
}
});
scope.$emit('$includeContentRequested', src);
} else {
cleanupLastIncludeContent();
}
});
scope.$on('$destroy', cleanupLastIncludeContent);
}
};
}])
/**
* Note that it's intentional that these classes are *not* applied through $animate.
* They must not be animated as they're expected to be present on the tooltip on
* initialization.
*/
.directive('tooltipClasses', function () {
return {
restrict: 'A',
link: function (scope, element, attrs) {
if (scope.placement) {
element.addClass(scope.placement);
}
if (scope.popupClass) {
element.addClass(scope.popupClass);
}
if (scope.animation()) {
element.addClass(attrs.tooltipAnimationClass);
}
}
};
})
.directive( 'tooltipPopup', function () {
return {
restrict: 'EA',
replace: true,
scope: { content: '@', placement: '@', popupClass: '@', animation: '&', isOpen: '&' },
templateUrl: 'template/tooltip/tooltip-popup.html'
};
})
.directive( 'tooltip', [ '$tooltip', function ( $tooltip ) {
return $tooltip( 'tooltip', 'tooltip', 'mouseenter' );
}])
.directive( 'tooltipTemplatePopup', function () {
return {
restrict: 'EA',
replace: true,
scope: { contentExp: '&', placement: '@', popupClass: '@', animation: '&', isOpen: '&',
originScope: '&' },
templateUrl: 'template/tooltip/tooltip-template-popup.html'
};
})
.directive( 'tooltipTemplate', [ '$tooltip', function ( $tooltip ) {
return $tooltip('tooltipTemplate', 'tooltip', 'mouseenter', {
useContentExp: true
});
}])
.directive( 'tooltipHtmlPopup', function () {
return {
restrict: 'EA',
replace: true,
scope: { contentExp: '&', placement: '@', popupClass: '@', animation: '&', isOpen: '&' },
templateUrl: 'template/tooltip/tooltip-html-popup.html'
};
})
.directive( 'tooltipHtml', [ '$tooltip', function ( $tooltip ) {
return $tooltip('tooltipHtml', 'tooltip', 'mouseenter', {
useContentExp: true
});
}])
/*
Deprecated
*/
.directive( 'tooltipHtmlUnsafePopup', function () {
return {
restrict: 'EA',
replace: true,
scope: { content: '@', placement: '@', popupClass: '@', animation: '&', isOpen: '&' },
templateUrl: 'template/tooltip/tooltip-html-unsafe-popup.html'
};
})
.value('tooltipHtmlUnsafeSuppressDeprecated', false)
.directive( 'tooltipHtmlUnsafe', [
'$tooltip', 'tooltipHtmlUnsafeSuppressDeprecated', '$log',
function ( $tooltip , tooltipHtmlUnsafeSuppressDeprecated , $log) {
if (!tooltipHtmlUnsafeSuppressDeprecated) {
$log.warn('tooltip-html-unsafe is now deprecated. Use tooltip-html or tooltip-template instead.');
}
return $tooltip( 'tooltipHtmlUnsafe', 'tooltip', 'mouseenter' );
}]);
/**
* The following features are still outstanding: popup delay, animation as a
* function, placement as a function, inside, support for more triggers than
* just mouse enter/leave, html popovers, and selector delegatation.
*/
angular.module( 'ui.bootstrap.popover', [ 'ui.bootstrap.tooltip' ] )
.directive( 'popoverTemplatePopup', function () {
return {
restrict: 'EA',
replace: true,
scope: { title: '@', contentExp: '&', placement: '@', popupClass: '@', animation: '&', isOpen: '&',
originScope: '&' },
templateUrl: 'template/popover/popover-template.html'
};
})
.directive( 'popoverTemplate', [ '$tooltip', function ( $tooltip ) {
return $tooltip( 'popoverTemplate', 'popover', 'click', {
useContentExp: true
} );
}])
.directive( 'popoverPopup', function () {
return {
restrict: 'EA',
replace: true,
scope: { title: '@', content: '@', placement: '@', popupClass: '@', animation: '&', isOpen: '&' },
templateUrl: 'template/popover/popover.html'
};
})
.directive( 'popover', [ '$tooltip', function ( $tooltip ) {
return $tooltip( 'popover', 'popover', 'click' );
}]);
angular.module('ui.bootstrap.progressbar', [])
.constant('progressConfig', {
animate: true,
max: 100
})
.controller('ProgressController', ['$scope', '$attrs', 'progressConfig', function($scope, $attrs, progressConfig) {
var self = this,
animate = angular.isDefined($attrs.animate) ? $scope.$parent.$eval($attrs.animate) : progressConfig.animate;
this.bars = [];
$scope.max = angular.isDefined($scope.max) ? $scope.max : progressConfig.max;
this.addBar = function(bar, element) {
if ( !animate ) {
element.css({'transition': 'none'});
}
this.bars.push(bar);
bar.max = $scope.max;
bar.$watch('value', function( value ) {
bar.recalculatePercentage();
});
bar.recalculatePercentage = function() {
bar.percent = +(100 * bar.value / bar.max).toFixed(2);
};
bar.$on('$destroy', function() {
element = null;
self.removeBar(bar);
});
};
this.removeBar = function(bar) {
this.bars.splice(this.bars.indexOf(bar), 1);
};
$scope.$watch('max', function(max) {
self.bars.forEach(function (bar) {
bar.max = $scope.max;
bar.recalculatePercentage();
});
});
}])
.directive('progress', function() {
return {
restrict: 'EA',
replace: true,
transclude: true,
controller: 'ProgressController',
require: 'progress',
scope: {
max: '=?'
},
templateUrl: 'template/progressbar/progress.html'
};
})
.directive('bar', function() {
return {
restrict: 'EA',
replace: true,
transclude: true,
require: '^progress',
scope: {
value: '=',
type: '@'
},
templateUrl: 'template/progressbar/bar.html',
link: function(scope, element, attrs, progressCtrl) {
progressCtrl.addBar(scope, element);
}
};
})
.directive('progressbar', function() {
return {
restrict: 'EA',
replace: true,
transclude: true,
controller: 'ProgressController',
scope: {
value: '=',
max: '=?',
type: '@'
},
templateUrl: 'template/progressbar/progressbar.html',
link: function(scope, element, attrs, progressCtrl) {
progressCtrl.addBar(scope, angular.element(element.children()[0]));
}
};
});
angular.module('ui.bootstrap.rating', [])
.constant('ratingConfig', {
max: 5,
stateOn: null,
stateOff: null
})
.controller('RatingController', ['$scope', '$attrs', 'ratingConfig', function($scope, $attrs, ratingConfig) {
var ngModelCtrl = { $setViewValue: angular.noop };
this.init = function(ngModelCtrl_) {
ngModelCtrl = ngModelCtrl_;
ngModelCtrl.$render = this.render;
ngModelCtrl.$formatters.push(function(value) {
if (angular.isNumber(value) && value << 0 !== value) {
value = Math.round(value);
}
return value;
});
this.stateOn = angular.isDefined($attrs.stateOn) ? $scope.$parent.$eval($attrs.stateOn) : ratingConfig.stateOn;
this.stateOff = angular.isDefined($attrs.stateOff) ? $scope.$parent.$eval($attrs.stateOff) : ratingConfig.stateOff;
var ratingStates = angular.isDefined($attrs.ratingStates) ? $scope.$parent.$eval($attrs.ratingStates) :
new Array( angular.isDefined($attrs.max) ? $scope.$parent.$eval($attrs.max) : ratingConfig.max );
$scope.range = this.buildTemplateObjects(ratingStates);
};
this.buildTemplateObjects = function(states) {
for (var i = 0, n = states.length; i < n; i++) {
states[i] = angular.extend({ index: i }, { stateOn: this.stateOn, stateOff: this.stateOff }, states[i]);
}
return states;
};
$scope.rate = function(value) {
if ( !$scope.readonly && value >= 0 && value <= $scope.range.length ) {
ngModelCtrl.$setViewValue(value);
ngModelCtrl.$render();
}
};
$scope.enter = function(value) {
if ( !$scope.readonly ) {
$scope.value = value;
}
$scope.onHover({value: value});
};
$scope.reset = function() {
$scope.value = ngModelCtrl.$viewValue;
$scope.onLeave();
};
$scope.onKeydown = function(evt) {
if (/(37|38|39|40)/.test(evt.which)) {
evt.preventDefault();
evt.stopPropagation();
$scope.rate( $scope.value + (evt.which === 38 || evt.which === 39 ? 1 : -1) );
}
};
this.render = function() {
$scope.value = ngModelCtrl.$viewValue;
};
}])
.directive('rating', function() {
return {
restrict: 'EA',
require: ['rating', 'ngModel'],
scope: {
readonly: '=?',
onHover: '&',
onLeave: '&'
},
controller: 'RatingController',
templateUrl: 'template/rating/rating.html',
replace: true,
link: function(scope, element, attrs, ctrls) {
var ratingCtrl = ctrls[0], ngModelCtrl = ctrls[1];
ratingCtrl.init( ngModelCtrl );
}
};
});
/**
* @ngdoc overview
* @name ui.bootstrap.tabs
*
* @description
* AngularJS version of the tabs directive.
*/
angular.module('ui.bootstrap.tabs', [])
.controller('TabsetController', ['$scope', function TabsetCtrl($scope) {
var ctrl = this,
tabs = ctrl.tabs = $scope.tabs = [];
ctrl.select = function(selectedTab) {
angular.forEach(tabs, function(tab) {
if (tab.active && tab !== selectedTab) {
tab.active = false;
tab.onDeselect();
}
});
selectedTab.active = true;
selectedTab.onSelect();
};
ctrl.addTab = function addTab(tab) {
tabs.push(tab);
// we can't run the select function on the first tab
// since that would select it twice
if (tabs.length === 1 && tab.active !== false) {
tab.active = true;
} else if (tab.active) {
ctrl.select(tab);
}
else {
tab.active = false;
}
};
ctrl.removeTab = function removeTab(tab) {
var index = tabs.indexOf(tab);
//Select a new tab if the tab to be removed is selected and not destroyed
if (tab.active && tabs.length > 1 && !destroyed) {
//If this is the last tab, select the previous tab. else, the next tab.
var newActiveIndex = index == tabs.length - 1 ? index - 1 : index + 1;
ctrl.select(tabs[newActiveIndex]);
}
tabs.splice(index, 1);
};
var destroyed;
$scope.$on('$destroy', function() {
destroyed = true;
});
}])
/**
* @ngdoc directive
* @name ui.bootstrap.tabs.directive:tabset
* @restrict EA
*
* @description
* Tabset is the outer container for the tabs directive
*
* @param {boolean=} vertical Whether or not to use vertical styling for the tabs.
* @param {boolean=} justified Whether or not to use justified styling for the tabs.
*
* @example
<example module="ui.bootstrap">
<file name="index.html">
<tabset>
<tab heading="Tab 1"><b>First</b> Content!</tab>
<tab heading="Tab 2"><i>Second</i> Content!</tab>
</tabset>
<hr />
<tabset vertical="true">
<tab heading="Vertical Tab 1"><b>First</b> Vertical Content!</tab>
<tab heading="Vertical Tab 2"><i>Second</i> Vertical Content!</tab>
</tabset>
<tabset justified="true">
<tab heading="Justified Tab 1"><b>First</b> Justified Content!</tab>
<tab heading="Justified Tab 2"><i>Second</i> Justified Content!</tab>
</tabset>
</file>
</example>
*/
.directive('tabset', function() {
return {
restrict: 'EA',
transclude: true,
replace: true,
scope: {
type: '@'
},
controller: 'TabsetController',
templateUrl: 'template/tabs/tabset.html',
link: function(scope, element, attrs) {
scope.vertical = angular.isDefined(attrs.vertical) ? scope.$parent.$eval(attrs.vertical) : false;
scope.justified = angular.isDefined(attrs.justified) ? scope.$parent.$eval(attrs.justified) : false;
}
};
})
/**
* @ngdoc directive
* @name ui.bootstrap.tabs.directive:tab
* @restrict EA
*
* @param {string=} heading The visible heading, or title, of the tab. Set HTML headings with {@link ui.bootstrap.tabs.directive:tabHeading tabHeading}.
* @param {string=} select An expression to evaluate when the tab is selected.
* @param {boolean=} active A binding, telling whether or not this tab is selected.
* @param {boolean=} disabled A binding, telling whether or not this tab is disabled.
*
* @description
* Creates a tab with a heading and content. Must be placed within a {@link ui.bootstrap.tabs.directive:tabset tabset}.
*
* @example
<example module="ui.bootstrap">
<file name="index.html">
<div ng-controller="TabsDemoCtrl">
<button class="btn btn-small" ng-click="items[0].active = true">
Select item 1, using active binding
</button>
<button class="btn btn-small" ng-click="items[1].disabled = !items[1].disabled">
Enable/disable item 2, using disabled binding
</button>
<br />
<tabset>
<tab heading="Tab 1">First Tab</tab>
<tab select="alertMe()">
<tab-heading><i class="icon-bell"></i> Alert me!</tab-heading>
Second Tab, with alert callback and html heading!
</tab>
<tab ng-repeat="item in items"
heading="{{item.title}}"
disabled="item.disabled"
active="item.active">
{{item.content}}
</tab>
</tabset>
</div>
</file>
<file name="script.js">
function TabsDemoCtrl($scope) {
$scope.items = [
{ title:"Dynamic Title 1", content:"Dynamic Item 0" },
{ title:"Dynamic Title 2", content:"Dynamic Item 1", disabled: true }
];
$scope.alertMe = function() {
setTimeout(function() {
alert("You've selected the alert tab!");
});
};
};
</file>
</example>
*/
/**
* @ngdoc directive
* @name ui.bootstrap.tabs.directive:tabHeading
* @restrict EA
*
* @description
* Creates an HTML heading for a {@link ui.bootstrap.tabs.directive:tab tab}. Must be placed as a child of a tab element.
*
* @example
<example module="ui.bootstrap">
<file name="index.html">
<tabset>
<tab>
<tab-heading><b>HTML</b> in my titles?!</tab-heading>
And some content, too!
</tab>
<tab>
<tab-heading><i class="icon-heart"></i> Icon heading?!?</tab-heading>
That's right.
</tab>
</tabset>
</file>
</example>
*/
.directive('tab', ['$parse', '$log', function($parse, $log) {
return {
require: '^tabset',
restrict: 'EA',
replace: true,
templateUrl: 'template/tabs/tab.html',
transclude: true,
scope: {
active: '=?',
heading: '@',
onSelect: '&select', //This callback is called in contentHeadingTransclude
//once it inserts the tab's content into the dom
onDeselect: '&deselect'
},
controller: function() {
//Empty controller so other directives can require being 'under' a tab
},
compile: function(elm, attrs, transclude) {
return function postLink(scope, elm, attrs, tabsetCtrl) {
scope.$watch('active', function(active) {
if (active) {
tabsetCtrl.select(scope);
}
});
scope.disabled = false;
if ( attrs.disable ) {
scope.$parent.$watch($parse(attrs.disable), function(value) {
scope.disabled = !! value;
});
}
// Deprecation support of "disabled" parameter
// fix(tab): IE9 disabled attr renders grey text on enabled tab #2677
// This code is duplicated from the lines above to make it easy to remove once
// the feature has been completely deprecated
if ( attrs.disabled ) {
$log.warn('Use of "disabled" attribute has been deprecated, please use "disable"');
scope.$parent.$watch($parse(attrs.disabled), function(value) {
scope.disabled = !! value;
});
}
scope.select = function() {
if ( !scope.disabled ) {
scope.active = true;
}
};
tabsetCtrl.addTab(scope);
scope.$on('$destroy', function() {
tabsetCtrl.removeTab(scope);
});
//We need to transclude later, once the content container is ready.
//when this link happens, we're inside a tab heading.
scope.$transcludeFn = transclude;
};
}
};
}])
.directive('tabHeadingTransclude', [function() {
return {
restrict: 'A',
require: '^tab',
link: function(scope, elm, attrs, tabCtrl) {
scope.$watch('headingElement', function updateHeadingElement(heading) {
if (heading) {
elm.html('');
elm.append(heading);
}
});
}
};
}])
.directive('tabContentTransclude', function() {
return {
restrict: 'A',
require: '^tabset',
link: function(scope, elm, attrs) {
var tab = scope.$eval(attrs.tabContentTransclude);
//Now our tab is ready to be transcluded: both the tab heading area
//and the tab content area are loaded. Transclude 'em both.
tab.$transcludeFn(tab.$parent, function(contents) {
angular.forEach(contents, function(node) {
if (isTabHeading(node)) {
//Let tabHeadingTransclude know.
tab.headingElement = node;
} else {
elm.append(node);
}
});
});
}
};
function isTabHeading(node) {
return node.tagName && (
node.hasAttribute('tab-heading') ||
node.hasAttribute('data-tab-heading') ||
node.tagName.toLowerCase() === 'tab-heading' ||
node.tagName.toLowerCase() === 'data-tab-heading'
);
}
})
;
angular.module('ui.bootstrap.timepicker', [])
.constant('timepickerConfig', {
hourStep: 1,
minuteStep: 1,
showMeridian: true,
meridians: null,
readonlyInput: false,
mousewheel: true,
arrowkeys: true,
showSpinners: true
})
.controller('TimepickerController', ['$scope', '$attrs', '$parse', '$log', '$locale', 'timepickerConfig', function($scope, $attrs, $parse, $log, $locale, timepickerConfig) {
var selected = new Date(),
ngModelCtrl = { $setViewValue: angular.noop }, // nullModelCtrl
meridians = angular.isDefined($attrs.meridians) ? $scope.$parent.$eval($attrs.meridians) : timepickerConfig.meridians || $locale.DATETIME_FORMATS.AMPMS;
this.init = function( ngModelCtrl_, inputs ) {
ngModelCtrl = ngModelCtrl_;
ngModelCtrl.$render = this.render;
ngModelCtrl.$formatters.unshift(function (modelValue) {
return modelValue ? new Date( modelValue ) : null;
});
var hoursInputEl = inputs.eq(0),
minutesInputEl = inputs.eq(1);
var mousewheel = angular.isDefined($attrs.mousewheel) ? $scope.$parent.$eval($attrs.mousewheel) : timepickerConfig.mousewheel;
if ( mousewheel ) {
this.setupMousewheelEvents( hoursInputEl, minutesInputEl );
}
var arrowkeys = angular.isDefined($attrs.arrowkeys) ? $scope.$parent.$eval($attrs.arrowkeys) : timepickerConfig.arrowkeys;
if (arrowkeys) {
this.setupArrowkeyEvents( hoursInputEl, minutesInputEl );
}
$scope.readonlyInput = angular.isDefined($attrs.readonlyInput) ? $scope.$parent.$eval($attrs.readonlyInput) : timepickerConfig.readonlyInput;
this.setupInputEvents( hoursInputEl, minutesInputEl );
};
var hourStep = timepickerConfig.hourStep;
if ($attrs.hourStep) {
$scope.$parent.$watch($parse($attrs.hourStep), function(value) {
hourStep = parseInt(value, 10);
});
}
var minuteStep = timepickerConfig.minuteStep;
if ($attrs.minuteStep) {
$scope.$parent.$watch($parse($attrs.minuteStep), function(value) {
minuteStep = parseInt(value, 10);
});
}
// 12H / 24H mode
$scope.showMeridian = timepickerConfig.showMeridian;
if ($attrs.showMeridian) {
$scope.$parent.$watch($parse($attrs.showMeridian), function(value) {
$scope.showMeridian = !!value;
if ( ngModelCtrl.$error.time ) {
// Evaluate from template
var hours = getHoursFromTemplate(), minutes = getMinutesFromTemplate();
if (angular.isDefined( hours ) && angular.isDefined( minutes )) {
selected.setHours( hours );
refresh();
}
} else {
updateTemplate();
}
});
}
// Get $scope.hours in 24H mode if valid
function getHoursFromTemplate ( ) {
var hours = parseInt( $scope.hours, 10 );
var valid = ( $scope.showMeridian ) ? (hours > 0 && hours < 13) : (hours >= 0 && hours < 24);
if ( !valid ) {
return undefined;
}
if ( $scope.showMeridian ) {
if ( hours === 12 ) {
hours = 0;
}
if ( $scope.meridian === meridians[1] ) {
hours = hours + 12;
}
}
return hours;
}
function getMinutesFromTemplate() {
var minutes = parseInt($scope.minutes, 10);
return ( minutes >= 0 && minutes < 60 ) ? minutes : undefined;
}
function pad( value ) {
return ( angular.isDefined(value) && value.toString().length < 2 ) ? '0' + value : value.toString();
}
// Respond on mousewheel spin
this.setupMousewheelEvents = function( hoursInputEl, minutesInputEl ) {
var isScrollingUp = function(e) {
if (e.originalEvent) {
e = e.originalEvent;
}
//pick correct delta variable depending on event
var delta = (e.wheelDelta) ? e.wheelDelta : -e.deltaY;
return (e.detail || delta > 0);
};
hoursInputEl.bind('mousewheel wheel', function(e) {
$scope.$apply( (isScrollingUp(e)) ? $scope.incrementHours() : $scope.decrementHours() );
e.preventDefault();
});
minutesInputEl.bind('mousewheel wheel', function(e) {
$scope.$apply( (isScrollingUp(e)) ? $scope.incrementMinutes() : $scope.decrementMinutes() );
e.preventDefault();
});
};
// Respond on up/down arrowkeys
this.setupArrowkeyEvents = function( hoursInputEl, minutesInputEl ) {
hoursInputEl.bind('keydown', function(e) {
if ( e.which === 38 ) { // up
e.preventDefault();
$scope.incrementHours();
$scope.$apply();
}
else if ( e.which === 40 ) { // down
e.preventDefault();
$scope.decrementHours();
$scope.$apply();
}
});
minutesInputEl.bind('keydown', function(e) {
if ( e.which === 38 ) { // up
e.preventDefault();
$scope.incrementMinutes();
$scope.$apply();
}
else if ( e.which === 40 ) { // down
e.preventDefault();
$scope.decrementMinutes();
$scope.$apply();
}
});
};
this.setupInputEvents = function( hoursInputEl, minutesInputEl ) {
if ( $scope.readonlyInput ) {
$scope.updateHours = angular.noop;
$scope.updateMinutes = angular.noop;
return;
}
var invalidate = function(invalidHours, invalidMinutes) {
ngModelCtrl.$setViewValue( null );
ngModelCtrl.$setValidity('time', false);
if (angular.isDefined(invalidHours)) {
$scope.invalidHours = invalidHours;
}
if (angular.isDefined(invalidMinutes)) {
$scope.invalidMinutes = invalidMinutes;
}
};
$scope.updateHours = function() {
var hours = getHoursFromTemplate();
if ( angular.isDefined(hours) ) {
selected.setHours( hours );
refresh( 'h' );
} else {
invalidate(true);
}
};
hoursInputEl.bind('blur', function(e) {
if ( !$scope.invalidHours && $scope.hours < 10) {
$scope.$apply( function() {
$scope.hours = pad( $scope.hours );
});
}
});
$scope.updateMinutes = function() {
var minutes = getMinutesFromTemplate();
if ( angular.isDefined(minutes) ) {
selected.setMinutes( minutes );
refresh( 'm' );
} else {
invalidate(undefined, true);
}
};
minutesInputEl.bind('blur', function(e) {
if ( !$scope.invalidMinutes && $scope.minutes < 10 ) {
$scope.$apply( function() {
$scope.minutes = pad( $scope.minutes );
});
}
});
};
this.render = function() {
var date = ngModelCtrl.$viewValue;
if ( isNaN(date) ) {
ngModelCtrl.$setValidity('time', false);
$log.error('Timepicker directive: "ng-model" value must be a Date object, a number of milliseconds since 01.01.1970 or a string representing an RFC2822 or ISO 8601 date.');
} else {
if ( date ) {
selected = date;
}
makeValid();
updateTemplate();
}
};
// Call internally when we know that model is valid.
function refresh( keyboardChange ) {
makeValid();
ngModelCtrl.$setViewValue( new Date(selected) );
updateTemplate( keyboardChange );
}
function makeValid() {
ngModelCtrl.$setValidity('time', true);
$scope.invalidHours = false;
$scope.invalidMinutes = false;
}
function updateTemplate( keyboardChange ) {
var hours = selected.getHours(), minutes = selected.getMinutes();
if ( $scope.showMeridian ) {
hours = ( hours === 0 || hours === 12 ) ? 12 : hours % 12; // Convert 24 to 12 hour system
}
$scope.hours = keyboardChange === 'h' ? hours : pad(hours);
if (keyboardChange !== 'm') {
$scope.minutes = pad(minutes);
}
$scope.meridian = selected.getHours() < 12 ? meridians[0] : meridians[1];
}
function addMinutes( minutes ) {
var dt = new Date( selected.getTime() + minutes * 60000 );
selected.setHours( dt.getHours(), dt.getMinutes() );
refresh();
}
$scope.showSpinners = angular.isDefined($attrs.showSpinners) ?
$scope.$parent.$eval($attrs.showSpinners) : timepickerConfig.showSpinners;
$scope.incrementHours = function() {
addMinutes( hourStep * 60 );
};
$scope.decrementHours = function() {
addMinutes( - hourStep * 60 );
};
$scope.incrementMinutes = function() {
addMinutes( minuteStep );
};
$scope.decrementMinutes = function() {
addMinutes( - minuteStep );
};
$scope.toggleMeridian = function() {
addMinutes( 12 * 60 * (( selected.getHours() < 12 ) ? 1 : -1) );
};
}])
.directive('timepicker', function () {
return {
restrict: 'EA',
require: ['timepicker', '?^ngModel'],
controller:'TimepickerController',
replace: true,
scope: {},
templateUrl: 'template/timepicker/timepicker.html',
link: function(scope, element, attrs, ctrls) {
var timepickerCtrl = ctrls[0], ngModelCtrl = ctrls[1];
if ( ngModelCtrl ) {
timepickerCtrl.init( ngModelCtrl, element.find('input') );
}
}
};
});
angular.module('ui.bootstrap.transition', [])
.value('$transitionSuppressDeprecated', false)
/**
* $transition service provides a consistent interface to trigger CSS 3 transitions and to be informed when they complete.
* @param {DOMElement} element The DOMElement that will be animated.
* @param {string|object|function} trigger The thing that will cause the transition to start:
* - As a string, it represents the css class to be added to the element.
* - As an object, it represents a hash of style attributes to be applied to the element.
* - As a function, it represents a function to be called that will cause the transition to occur.
* @return {Promise} A promise that is resolved when the transition finishes.
*/
.factory('$transition', [
'$q', '$timeout', '$rootScope', '$log', '$transitionSuppressDeprecated',
function($q , $timeout , $rootScope , $log , $transitionSuppressDeprecated) {
if (!$transitionSuppressDeprecated) {
$log.warn('$transition is now deprecated. Use $animate from ngAnimate instead.');
}
var $transition = function(element, trigger, options) {
options = options || {};
var deferred = $q.defer();
var endEventName = $transition[options.animation ? 'animationEndEventName' : 'transitionEndEventName'];
var transitionEndHandler = function(event) {
$rootScope.$apply(function() {
element.unbind(endEventName, transitionEndHandler);
deferred.resolve(element);
});
};
if (endEventName) {
element.bind(endEventName, transitionEndHandler);
}
// Wrap in a timeout to allow the browser time to update the DOM before the transition is to occur
$timeout(function() {
if ( angular.isString(trigger) ) {
element.addClass(trigger);
} else if ( angular.isFunction(trigger) ) {
trigger(element);
} else if ( angular.isObject(trigger) ) {
element.css(trigger);
}
//If browser does not support transitions, instantly resolve
if ( !endEventName ) {
deferred.resolve(element);
}
});
// Add our custom cancel function to the promise that is returned
// We can call this if we are about to run a new transition, which we know will prevent this transition from ending,
// i.e. it will therefore never raise a transitionEnd event for that transition
deferred.promise.cancel = function() {
if ( endEventName ) {
element.unbind(endEventName, transitionEndHandler);
}
deferred.reject('Transition cancelled');
};
return deferred.promise;
};
// Work out the name of the transitionEnd event
var transElement = document.createElement('trans');
var transitionEndEventNames = {
'WebkitTransition': 'webkitTransitionEnd',
'MozTransition': 'transitionend',
'OTransition': 'oTransitionEnd',
'transition': 'transitionend'
};
var animationEndEventNames = {
'WebkitTransition': 'webkitAnimationEnd',
'MozTransition': 'animationend',
'OTransition': 'oAnimationEnd',
'transition': 'animationend'
};
function findEndEventName(endEventNames) {
for (var name in endEventNames){
if (transElement.style[name] !== undefined) {
return endEventNames[name];
}
}
}
$transition.transitionEndEventName = findEndEventName(transitionEndEventNames);
$transition.animationEndEventName = findEndEventName(animationEndEventNames);
return $transition;
}]);
angular.module('ui.bootstrap.typeahead', ['ui.bootstrap.position', 'ui.bootstrap.bindHtml'])
/**
* A helper service that can parse typeahead's syntax (string provided by users)
* Extracted to a separate service for ease of unit testing
*/
.factory('typeaheadParser', ['$parse', function ($parse) {
// 00000111000000000000022200000000000000003333333333333330000000000044000
var TYPEAHEAD_REGEXP = /^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?\s+for\s+(?:([\$\w][\$\w\d]*))\s+in\s+([\s\S]+?)$/;
return {
parse:function (input) {
var match = input.match(TYPEAHEAD_REGEXP);
if (!match) {
throw new Error(
'Expected typeahead specification in form of "_modelValue_ (as _label_)? for _item_ in _collection_"' +
' but got "' + input + '".');
}
return {
itemName:match[3],
source:$parse(match[4]),
viewMapper:$parse(match[2] || match[1]),
modelMapper:$parse(match[1])
};
}
};
}])
.directive('typeahead', ['$compile', '$parse', '$q', '$timeout', '$document', '$rootScope', '$position', 'typeaheadParser',
function ($compile, $parse, $q, $timeout, $document, $rootScope, $position, typeaheadParser) {
var HOT_KEYS = [9, 13, 27, 38, 40];
return {
require:'ngModel',
link:function (originalScope, element, attrs, modelCtrl) {
//SUPPORTED ATTRIBUTES (OPTIONS)
//minimal no of characters that needs to be entered before typeahead kicks-in
var minLength = originalScope.$eval(attrs.typeaheadMinLength);
if (!minLength && minLength !== 0) {
minLength = 1;
}
//minimal wait time after last character typed before typeahead kicks-in
var waitTime = originalScope.$eval(attrs.typeaheadWaitMs) || 0;
//should it restrict model values to the ones selected from the popup only?
var isEditable = originalScope.$eval(attrs.typeaheadEditable) !== false;
//binding to a variable that indicates if matches are being retrieved asynchronously
var isLoadingSetter = $parse(attrs.typeaheadLoading).assign || angular.noop;
//a callback executed when a match is selected
var onSelectCallback = $parse(attrs.typeaheadOnSelect);
var inputFormatter = attrs.typeaheadInputFormatter ? $parse(attrs.typeaheadInputFormatter) : undefined;
var appendToBody = attrs.typeaheadAppendToBody ? originalScope.$eval(attrs.typeaheadAppendToBody) : false;
var focusFirst = originalScope.$eval(attrs.typeaheadFocusFirst) !== false;
//INTERNAL VARIABLES
//model setter executed upon match selection
var $setModelValue = $parse(attrs.ngModel).assign;
//expressions used by typeahead
var parserResult = typeaheadParser.parse(attrs.typeahead);
var hasFocus;
//create a child scope for the typeahead directive so we are not polluting original scope
//with typeahead-specific data (matches, query etc.)
var scope = originalScope.$new();
originalScope.$on('$destroy', function(){
scope.$destroy();
});
// WAI-ARIA
var popupId = 'typeahead-' + scope.$id + '-' + Math.floor(Math.random() * 10000);
element.attr({
'aria-autocomplete': 'list',
'aria-expanded': false,
'aria-owns': popupId
});
//pop-up element used to display matches
var popUpEl = angular.element('<div typeahead-popup></div>');
popUpEl.attr({
id: popupId,
matches: 'matches',
active: 'activeIdx',
select: 'select(activeIdx)',
query: 'query',
position: 'position'
});
//custom item template
if (angular.isDefined(attrs.typeaheadTemplateUrl)) {
popUpEl.attr('template-url', attrs.typeaheadTemplateUrl);
}
var resetMatches = function() {
scope.matches = [];
scope.activeIdx = -1;
element.attr('aria-expanded', false);
};
var getMatchId = function(index) {
return popupId + '-option-' + index;
};
// Indicate that the specified match is the active (pre-selected) item in the list owned by this typeahead.
// This attribute is added or removed automatically when the `activeIdx` changes.
scope.$watch('activeIdx', function(index) {
if (index < 0) {
element.removeAttr('aria-activedescendant');
} else {
element.attr('aria-activedescendant', getMatchId(index));
}
});
var getMatchesAsync = function(inputValue) {
var locals = {$viewValue: inputValue};
isLoadingSetter(originalScope, true);
$q.when(parserResult.source(originalScope, locals)).then(function(matches) {
//it might happen that several async queries were in progress if a user were typing fast
//but we are interested only in responses that correspond to the current view value
var onCurrentRequest = (inputValue === modelCtrl.$viewValue);
if (onCurrentRequest && hasFocus) {
if (matches && matches.length > 0) {
scope.activeIdx = focusFirst ? 0 : -1;
scope.matches.length = 0;
//transform labels
for(var i=0; i<matches.length; i++) {
locals[parserResult.itemName] = matches[i];
scope.matches.push({
id: getMatchId(i),
label: parserResult.viewMapper(scope, locals),
model: matches[i]
});
}
scope.query = inputValue;
//position pop-up with matches - we need to re-calculate its position each time we are opening a window
//with matches as a pop-up might be absolute-positioned and position of an input might have changed on a page
//due to other elements being rendered
scope.position = appendToBody ? $position.offset(element) : $position.position(element);
scope.position.top = scope.position.top + element.prop('offsetHeight');
element.attr('aria-expanded', true);
} else {
resetMatches();
}
}
if (onCurrentRequest) {
isLoadingSetter(originalScope, false);
}
}, function(){
resetMatches();
isLoadingSetter(originalScope, false);
});
};
resetMatches();
//we need to propagate user's query so we can higlight matches
scope.query = undefined;
//Declare the timeout promise var outside the function scope so that stacked calls can be cancelled later
var timeoutPromise;
var scheduleSearchWithTimeout = function(inputValue) {
timeoutPromise = $timeout(function () {
getMatchesAsync(inputValue);
}, waitTime);
};
var cancelPreviousTimeout = function() {
if (timeoutPromise) {
$timeout.cancel(timeoutPromise);
}
};
//plug into $parsers pipeline to open a typeahead on view changes initiated from DOM
//$parsers kick-in on all the changes coming from the view as well as manually triggered by $setViewValue
modelCtrl.$parsers.unshift(function (inputValue) {
hasFocus = true;
if (minLength === 0 || inputValue && inputValue.length >= minLength) {
if (waitTime > 0) {
cancelPreviousTimeout();
scheduleSearchWithTimeout(inputValue);
} else {
getMatchesAsync(inputValue);
}
} else {
isLoadingSetter(originalScope, false);
cancelPreviousTimeout();
resetMatches();
}
if (isEditable) {
return inputValue;
} else {
if (!inputValue) {
// Reset in case user had typed something previously.
modelCtrl.$setValidity('editable', true);
return inputValue;
} else {
modelCtrl.$setValidity('editable', false);
return undefined;
}
}
});
modelCtrl.$formatters.push(function (modelValue) {
var candidateViewValue, emptyViewValue;
var locals = {};
// The validity may be set to false via $parsers (see above) if
// the model is restricted to selected values. If the model
// is set manually it is considered to be valid.
if (!isEditable) {
modelCtrl.$setValidity('editable', true);
}
if (inputFormatter) {
locals.$model = modelValue;
return inputFormatter(originalScope, locals);
} else {
//it might happen that we don't have enough info to properly render input value
//we need to check for this situation and simply return model value if we can't apply custom formatting
locals[parserResult.itemName] = modelValue;
candidateViewValue = parserResult.viewMapper(originalScope, locals);
locals[parserResult.itemName] = undefined;
emptyViewValue = parserResult.viewMapper(originalScope, locals);
return candidateViewValue!== emptyViewValue ? candidateViewValue : modelValue;
}
});
scope.select = function (activeIdx) {
//called from within the $digest() cycle
var locals = {};
var model, item;
locals[parserResult.itemName] = item = scope.matches[activeIdx].model;
model = parserResult.modelMapper(originalScope, locals);
$setModelValue(originalScope, model);
modelCtrl.$setValidity('editable', true);
modelCtrl.$setValidity('parse', true);
onSelectCallback(originalScope, {
$item: item,
$model: model,
$label: parserResult.viewMapper(originalScope, locals)
});
resetMatches();
//return focus to the input element if a match was selected via a mouse click event
// use timeout to avoid $rootScope:inprog error
$timeout(function() { element[0].focus(); }, 0, false);
};
//bind keyboard events: arrows up(38) / down(40), enter(13) and tab(9), esc(27)
element.bind('keydown', function (evt) {
//typeahead is open and an "interesting" key was pressed
if (scope.matches.length === 0 || HOT_KEYS.indexOf(evt.which) === -1) {
return;
}
// if there's nothing selected (i.e. focusFirst) and enter is hit, don't do anything
if (scope.activeIdx == -1 && (evt.which === 13 || evt.which === 9)) {
return;
}
evt.preventDefault();
if (evt.which === 40) {
scope.activeIdx = (scope.activeIdx + 1) % scope.matches.length;
scope.$digest();
} else if (evt.which === 38) {
scope.activeIdx = (scope.activeIdx > 0 ? scope.activeIdx : scope.matches.length) - 1;
scope.$digest();
} else if (evt.which === 13 || evt.which === 9) {
scope.$apply(function () {
scope.select(scope.activeIdx);
});
} else if (evt.which === 27) {
evt.stopPropagation();
resetMatches();
scope.$digest();
}
});
element.bind('blur', function (evt) {
hasFocus = false;
});
// Keep reference to click handler to unbind it.
var dismissClickHandler = function (evt) {
if (element[0] !== evt.target) {
resetMatches();
if (!$rootScope.$$phase) {
scope.$digest();
}
}
};
$document.bind('click', dismissClickHandler);
originalScope.$on('$destroy', function(){
$document.unbind('click', dismissClickHandler);
if (appendToBody) {
$popup.remove();
}
// Prevent jQuery cache memory leak
popUpEl.remove();
});
var $popup = $compile(popUpEl)(scope);
if (appendToBody) {
$document.find('body').append($popup);
} else {
element.after($popup);
}
}
};
}])
.directive('typeaheadPopup', function () {
return {
restrict:'EA',
scope:{
matches:'=',
query:'=',
active:'=',
position:'&',
select:'&'
},
replace:true,
templateUrl:'template/typeahead/typeahead-popup.html',
link:function (scope, element, attrs) {
scope.templateUrl = attrs.templateUrl;
scope.isOpen = function () {
return scope.matches.length > 0;
};
scope.isActive = function (matchIdx) {
return scope.active == matchIdx;
};
scope.selectActive = function (matchIdx) {
scope.active = matchIdx;
};
scope.selectMatch = function (activeIdx) {
scope.select({activeIdx:activeIdx});
};
}
};
})
.directive('typeaheadMatch', ['$templateRequest', '$compile', '$parse', function ($templateRequest, $compile, $parse) {
return {
restrict:'EA',
scope:{
index:'=',
match:'=',
query:'='
},
link:function (scope, element, attrs) {
var tplUrl = $parse(attrs.templateUrl)(scope.$parent) || 'template/typeahead/typeahead-match.html';
$templateRequest(tplUrl).then(function(tplContent) {
$compile(tplContent.trim())(scope, function(clonedElement){
element.replaceWith(clonedElement);
});
});
}
};
}])
.filter('typeaheadHighlight', function() {
function escapeRegexp(queryToEscape) {
return queryToEscape.replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1');
}
return function(matchItem, query) {
return query ? ('' + matchItem).replace(new RegExp(escapeRegexp(query), 'gi'), '<strong>$&</strong>') : matchItem;
};
});
!angular.$$csp() && angular.element(document).find('head').prepend('<style type="text/css">.ng-animate.item:not(.left):not(.right){-webkit-transition:0s ease-in-out left;transition:0s ease-in-out left}</style>'); |
/**
* Trailpack Configuration
*
* @see {@link http://trailsjs.io/doc/trailpack/config}
*/
module.exports = {
lifecycle: {
configure: {
listen: [ ]
}
}
}
|
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
errorHandler = require('./errors.server.controller'),
Helpline = mongoose.model('Helpline'),
_ = require('lodash');
/**
* Create a Helpline
*/
exports.create = function(req, res) {
var helpline = new Helpline(req.body);
helpline.user = req.user;
helpline.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(helpline);
}
});
};
/**
* Show the current Helpline
*/
exports.read = function(req, res) {
res.jsonp(req.helpline);
};
/**
* Update a Helpline
*/
exports.update = function(req, res) {
var helpline = req.helpline ;
helpline = _.extend(helpline , req.body);
helpline.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(helpline);
}
});
};
/**
* Delete an Helpline
*/
exports.delete = function(req, res) {
var helpline = req.helpline ;
helpline.remove(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(helpline);
}
});
};
/**
* List of Helplines
*/
exports.list = function(req, res) {
Helpline.find().sort('-created').populate('user', 'displayName').exec(function(err, helplines) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(helplines);
}
});
};
/**
* Helpline middleware
*/
exports.helplineByID = function(req, res, next, id) {
Helpline.findById(id).populate('user', 'displayName').exec(function(err, helpline) {
if (err) return next(err);
if (! helpline) return next(new Error('Failed to load Helpline ' + id));
req.helpline = helpline ;
next();
});
};
/**
* Helpline authorization middleware
*/
exports.hasAuthorization = function(req, res, next) {
if (req.helpline.user.id !== req.user.id) {
return res.status(403).send('User is not authorized');
}
next();
};
|
'use strict';
/* Controllers */
var dnmtControllers = angular.module('dnmtControllers', []);
dnmtControllers.controller('SessionCtrl', ['$scope', 'Server',
function($scope, Server) {
/*
1. If not logged in and cookie auth, show login form
2. If not logged in and not cookie auth, show login link
3. If logged in show username, roles
*/
var session = Session();
$scope.isLoggedIn = (session.authenticated != false);
$scope.user = session.userCtx.user;
$scope.roles = session.userCtx.roles;
$scope.logout = function() {
session.logout();
};
$scope.login = function(user, pass) {
session.login(user, pass);
$scope.user = session.userCtx.user;
$scope.roles = session.userCtx.roles;
};
}]);
|
import { AppRegistry } from 'react-native';
import PostersGaloreAndroid from './src/containers/App';
AppRegistry.registerComponent('Posters_Galore_Android', () => PostersGaloreAndroid);
|
/*** METEOR ACCOUNTS ***/
if (Accounts.emailTemplates) {
Accounts.emailTemplates.siteName = 'My Budget';
Accounts.emailTemplates.from = 'My Budget <[email protected]>';
Accounts.emailTemplates.resetPassword.subject = function(user, url) {
return 'Recupera tu contraseña';
};
Accounts.emailTemplates.resetPassword.text = function(user, url) {
url = url.replace('#/', '')
var body = 'Hola ' + user.getFullName() + ', \n\r\n\r';
body += 'Para recuperar tu contraseña, simplemente haz click en el link de abajo.\n\r\n\r';
body += url + '\n\r\n\r';
body += 'Gracias.'
return body;
};
}
|
#!/usr/bin/env node
require('../lib/lispy').run();
|
// This is a manifest file that'll be compiled into including all the files listed below.
// Add new JavaScript/Coffee code in separate files in this directory and they'll automatically
// be included in the compiled file accessible from http://example.com/assets/application.js
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
//= require jquery
//= require jquery_ujs
//= require odometer/bootstrap.min
//= require odometer/d3.min
//= require odometer/jquery-ui.min
//= require odometer/knockout.min
//= require odometer/rickshaw.min
//= require odometer/h5utils
//= require_tree .
|
$package("org.mathdox.formulaeditor");
$identify("org/mathdox/formulaeditor/EventHandlerLocal.js");
$main(function(){
org.mathdox.formulaeditor.EventHandlerLocal = $extend(Object, {
initialize : function(element) {
// save the 'this' pointer so that it can be used in the event handlers
var handler = this;
// register the onkeydown handler, if present
if (this.onkeydown instanceof Function) {
var saved1 = element.onkeydown;
element.onkeydown = function(event) {
if (!event) {
event = window.event; // MSIE's non-standard way of supplying events
}
return handler.onkeydown(event) && saved1 && saved1(event);
};
}
// register the onkeypress handler, if present
if (this.onkeypress instanceof Function) {
var saved2 = element.onkeypress;
element.onkeypress = function(event) {
if (!event) {
event = window.event; // MSIE's non-standard way of supplying events
}
if (!("charCode" in event)) {
event.charCode = event.keyCode; // MSIE doesn't set charCode
}
return handler.onkeypress(event) && saved2 && saved2(event);
};
}
// register the onmousedown handler, if present
if (this.onmousedown instanceof Function) {
var saved3 = element.onclick;
var saved3a = element.ontouchstart;
element.onmousedown = function(event) {
if (!event) {
event = window.event; // MSIE's non-standard way of supplying events
}
return handler.onmousedown(event) && saved3 && saved3(event);
};
element.ontouchstart = function(event) {
if (!event) {
event = window.event; // MSIE's non-standard way of supplying events
}
return handler.onmousedown(handler.rewriteTouchEvent(event)) && saved3a && saved3a(event);
}
}
// register the onmouseup handler, if present
if (this.onmouseup instanceof Function) {
var saved4 = element.onclick;
var saved4a = element.ontouchend;
element.onmouseup = function(event) {
if (!event) {
event = window.event; // MSIE's non-standard way of supplying events
}
return handler.onmouseup(event) && saved4 && saved4(event);
};
element.ontouchend = function(event) {
if (!event) {
event = window.event; // MSIE's non-standard way of supplying events
}
return handler.onmouseup(handler.rewriteTouchEvent(event)) && saved5a && saved4a(event);
}
}
// register the onmousemove handler, if present
if (this.onmousemove instanceof Function) {
var saved5 = element.onmousemove;
element.onmousemove = function(event) {
if (!event) {
event = window.event; // MSIE's non-standard way of supplying events
}
return handler.onmousemove(event) && saved5 && saved5(event);
};
}
// register the onmouseout handler, if present
if (this.onmouseout instanceof Function) {
var saved6 = element.onmouseout;
element.onmouseout = function(event) {
if (!event) {
event = window.event; // MSIE's non-standard way of supplying events
}
return handler.onmouseout(event) && saved6 && saved6(event);
};
}
// register the onmouseover handler, if present
if (this.onmouseover instanceof Function) {
var saved7 = element.onmouseover;
element.onmouseover = function(event) {
if (!event) {
event = window.event; // MSIE's non-standard way of supplying events
}
return handler.onmouseover(event) && saved7 && saved7(event);
};
}
},
// see also http://ross.posterous.com/2008/08/19/iphone-touch-events-in-javascript/
rewriteTouchEvent: function(event) {
var touches = event.changedTouches;
var first = touches[0];
var type = "";
switch(event.type)
{
case "touchstart":
type = "mousedown";
break;
case "touchmove":
type="mousemove";
break;
case "touchend":
type="mouseup";
break;
default: return;
}
// initMouseEvent(type, canBubble, cancelable, view, clickCount,
// screenX, screenY, clientX, clientY, ctrlKey,
// altKey, shiftKey, metaKey, button, relatedTarget);
var simulatedEvent = element.createEvent("MouseEvent");
simulatedEvent.initMouseEvent(type, true, true, window, 1,
first.screenX, first.screenY,
first.clientX, first.clientY, false,
false, false, false, 0/*left*/, null);
simulatedEvent.mathdoxnoadjust = true;
return simulatedEvent;
}
});
});
|
var container = {};(function() {
var dfs = {"am_pm":["f.h.","e.h."],"day_name":["sunnudagur","mánudagur","þriðjudagur","miðvikudagur","fimmtudagur","föstudagur","laugardagur"],"day_short":["sun","mán","þri","mið","fim","fös","lau"],"era":["fyrir Krist","eftir Krist"],"era_name":["fyrir Krist","eftir Krist"],"month_name":["janúar","febrúar","mars","apríl","maí","júní","júlí","ágúst","september","október","nóvember","desember"],"month_short":["jan","feb","mar","apr","maí","jún","júl","ágú","sep","okt","nóv","des"],"order_full":"DMY","order_long":"DMY","order_medium":"DMY","order_short":"DMY"};
var nfs = {"decimal_separator":",","grouping_separator":".","minus":"−"};
var df = {SHORT_PADDED_CENTURY:function(d){if(d){return(((d.getDate()+101)+'').substring(1)+'.'+((d.getMonth()+101)+'').substring(1)+'.'+d.getFullYear());}},SHORT:function(d){if(d){return(d.getDate()+'.'+(d.getMonth()+1)+'.'+d.getFullYear());}},SHORT_NOYEAR:function(d){if(d){return(d.getDate()+'.'+(d.getMonth()+1));}},SHORT_NODAY:function(d){if(d){return((d.getMonth()+1)+'.'+d.getFullYear());}},MEDIUM:function(d){if(d){return(d.getDate()+'.'+(d.getMonth()+1)+'.'+d.getFullYear());}},MEDIUM_NOYEAR:function(d){if(d){return(d.getDate()+'.'+(d.getMonth()+1));}},MEDIUM_WEEKDAY_NOYEAR:function(d){if(d){return(dfs.day_short[d.getDay()]+' '+d.getDate()+'.'+(d.getMonth()+1));}},LONG_NODAY:function(d){if(d){return(dfs.month_name[d.getMonth()]+' '+d.getFullYear());}},LONG:function(d){if(d){return(d.getDate()+'.'+' '+dfs.month_name[d.getMonth()]+' '+d.getFullYear());}},FULL:function(d){if(d){return(d.getDate()+'.'+' '+dfs.month_name[d.getMonth()]+' '+d.getFullYear());}}};
container = container || new Object();
var icu = container;
icu.getCountry = function() { return "" };
icu.getCountryName = function() { return "" };
icu.getDateFormat = function(formatCode) { var retVal = {}; retVal.format = df[formatCode]; return retVal; };
icu.getDateFormats = function() { return df; };
icu.getDateFormatSymbols = function() { return dfs; };
icu.getDecimalFormat = function(places) { var retVal = {}; retVal.format = function(n) { var ns = n < 0 ? Math.abs(n).toFixed(places) : n.toFixed(places); var ns2 = ns.split('.'); s = ns2[0]; var d = ns2[1]; var rgx = /(\d+)(\d{3})/;while(rgx.test(s)){s = s.replace(rgx, '$1' + nfs["grouping_separator"] + '$2');} return (n < 0 ? nfs["minus"] : "") + s + nfs["decimal_separator"] + d;}; return retVal; };
icu.getDecimalFormatSymbols = function() { return nfs; };
icu.getIntegerFormat = function() { var retVal = {}; retVal.format = function(i) { var s = i < 0 ? Math.abs(i).toString() : i.toString(); var rgx = /(\d+)(\d{3})/;while(rgx.test(s)){s = s.replace(rgx, '$1' + nfs["grouping_separator"] + '$2');} return i < 0 ? nfs["minus"] + s : s;}; return retVal; };
icu.getLanguage = function() { return "is" };
icu.getLanguageName = function() { return "íslenska" };
icu.getLocale = function() { return "is" };
icu.getLocaleName = function() { return "íslenska" };
})();export default container; |
// Copyright 2018-2021, University of Colorado Boulder
/**
* ParallelDOM tests
*
* @author Sam Reid (PhET Interactive Simulations)
*/
import PDOMUtils from './PDOMUtils.js';
QUnit.module( 'AccessibilityUtilsTests' );
// tests
QUnit.test( 'insertElements', assert => {
const div1 = document.createElement( 'div1' );
const div2 = document.createElement( 'div2' );
const div3 = document.createElement( 'div3' );
const div4 = document.createElement( 'div4' );
PDOMUtils.insertElements( div1, [ div2, div3, div4 ] );
assert.ok( div1.childNodes.length === 3, 'inserted number of elements' );
assert.ok( div1.childNodes[ 0 ] === div2, 'inserted div2 order of elements' );
assert.ok( div1.childNodes[ 1 ] === div3, 'inserted div3 order of elements' );
assert.ok( div1.childNodes[ 2 ] === div4, 'inserted div4 order of elements' );
const div5 = document.createElement( 'div5' );
const div6 = document.createElement( 'div6' );
const div7 = document.createElement( 'div7' );
PDOMUtils.insertElements( div1, [ div5, div6, div7 ], div3 );
assert.ok( div1.childNodes[ 0 ] === div2, 'inserted div2 order of elements' );
assert.ok( div1.childNodes[ 1 ] === div5, 'inserted div5 order of elements' );
assert.ok( div1.childNodes[ 2 ] === div6, 'inserted div6 order of elements' );
assert.ok( div1.childNodes[ 3 ] === div7, 'inserted div7 order of elements' );
assert.ok( div1.childNodes[ 4 ] === div3, 'inserted div3 order of elements' );
assert.ok( div1.childNodes[ 5 ] === div4, 'inserted div4 order of elements' );
} );
QUnit.test( 'getNext/PreviousFocusable', assert => {
const parent = PDOMUtils.createElement( 'div', false );
const button = PDOMUtils.createElement( 'button', true ); // focusable
const div = PDOMUtils.createElement( 'div', true ); // focusable
const p = PDOMUtils.createElement( 'p', false ); // not focusable
// elements must be in DOM to be focusable
document.body.appendChild( parent );
parent.appendChild( button );
parent.appendChild( div );
parent.appendChild( p );
const firstFocusable = PDOMUtils.getNextFocusable( parent );
assert.ok( firstFocusable === button, 'first focusable found' );
firstFocusable.focus();
const secondFocusable = PDOMUtils.getNextFocusable( parent );
assert.ok( secondFocusable === div, 'second focusable found' );
secondFocusable.focus();
// should still return the div because the p isn't focusable
const thirdFocusable = PDOMUtils.getNextFocusable( parent );
assert.ok( thirdFocusable === div, 'no more focusables after div' );
// remove the DOM nodes so they don't clutter the tests
document.body.removeChild( parent );
} );
QUnit.test( 'overrideFocusWithTabIndex', assert => {
// test function directly
const testButton = document.createElement( 'button' );
const testListItem = document.createElement( 'li' );
const testLink = document.createElement( 'a' );
const testSection = document.createElement( 'section' );
// defaults, should not an tabindex to any elements
PDOMUtils.overrideFocusWithTabIndex( testButton, true );
PDOMUtils.overrideFocusWithTabIndex( testLink, true );
PDOMUtils.overrideFocusWithTabIndex( testListItem, false );
PDOMUtils.overrideFocusWithTabIndex( testSection, false );
assert.ok( testButton.getAttribute( 'tabindex' ) === null, 'testButton focusable by default, shouldn\'t have override' );
assert.ok( testLink.getAttribute( 'tabindex' ) === null, 'testLink focusable by default, shouldn\'t have override' );
assert.ok( testListItem.getAttribute( 'tabindex' ) === null, 'testListItem not focusable by default, shouldn\'t have override' );
assert.ok( testSection.getAttribute( 'tabindex' ) === null, 'testSection not focusable by default, shouldn\'t have override' );
// override all, should all should have a tabindex
PDOMUtils.overrideFocusWithTabIndex( testButton, false );
PDOMUtils.overrideFocusWithTabIndex( testLink, false );
PDOMUtils.overrideFocusWithTabIndex( testListItem, true );
PDOMUtils.overrideFocusWithTabIndex( testSection, true );
assert.ok( testButton.getAttribute( 'tabindex' ) === '-1', 'testButton focusable by default, should have override' );
assert.ok( testLink.getAttribute( 'tabindex' ) === '-1', 'testLink focusable by default, should have override' );
assert.ok( testListItem.getAttribute( 'tabindex' ) === '0', 'testListItem not focusable by default, should have override' );
assert.ok( testSection.getAttribute( 'tabindex' ) === '0', 'testSection not focusable by default, should have override' );
// test function in usages with createElement
// tab index should only be set on elements where we are overriding what is being done natively in the browser
const defaultButton = PDOMUtils.createElement( 'button', true ); // focusable
const defaultParagraph = PDOMUtils.createElement( 'p', false ); // not focusable
const defaultDiv = PDOMUtils.createElement( 'div', false ); // not focusable
// use getAttribute because tabIndex DOM property is always provided by default
assert.ok( defaultButton.getAttribute( 'tabindex' ) === null, 'default button has no tab index' );
assert.ok( defaultParagraph.getAttribute( 'tabindex' ) === null, 'default paragraph has no tab index' );
assert.ok( defaultDiv.getAttribute( 'tabindex' ) === null, 'default div has no tab index' );
// custom focusability should all have tab indices, even those that are being removed from the document
const customButton = PDOMUtils.createElement( 'button', false ); // not focusable
const customParagraph = PDOMUtils.createElement( 'p', true ); // focusable
const customDiv = PDOMUtils.createElement( 'div', true ); // focusable
assert.ok( customButton.getAttribute( 'tabindex' ) === '-1', 'custom button removed from focus' );
assert.ok( customParagraph.getAttribute( 'tabindex' ) === '0', 'custom paragraph added to focus' );
assert.ok( customDiv.getAttribute( 'tabindex' ) === '0', 'custom button removed from focus' );
} );
QUnit.test( 'setTextContent', assert => {
const toyElement = PDOMUtils.createElement( 'div' );
// basic string
const stringContent = 'I am feeling pretty flat today.';
// formatted content
const htmlContent = 'I am <i>feeling</i> rather <strong>BOLD</strong> today';
// malformed formatting tags
const malformedHTMLContent = 'I am feeling a <b>bit off> today.';
// tags not allowed as innerHTML
const invalidHTMLContent = 'I am feeling a bit <a href="daring">devious</a> today.';
PDOMUtils.setTextContent( toyElement, stringContent );
assert.ok( toyElement.textContent === stringContent, 'textContent set for basic string' );
assert.ok( toyElement.firstElementChild === null, 'no innerHTML for basic string' );
PDOMUtils.setTextContent( toyElement, htmlContent );
assert.ok( toyElement.innerHTML === htmlContent, 'innerHTML set for formated content' );
assert.ok( toyElement.firstElementChild !== null, 'element child exists for innerHTML' );
PDOMUtils.setTextContent( toyElement, malformedHTMLContent );
assert.ok( toyElement.textContent === malformedHTMLContent, 'malformed HTML set as content' );
assert.ok( toyElement.firstElementChild === null, 'fallback to textContent for malformed tags' );
PDOMUtils.setTextContent( toyElement, invalidHTMLContent );
assert.ok( toyElement.textContent === invalidHTMLContent, 'invalid HTML set as content' );
assert.ok( toyElement.firstElementChild === null, 'fallback to textContent for disallowed tags' );
} ); |
'use strict'
var chalk = require('chalk')
var util = require('util')
var map = require('../lib/common/array/map')
var newLine = '\n'
exports.warn = function (x, y, z) { return helper('yellow', x, y, z) }
exports.log = function (x, y, z) { return helper('green', x, y, z) }
exports.info = function (x, y, z) { return helper('blue', x, y, z) }
exports.debug = function (x, y, z) { return helper('cyan', x, y, z) }
exports.error = function () {
var i, j, argument, output, lines, error, trace
for (i = 0, j = arguments.length; i < j; i++) {
argument = arguments[i]
if (argument instanceof Error) {
output = argument.stack || argument.name
lines = output.split(newLine)
error = lines[0]
trace = map(lines.slice(1), formatLine).join(newLine)
helper('red', error)
if (trace.length) helper('gray', trace)
continue
}
helper('red', argument)
}
}
function formatLine (line) {
return ' ' + line.trim()
}
function helper (color, x, y, z) {
var output = map([x, y, z], function (argument) {
return typeof argument === 'object' ?
util.inspect(argument, { depth: null }) :
argument
}).join(' ')
map(output.split(newLine), function (line) {
if (line.trim())
console.log('# ' + chalk[color](line)) // eslint-disable-line
})
}
|
var should = require('should'),
testUtils = require('../../utils'),
sequence = require('../../../server/lib/promise/sequence'),
_ = require('lodash'),
// Stuff we are testing
AppModel = require('../../../server/models/app').App,
context = testUtils.context.admin;
describe('App Model', function () {
// Keep the DB clean
before(testUtils.teardown);
afterEach(testUtils.teardown);
beforeEach(testUtils.setup('app'));
before(function () {
should.exist(AppModel);
});
it('can findAll', function (done) {
AppModel.findAll().then(function (results) {
should.exist(results);
results.length.should.be.above(0);
done();
}).catch(done);
});
it('can findOne', function (done) {
AppModel.findOne({id: testUtils.DataGenerator.Content.apps[0].id}).then(function (foundApp) {
should.exist(foundApp);
foundApp.get('created_at').should.be.an.instanceof(Date);
done();
}).catch(done);
});
it('can edit', function (done) {
AppModel.findOne({id: testUtils.DataGenerator.Content.apps[0].id}).then(function (foundApp) {
should.exist(foundApp);
return foundApp.set({name: 'New App'}).save(null, context);
}).then(function () {
return AppModel.findOne({id: testUtils.DataGenerator.Content.apps[0].id});
}).then(function (updatedApp) {
should.exist(updatedApp);
updatedApp.get('name').should.equal('New App');
done();
}).catch(done);
});
it('can add', function (done) {
var newApp = testUtils.DataGenerator.forKnex.createApp(testUtils.DataGenerator.Content.apps[1]);
AppModel.add(newApp, context).then(function (createdApp) {
should.exist(createdApp);
createdApp.attributes.name.should.equal(newApp.name);
done();
}).catch(done);
});
it('can destroy', function (done) {
var firstApp = {id: testUtils.DataGenerator.Content.apps[0].id};
AppModel.findOne(firstApp).then(function (foundApp) {
should.exist(foundApp);
foundApp.attributes.id.should.equal(firstApp.id);
return AppModel.destroy(firstApp);
}).then(function (response) {
response.toJSON().should.be.empty();
return AppModel.findOne(firstApp);
}).then(function (newResults) {
should.equal(newResults, null);
done();
}).catch(done);
});
it('can generate a slug', function (done) {
// Create 12 apps
sequence(_.times(12, function (i) {
return function () {
return AppModel.add({
name: 'Kudos ' + i,
version: '0.0.1',
status: 'installed'
}, context);
};
})).then(function (createdApps) {
// Should have created 12 apps
createdApps.length.should.equal(12);
// Should have matching slugs
_(createdApps).each(function (app, i) {
app.get('slug').should.equal('kudos-' + i);
});
done();
}).catch(done);
});
});
|
module.exports = 'STYLE_MODULE';
|