code
stringlengths 2
1.05M
|
---|
export const ic_explicit_outline = {"viewBox":"0 0 24 24","children":[{"name":"path","attribs":{"d":"M0 0h24v24H0V0z","fill":"none"},"children":[]},{"name":"path","attribs":{"d":"M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H5V5h14v14zm-4-4h-4v-2h4v-2h-4V9h4V7H9v10h6z"},"children":[]}]};
|
import * as service from './TestTaskService.js';
import * as util from './TestTaskUtil.js';
// ------------------------------------
// Constants
// ------------------------------------
const RECEIVE_ATTRIBUTES_WITH_VALUES = 'RECEIVE_ATTRIBUTES_WITH_VALUES';
const RECEIVE_VALUES = 'RECEIVE_VALUES';
const UPDATE_ATTRIBUTE_ON_CLIENT = 'UPDATE_ATTRIBUTE_ON_CLIENT';
const RECEIVE_UPDATED_ATTRIBUTE_FROM_SERVER = 'RECEIVE_UPDATED_ATTRIBUTE_FROM_SERVER';
const TOGGLE_ATTRIBUTE_SELECTION = 'TOGGLE_ATTRIBUTE_SELECTION';
const TOGGLE_VALUE_SELECTION = 'TOGGLE_VALUE_SELECTION';
const CALL_API = 'CALL_API';
const SHOW_ERROR = 'SHOW_ERROR';
const HIDE_ERROR = 'HIDE_ERROR';
const DEFAULT_SELECTED_ATTRIBUTE_INDEX = 1;
// ------------------------------------
// Actions
// ------------------------------------
function receiveAttributesWithValues (payload) {
return {
type : RECEIVE_ATTRIBUTES_WITH_VALUES,
payload
}
}
function receiveValues (payload) {
return {
type : RECEIVE_VALUES,
payload
}
}
function callApi () {
return {
type : CALL_API
}
}
function showError (payload) {
return {
type : SHOW_ERROR,
payload
}
}
function hideError () {
return {
type : HIDE_ERROR
}
}
export function toggleAttributeSelection (payload) {
return {
type : TOGGLE_ATTRIBUTE_SELECTION,
payload
}
}
export function toggleValueSelection (payload) {
return {
type : TOGGLE_VALUE_SELECTION,
payload
}
}
export function receiveUpdatedAttributesFromServer (payload) {
return {
type : RECEIVE_UPDATED_ATTRIBUTE_FROM_SERVER,
payload
}
}
/* This is a thunk, meaning it is a function that immediately
returns a function for lazy evaluation. It is incredibly useful for
creating async actions, especially when combined with redux-thunk! */
export function getAttributesWithValuesAndValues() {
return (dispatch) => {
dispatch(callApi()); // this dispatch is for showing loading component
return Promise.all([service.getAttributesWithValues(), service.getValues()])
.then(function(attributesAndValues){
if(true){
// Instead of true check for API status code.
dispatch(receiveAttributesWithValues(attributesAndValues[0]));
dispatch(receiveValues(attributesAndValues[1]));
}
else {
dispatch(showError(error))
}
});
}
}
export function updateAttribute(valueId) {
return (dispatch, getState) => {
let params = {};
params.attributeId = getState().testTask.selectedAttributeId;
params.valueId = valueId;
return Promise(service.updateAttributesWithValues(params))
.then(function(updatedAttribute){
if(true){
// Instead of true check for API status code.
dispatch(receiveUpdatedAttributesFromServer(updatedAttribute));
}
else {
dispatch(showError(error))
}
});
}
}
// ------------------------------------
// Action Handlers
// ------------------------------------
const ACTION_HANDLERS = {
[RECEIVE_ATTRIBUTES_WITH_VALUES] : (state, action) => {
// let attributeWithValues = util.setDefaultSelection(action.payload, DEFAULT_SELECTED_ATTRIBUTE_INDEX );
let attributeWithValues = util.setDefaultSelection(action.payload );
return {...state, attributeWithValues : attributeWithValues }
},
[RECEIVE_VALUES] : (state, action) => {
let valuesSortedByRank = util.sortByRank(action.payload);
return {...state, values : valuesSortedByRank}
},
[UPDATE_ATTRIBUTE_ON_CLIENT] : (state, action) => {
let newAttributeWithValues = state.attributeWithValues;
// logic here
return { ...state, attributeWithValues : newAttributeWithValues}
},
[RECEIVE_UPDATED_ATTRIBUTE_FROM_SERVER] : (state, action) => {
let newAttributeWithValues = utils.updateAttribute(state.attributeWithValues,action.payload);
return { ...state, attributeWithValues : newAttributeWithValues}
},
[TOGGLE_ATTRIBUTE_SELECTION] : (state, action) => {
let isSelected = action.payload.isSelected;
let id = action.payload.id;
let newState = util.updateAttributeSelection(state , id, isSelected )
newState.selectedAttributeId = id;
return { ...newState }
},
[TOGGLE_VALUE_SELECTION] : (state, action) => {
let isSelected = action.payload.isSelected;
let id = action.payload.id;
let newState = util.updateValueSelection(state , id, isSelected )
return { ...newState }
},
[CALL_API] : (state, action) => state,
[SHOW_ERROR] : (state, action) => state,
[HIDE_ERROR] : (state, action) => state
}
// ------------------------------------
// Reducer
// ------------------------------------
const initialState = {
attributeWithValues : [],
values : [],
selectedAttributeId : 1
}
export default function testTaskReducer (state = initialState, action) {
const handler = ACTION_HANDLERS[action.type]
return handler ? handler(state, action) : state
}
|
import rimraf from 'rimraf';
import log from 'fancy-log';
import colors from 'ansi-colors';
import {dirs, sassPaths, JSpaths} from './constants';
export default function clean(done){
log(colors.red('Deleting assets...'));
rimraf(dirs.dest, done);
}
export function cleanScripts(done){
log(colors.red('Deleting JS...'));
rimraf(JSpaths.dest, done);
}
export function cleanStyles(done){
log(colors.red('Deleting CSS...'));
rimraf(sassPaths.dest, done);
}
|
/* ========================================================================
* Bootstrap: transition.js v3.3.5
* http://getbootstrap.com/javascript/#transitions
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/)
// ============================================================
function transitionEnd() {
var el = document.createElement('bootstrap')
var transEndEventNames = {
WebkitTransition : 'webkitTransitionEnd',
MozTransition : 'transitionend',
OTransition : 'oTransitionEnd otransitionend',
transition : 'transitionend'
}
for (var name in transEndEventNames) {
if (el.style[name] !== undefined) {
return { end: transEndEventNames[name] }
}
}
return false // explicit for ie8 ( ._.)
}
// http://blog.alexmaccaw.com/css-transitions
$.fn.emulateTransitionEnd = function (duration) {
var called = false
var $el = this
$(this).one('bsTransitionEnd', function () { called = true })
var callback = function () { if (!called) $($el).trigger($.support.transition.end) }
setTimeout(callback, duration)
return this
}
$(function () {
$.support.transition = transitionEnd()
if (!$.support.transition) return
$.event.special.bsTransitionEnd = {
bindType: $.support.transition.end,
delegateType: $.support.transition.end,
handle: function (e) {
if ($(e.target).is(this)) return e.handleObj.handler.apply(this, arguments)
}
}
})
}(jQuery);
/* ========================================================================
* Bootstrap: alert.js v3.3.5
* http://getbootstrap.com/javascript/#alerts
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// ALERT CLASS DEFINITION
// ======================
var dismiss = '[data-dismiss="alert"]'
var Alert = function (el) {
$(el).on('click', dismiss, this.close)
}
Alert.VERSION = '3.3.5'
Alert.TRANSITION_DURATION = 150
Alert.prototype.close = function (e) {
var $this = $(this)
var selector = $this.attr('data-target')
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
var $parent = $(selector)
if (e) e.preventDefault()
if (!$parent.length) {
$parent = $this.closest('.alert')
}
$parent.trigger(e = $.Event('close.bs.alert'))
if (e.isDefaultPrevented()) return
$parent.removeClass('in')
function removeElement() {
// detach from parent, fire event then clean up data
$parent.detach().trigger('closed.bs.alert').remove()
}
$.support.transition && $parent.hasClass('fade') ?
$parent
.one('bsTransitionEnd', removeElement)
.emulateTransitionEnd(Alert.TRANSITION_DURATION) :
removeElement()
}
// ALERT PLUGIN DEFINITION
// =======================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.alert')
if (!data) $this.data('bs.alert', (data = new Alert(this)))
if (typeof option == 'string') data[option].call($this)
})
}
var old = $.fn.alert
$.fn.alert = Plugin
$.fn.alert.Constructor = Alert
// ALERT NO CONFLICT
// =================
$.fn.alert.noConflict = function () {
$.fn.alert = old
return this
}
// ALERT DATA-API
// ==============
$(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close)
}(jQuery);
/* ========================================================================
* Bootstrap: button.js v3.3.5
* http://getbootstrap.com/javascript/#buttons
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// BUTTON PUBLIC CLASS DEFINITION
// ==============================
var Button = function (element, options) {
this.$element = $(element)
this.options = $.extend({}, Button.DEFAULTS, options)
this.isLoading = false
}
Button.VERSION = '3.3.5'
Button.DEFAULTS = {
loadingText: 'loading...'
}
Button.prototype.setState = function (state) {
var d = 'disabled'
var $el = this.$element
var val = $el.is('input') ? 'val' : 'html'
var data = $el.data()
state += 'Text'
if (data.resetText == null) $el.data('resetText', $el[val]())
// push to event loop to allow forms to submit
setTimeout($.proxy(function () {
$el[val](data[state] == null ? this.options[state] : data[state])
if (state == 'loadingText') {
this.isLoading = true
$el.addClass(d).attr(d, d)
} else if (this.isLoading) {
this.isLoading = false
$el.removeClass(d).removeAttr(d)
}
}, this), 0)
}
Button.prototype.toggle = function () {
var changed = true
var $parent = this.$element.closest('[data-toggle="buttons"]')
if ($parent.length) {
var $input = this.$element.find('input')
if ($input.prop('type') == 'radio') {
if ($input.prop('checked')) changed = false
$parent.find('.active').removeClass('active')
this.$element.addClass('active')
} else if ($input.prop('type') == 'checkbox') {
if (($input.prop('checked')) !== this.$element.hasClass('active')) changed = false
this.$element.toggleClass('active')
}
$input.prop('checked', this.$element.hasClass('active'))
if (changed) $input.trigger('change')
} else {
this.$element.attr('aria-pressed', !this.$element.hasClass('active'))
this.$element.toggleClass('active')
}
}
// BUTTON PLUGIN DEFINITION
// ========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.button')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.button', (data = new Button(this, options)))
if (option == 'toggle') data.toggle()
else if (option) data.setState(option)
})
}
var old = $.fn.button
$.fn.button = Plugin
$.fn.button.Constructor = Button
// BUTTON NO CONFLICT
// ==================
$.fn.button.noConflict = function () {
$.fn.button = old
return this
}
// BUTTON DATA-API
// ===============
$(document)
.on('click.bs.button.data-api', '[data-toggle^="button"]', function (e) {
var $btn = $(e.target)
if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn')
Plugin.call($btn, 'toggle')
if (!($(e.target).is('input[type="radio"]') || $(e.target).is('input[type="checkbox"]'))) e.preventDefault()
})
.on('focus.bs.button.data-api blur.bs.button.data-api', '[data-toggle^="button"]', function (e) {
$(e.target).closest('.btn').toggleClass('focus', /^focus(in)?$/.test(e.type))
})
}(jQuery);
/* ========================================================================
* Bootstrap: carousel.js v3.3.5
* http://getbootstrap.com/javascript/#carousel
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// CAROUSEL CLASS DEFINITION
// =========================
var Carousel = function (element, options) {
this.$element = $(element)
this.$indicators = this.$element.find('.carousel-indicators')
this.options = options
this.paused = null
this.sliding = null
this.interval = null
this.$active = null
this.$items = null
this.options.keyboard && this.$element.on('keydown.bs.carousel', $.proxy(this.keydown, this))
this.options.pause == 'hover' && !('ontouchstart' in document.documentElement) && this.$element
.on('mouseenter.bs.carousel', $.proxy(this.pause, this))
.on('mouseleave.bs.carousel', $.proxy(this.cycle, this))
}
Carousel.VERSION = '3.3.5'
Carousel.TRANSITION_DURATION = 600
Carousel.DEFAULTS = {
interval: 5000,
pause: 'hover',
wrap: true,
keyboard: true
}
Carousel.prototype.keydown = function (e) {
if (/input|textarea/i.test(e.target.tagName)) return
switch (e.which) {
case 37: this.prev(); break
case 39: this.next(); break
default: return
}
e.preventDefault()
}
Carousel.prototype.cycle = function (e) {
e || (this.paused = false)
this.interval && clearInterval(this.interval)
this.options.interval
&& !this.paused
&& (this.interval = setInterval($.proxy(this.next, this), this.options.interval))
return this
}
Carousel.prototype.getItemIndex = function (item) {
this.$items = item.parent().children('.item')
return this.$items.index(item || this.$active)
}
Carousel.prototype.getItemForDirection = function (direction, active) {
var activeIndex = this.getItemIndex(active)
var willWrap = (direction == 'prev' && activeIndex === 0)
|| (direction == 'next' && activeIndex == (this.$items.length - 1))
if (willWrap && !this.options.wrap) return active
var delta = direction == 'prev' ? -1 : 1
var itemIndex = (activeIndex + delta) % this.$items.length
return this.$items.eq(itemIndex)
}
Carousel.prototype.to = function (pos) {
var that = this
var activeIndex = this.getItemIndex(this.$active = this.$element.find('.item.active'))
if (pos > (this.$items.length - 1) || pos < 0) return
if (this.sliding) return this.$element.one('slid.bs.carousel', function () { that.to(pos) }) // yes, "slid"
if (activeIndex == pos) return this.pause().cycle()
return this.slide(pos > activeIndex ? 'next' : 'prev', this.$items.eq(pos))
}
Carousel.prototype.pause = function (e) {
e || (this.paused = true)
if (this.$element.find('.next, .prev').length && $.support.transition) {
this.$element.trigger($.support.transition.end)
this.cycle(true)
}
this.interval = clearInterval(this.interval)
return this
}
Carousel.prototype.next = function () {
if (this.sliding) return
return this.slide('next')
}
Carousel.prototype.prev = function () {
if (this.sliding) return
return this.slide('prev')
}
Carousel.prototype.slide = function (type, next) {
var $active = this.$element.find('.item.active')
var $next = next || this.getItemForDirection(type, $active)
var isCycling = this.interval
var direction = type == 'next' ? 'left' : 'right'
var that = this
if ($next.hasClass('active')) return (this.sliding = false)
var relatedTarget = $next[0]
var slideEvent = $.Event('slide.bs.carousel', {
relatedTarget: relatedTarget,
direction: direction
})
this.$element.trigger(slideEvent)
if (slideEvent.isDefaultPrevented()) return
this.sliding = true
isCycling && this.pause()
if (this.$indicators.length) {
this.$indicators.find('.active').removeClass('active')
var $nextIndicator = $(this.$indicators.children()[this.getItemIndex($next)])
$nextIndicator && $nextIndicator.addClass('active')
}
var slidEvent = $.Event('slid.bs.carousel', { relatedTarget: relatedTarget, direction: direction }) // yes, "slid"
if ($.support.transition && this.$element.hasClass('slide')) {
$next.addClass(type)
$next[0].offsetWidth // force reflow
$active.addClass(direction)
$next.addClass(direction)
$active
.one('bsTransitionEnd', function () {
$next.removeClass([type, direction].join(' ')).addClass('active')
$active.removeClass(['active', direction].join(' '))
that.sliding = false
setTimeout(function () {
that.$element.trigger(slidEvent)
}, 0)
})
.emulateTransitionEnd(Carousel.TRANSITION_DURATION)
} else {
$active.removeClass('active')
$next.addClass('active')
this.sliding = false
this.$element.trigger(slidEvent)
}
isCycling && this.cycle()
return this
}
// CAROUSEL PLUGIN DEFINITION
// ==========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.carousel')
var options = $.extend({}, Carousel.DEFAULTS, $this.data(), typeof option == 'object' && option)
var action = typeof option == 'string' ? option : options.slide
if (!data) $this.data('bs.carousel', (data = new Carousel(this, options)))
if (typeof option == 'number') data.to(option)
else if (action) data[action]()
else if (options.interval) data.pause().cycle()
})
}
var old = $.fn.carousel
$.fn.carousel = Plugin
$.fn.carousel.Constructor = Carousel
// CAROUSEL NO CONFLICT
// ====================
$.fn.carousel.noConflict = function () {
$.fn.carousel = old
return this
}
// CAROUSEL DATA-API
// =================
var clickHandler = function (e) {
var href
var $this = $(this)
var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) // strip for ie7
if (!$target.hasClass('carousel')) return
var options = $.extend({}, $target.data(), $this.data())
var slideIndex = $this.attr('data-slide-to')
if (slideIndex) options.interval = false
Plugin.call($target, options)
if (slideIndex) {
$target.data('bs.carousel').to(slideIndex)
}
e.preventDefault()
}
$(document)
.on('click.bs.carousel.data-api', '[data-slide]', clickHandler)
.on('click.bs.carousel.data-api', '[data-slide-to]', clickHandler)
$(window).on('load', function () {
$('[data-ride="carousel"]').each(function () {
var $carousel = $(this)
Plugin.call($carousel, $carousel.data())
})
})
}(jQuery);
/* ========================================================================
* Bootstrap: collapse.js v3.3.5
* http://getbootstrap.com/javascript/#collapse
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// COLLAPSE PUBLIC CLASS DEFINITION
// ================================
var Collapse = function (element, options) {
this.$element = $(element)
this.options = $.extend({}, Collapse.DEFAULTS, options)
this.$trigger = $('[data-toggle="collapse"][href="#' + element.id + '"],' +
'[data-toggle="collapse"][data-target="#' + element.id + '"]')
this.transitioning = null
if (this.options.parent) {
this.$parent = this.getParent()
} else {
this.addAriaAndCollapsedClass(this.$element, this.$trigger)
}
if (this.options.toggle) this.toggle()
}
Collapse.VERSION = '3.3.5'
Collapse.TRANSITION_DURATION = 350
Collapse.DEFAULTS = {
toggle: true
}
Collapse.prototype.dimension = function () {
var hasWidth = this.$element.hasClass('width')
return hasWidth ? 'width' : 'height'
}
Collapse.prototype.show = function () {
if (this.transitioning || this.$element.hasClass('in')) return
var activesData
var actives = this.$parent && this.$parent.children('.panel').children('.in, .collapsing')
if (actives && actives.length) {
activesData = actives.data('bs.collapse')
if (activesData && activesData.transitioning) return
}
var startEvent = $.Event('show.bs.collapse')
this.$element.trigger(startEvent)
if (startEvent.isDefaultPrevented()) return
if (actives && actives.length) {
Plugin.call(actives, 'hide')
activesData || actives.data('bs.collapse', null)
}
var dimension = this.dimension()
this.$element
.removeClass('collapse')
.addClass('collapsing')[dimension](0)
.attr('aria-expanded', true)
this.$trigger
.removeClass('collapsed')
.attr('aria-expanded', true)
this.transitioning = 1
var complete = function () {
this.$element
.removeClass('collapsing')
.addClass('collapse in')[dimension]('')
this.transitioning = 0
this.$element
.trigger('shown.bs.collapse')
}
if (!$.support.transition) return complete.call(this)
var scrollSize = $.camelCase(['scroll', dimension].join('-'))
this.$element
.one('bsTransitionEnd', $.proxy(complete, this))
.emulateTransitionEnd(Collapse.TRANSITION_DURATION)[dimension](this.$element[0][scrollSize])
}
Collapse.prototype.hide = function () {
if (this.transitioning || !this.$element.hasClass('in')) return
var startEvent = $.Event('hide.bs.collapse')
this.$element.trigger(startEvent)
if (startEvent.isDefaultPrevented()) return
var dimension = this.dimension()
this.$element[dimension](this.$element[dimension]())[0].offsetHeight
this.$element
.addClass('collapsing')
.removeClass('collapse in')
.attr('aria-expanded', false)
this.$trigger
.addClass('collapsed')
.attr('aria-expanded', false)
this.transitioning = 1
var complete = function () {
this.transitioning = 0
this.$element
.removeClass('collapsing')
.addClass('collapse')
.trigger('hidden.bs.collapse')
}
if (!$.support.transition) return complete.call(this)
this.$element
[dimension](0)
.one('bsTransitionEnd', $.proxy(complete, this))
.emulateTransitionEnd(Collapse.TRANSITION_DURATION)
}
Collapse.prototype.toggle = function () {
this[this.$element.hasClass('in') ? 'hide' : 'show']()
}
Collapse.prototype.getParent = function () {
return $(this.options.parent)
.find('[data-toggle="collapse"][data-parent="' + this.options.parent + '"]')
.each($.proxy(function (i, element) {
var $element = $(element)
this.addAriaAndCollapsedClass(getTargetFromTrigger($element), $element)
}, this))
.end()
}
Collapse.prototype.addAriaAndCollapsedClass = function ($element, $trigger) {
var isOpen = $element.hasClass('in')
$element.attr('aria-expanded', isOpen)
$trigger
.toggleClass('collapsed', !isOpen)
.attr('aria-expanded', isOpen)
}
function getTargetFromTrigger($trigger) {
var href
var target = $trigger.attr('data-target')
|| (href = $trigger.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') // strip for ie7
return $(target)
}
// COLLAPSE PLUGIN DEFINITION
// ==========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.collapse')
var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option)
if (!data && options.toggle && /show|hide/.test(option)) options.toggle = false
if (!data) $this.data('bs.collapse', (data = new Collapse(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.collapse
$.fn.collapse = Plugin
$.fn.collapse.Constructor = Collapse
// COLLAPSE NO CONFLICT
// ====================
$.fn.collapse.noConflict = function () {
$.fn.collapse = old
return this
}
// COLLAPSE DATA-API
// =================
$(document).on('click.bs.collapse.data-api', '[data-toggle="collapse"]', function (e) {
var $this = $(this)
if (!$this.attr('data-target')) e.preventDefault()
var $target = getTargetFromTrigger($this)
var data = $target.data('bs.collapse')
var option = data ? 'toggle' : $this.data()
Plugin.call($target, option)
})
}(jQuery);
/* ========================================================================
* Bootstrap: dropdown.js v3.3.5
* http://getbootstrap.com/javascript/#dropdowns
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// DROPDOWN CLASS DEFINITION
// =========================
var backdrop = '.dropdown-backdrop'
var toggle = '[data-toggle="dropdown"]'
var Dropdown = function (element) {
$(element).on('click.bs.dropdown', this.toggle)
}
Dropdown.VERSION = '3.3.5'
function getParent($this) {
var selector = $this.attr('data-target')
if (!selector) {
selector = $this.attr('href')
selector = selector && /#[A-Za-z]/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
var $parent = selector && $(selector)
return $parent && $parent.length ? $parent : $this.parent()
}
function clearMenus(e) {
if (e && e.which === 3) return
$(backdrop).remove()
$(toggle).each(function () {
var $this = $(this)
var $parent = getParent($this)
var relatedTarget = { relatedTarget: this }
if (!$parent.hasClass('open')) return
if (e && e.type == 'click' && /input|textarea/i.test(e.target.tagName) && $.contains($parent[0], e.target)) return
$parent.trigger(e = $.Event('hide.bs.dropdown', relatedTarget))
if (e.isDefaultPrevented()) return
$this.attr('aria-expanded', 'false')
$parent.removeClass('open').trigger('hidden.bs.dropdown', relatedTarget)
})
}
Dropdown.prototype.toggle = function (e) {
var $this = $(this)
if ($this.is('.disabled, :disabled')) return
var $parent = getParent($this)
var isActive = $parent.hasClass('open')
clearMenus()
if (!isActive) {
if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) {
// if mobile we use a backdrop because click events don't delegate
$(document.createElement('div'))
.addClass('dropdown-backdrop')
.insertAfter($(this))
.on('click', clearMenus)
}
var relatedTarget = { relatedTarget: this }
$parent.trigger(e = $.Event('show.bs.dropdown', relatedTarget))
if (e.isDefaultPrevented()) return
$this
.trigger('focus')
.attr('aria-expanded', 'true')
$parent
.toggleClass('open')
.trigger('shown.bs.dropdown', relatedTarget)
}
return false
}
Dropdown.prototype.keydown = function (e) {
if (!/(38|40|27|32)/.test(e.which) || /input|textarea/i.test(e.target.tagName)) return
var $this = $(this)
e.preventDefault()
e.stopPropagation()
if ($this.is('.disabled, :disabled')) return
var $parent = getParent($this)
var isActive = $parent.hasClass('open')
if (!isActive && e.which != 27 || isActive && e.which == 27) {
if (e.which == 27) $parent.find(toggle).trigger('focus')
return $this.trigger('click')
}
var desc = ' li:not(.disabled):visible a'
var $items = $parent.find('.dropdown-menu' + desc)
if (!$items.length) return
var index = $items.index(e.target)
if (e.which == 38 && index > 0) index-- // up
if (e.which == 40 && index < $items.length - 1) index++ // down
if (!~index) index = 0
$items.eq(index).trigger('focus')
}
// DROPDOWN PLUGIN DEFINITION
// ==========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.dropdown')
if (!data) $this.data('bs.dropdown', (data = new Dropdown(this)))
if (typeof option == 'string') data[option].call($this)
})
}
var old = $.fn.dropdown
$.fn.dropdown = Plugin
$.fn.dropdown.Constructor = Dropdown
// DROPDOWN NO CONFLICT
// ====================
$.fn.dropdown.noConflict = function () {
$.fn.dropdown = old
return this
}
// APPLY TO STANDARD DROPDOWN ELEMENTS
// ===================================
$(document)
.on('click.bs.dropdown.data-api', clearMenus)
.on('click.bs.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() })
.on('click.bs.dropdown.data-api', toggle, Dropdown.prototype.toggle)
.on('keydown.bs.dropdown.data-api', toggle, Dropdown.prototype.keydown)
.on('keydown.bs.dropdown.data-api', '.dropdown-menu', Dropdown.prototype.keydown)
}(jQuery);
/* ========================================================================
* Bootstrap: modal.js v3.3.5
* http://getbootstrap.com/javascript/#modals
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// MODAL CLASS DEFINITION
// ======================
var Modal = function (element, options) {
this.options = options
this.$body = $(document.body)
this.$element = $(element)
this.$dialog = this.$element.find('.modal-dialog')
this.$backdrop = null
this.isShown = null
this.originalBodyPad = null
this.scrollbarWidth = 0
this.ignoreBackdropClick = false
if (this.options.remote) {
this.$element
.find('.modal-content')
.load(this.options.remote, $.proxy(function () {
this.$element.trigger('loaded.bs.modal')
}, this))
}
}
Modal.VERSION = '3.3.5'
Modal.TRANSITION_DURATION = 300
Modal.BACKDROP_TRANSITION_DURATION = 150
Modal.DEFAULTS = {
backdrop: true,
keyboard: true,
show: true
}
Modal.prototype.toggle = function (_relatedTarget) {
return this.isShown ? this.hide() : this.show(_relatedTarget)
}
Modal.prototype.show = function (_relatedTarget) {
var that = this
var e = $.Event('show.bs.modal', { relatedTarget: _relatedTarget })
this.$element.trigger(e)
if (this.isShown || e.isDefaultPrevented()) return
this.isShown = true
this.checkScrollbar()
this.setScrollbar()
this.$body.addClass('modal-open')
this.escape()
this.resize()
this.$element.on('click.dismiss.bs.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this))
this.$dialog.on('mousedown.dismiss.bs.modal', function () {
that.$element.one('mouseup.dismiss.bs.modal', function (e) {
if ($(e.target).is(that.$element)) that.ignoreBackdropClick = true
})
})
this.backdrop(function () {
var transition = $.support.transition && that.$element.hasClass('fade')
if (!that.$element.parent().length) {
that.$element.appendTo(that.$body) // don't move modals dom position
}
that.$element
.show()
.scrollTop(0)
that.adjustDialog()
if (transition) {
that.$element[0].offsetWidth // force reflow
}
that.$element.addClass('in')
that.enforceFocus()
var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget })
transition ?
that.$dialog // wait for modal to slide in
.one('bsTransitionEnd', function () {
that.$element.trigger('focus').trigger(e)
})
.emulateTransitionEnd(Modal.TRANSITION_DURATION) :
that.$element.trigger('focus').trigger(e)
})
}
Modal.prototype.hide = function (e) {
if (e) e.preventDefault()
e = $.Event('hide.bs.modal')
this.$element.trigger(e)
if (!this.isShown || e.isDefaultPrevented()) return
this.isShown = false
this.escape()
this.resize()
$(document).off('focusin.bs.modal')
this.$element
.removeClass('in')
.off('click.dismiss.bs.modal')
.off('mouseup.dismiss.bs.modal')
this.$dialog.off('mousedown.dismiss.bs.modal')
$.support.transition && this.$element.hasClass('fade') ?
this.$element
.one('bsTransitionEnd', $.proxy(this.hideModal, this))
.emulateTransitionEnd(Modal.TRANSITION_DURATION) :
this.hideModal()
}
Modal.prototype.enforceFocus = function () {
$(document)
.off('focusin.bs.modal') // guard against infinite focus loop
.on('focusin.bs.modal', $.proxy(function (e) {
if (this.$element[0] !== e.target && !this.$element.has(e.target).length) {
this.$element.trigger('focus')
}
}, this))
}
Modal.prototype.escape = function () {
if (this.isShown && this.options.keyboard) {
this.$element.on('keydown.dismiss.bs.modal', $.proxy(function (e) {
e.which == 27 && this.hide()
}, this))
} else if (!this.isShown) {
this.$element.off('keydown.dismiss.bs.modal')
}
}
Modal.prototype.resize = function () {
if (this.isShown) {
$(window).on('resize.bs.modal', $.proxy(this.handleUpdate, this))
} else {
$(window).off('resize.bs.modal')
}
}
Modal.prototype.hideModal = function () {
var that = this
this.$element.hide()
this.backdrop(function () {
that.$body.removeClass('modal-open')
that.resetAdjustments()
that.resetScrollbar()
that.$element.trigger('hidden.bs.modal')
})
}
Modal.prototype.removeBackdrop = function () {
this.$backdrop && this.$backdrop.remove()
this.$backdrop = null
}
Modal.prototype.backdrop = function (callback) {
var that = this
var animate = this.$element.hasClass('fade') ? 'fade' : ''
if (this.isShown && this.options.backdrop) {
var doAnimate = $.support.transition && animate
this.$backdrop = $(document.createElement('div'))
.addClass('modal-backdrop ' + animate)
.appendTo(this.$body)
this.$element.on('click.dismiss.bs.modal', $.proxy(function (e) {
if (this.ignoreBackdropClick) {
this.ignoreBackdropClick = false
return
}
if (e.target !== e.currentTarget) return
this.options.backdrop == 'static'
? this.$element[0].focus()
: this.hide()
}, this))
if (doAnimate) this.$backdrop[0].offsetWidth // force reflow
this.$backdrop.addClass('in')
if (!callback) return
doAnimate ?
this.$backdrop
.one('bsTransitionEnd', callback)
.emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) :
callback()
} else if (!this.isShown && this.$backdrop) {
this.$backdrop.removeClass('in')
var callbackRemove = function () {
that.removeBackdrop()
callback && callback()
}
$.support.transition && this.$element.hasClass('fade') ?
this.$backdrop
.one('bsTransitionEnd', callbackRemove)
.emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) :
callbackRemove()
} else if (callback) {
callback()
}
}
// these following methods are used to handle overflowing modals
Modal.prototype.handleUpdate = function () {
this.adjustDialog()
}
Modal.prototype.adjustDialog = function () {
var modalIsOverflowing = this.$element[0].scrollHeight > document.documentElement.clientHeight
this.$element.css({
paddingLeft: !this.bodyIsOverflowing && modalIsOverflowing ? this.scrollbarWidth : '',
paddingRight: this.bodyIsOverflowing && !modalIsOverflowing ? this.scrollbarWidth : ''
})
}
Modal.prototype.resetAdjustments = function () {
this.$element.css({
paddingLeft: '',
paddingRight: ''
})
}
Modal.prototype.checkScrollbar = function () {
var fullWindowWidth = window.innerWidth
if (!fullWindowWidth) { // workaround for missing window.innerWidth in IE8
var documentElementRect = document.documentElement.getBoundingClientRect()
fullWindowWidth = documentElementRect.right - Math.abs(documentElementRect.left)
}
this.bodyIsOverflowing = document.body.clientWidth < fullWindowWidth
this.scrollbarWidth = this.measureScrollbar()
}
Modal.prototype.setScrollbar = function () {
var bodyPad = parseInt((this.$body.css('padding-right') || 0), 10)
this.originalBodyPad = document.body.style.paddingRight || ''
if (this.bodyIsOverflowing) this.$body.css('padding-right', bodyPad + this.scrollbarWidth)
}
Modal.prototype.resetScrollbar = function () {
this.$body.css('padding-right', this.originalBodyPad)
}
Modal.prototype.measureScrollbar = function () { // thx walsh
var scrollDiv = document.createElement('div')
scrollDiv.className = 'modal-scrollbar-measure'
this.$body.append(scrollDiv)
var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth
this.$body[0].removeChild(scrollDiv)
return scrollbarWidth
}
// MODAL PLUGIN DEFINITION
// =======================
function Plugin(option, _relatedTarget) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.modal')
var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option)
if (!data) $this.data('bs.modal', (data = new Modal(this, options)))
if (typeof option == 'string') data[option](_relatedTarget)
else if (options.show) data.show(_relatedTarget)
})
}
var old = $.fn.modal
$.fn.modal = Plugin
$.fn.modal.Constructor = Modal
// MODAL NO CONFLICT
// =================
$.fn.modal.noConflict = function () {
$.fn.modal = old
return this
}
// MODAL DATA-API
// ==============
$(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) {
var $this = $(this)
var href = $this.attr('href')
var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) // strip for ie7
var option = $target.data('bs.modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data())
if ($this.is('a')) e.preventDefault()
$target.one('show.bs.modal', function (showEvent) {
if (showEvent.isDefaultPrevented()) return // only register focus restorer if modal will actually get shown
$target.one('hidden.bs.modal', function () {
$this.is(':visible') && $this.trigger('focus')
})
})
Plugin.call($target, option, this)
})
}(jQuery);
/* ========================================================================
* Bootstrap: tooltip.js v3.3.5
* http://getbootstrap.com/javascript/#tooltip
* Inspired by the original jQuery.tipsy by Jason Frame
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// TOOLTIP PUBLIC CLASS DEFINITION
// ===============================
var Tooltip = function (element, options) {
this.type = null
this.options = null
this.enabled = null
this.timeout = null
this.hoverState = null
this.$element = null
this.inState = null
this.init('tooltip', element, options)
}
Tooltip.VERSION = '3.3.5'
Tooltip.TRANSITION_DURATION = 150
Tooltip.DEFAULTS = {
animation: true,
placement: 'top',
selector: false,
template: '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',
trigger: 'hover focus',
title: '',
delay: 0,
html: false,
container: false,
viewport: {
selector: 'body',
padding: 0
}
}
Tooltip.prototype.init = function (type, element, options) {
this.enabled = true
this.type = type
this.$element = $(element)
this.options = this.getOptions(options)
this.$viewport = this.options.viewport && $($.isFunction(this.options.viewport) ? this.options.viewport.call(this, this.$element) : (this.options.viewport.selector || this.options.viewport))
this.inState = { click: false, hover: false, focus: false }
if (this.$element[0] instanceof document.constructor && !this.options.selector) {
throw new Error('`selector` option must be specified when initializing ' + this.type + ' on the window.document object!')
}
var triggers = this.options.trigger.split(' ')
for (var i = triggers.length; i--;) {
var trigger = triggers[i]
if (trigger == 'click') {
this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this))
} else if (trigger != 'manual') {
var eventIn = trigger == 'hover' ? 'mouseenter' : 'focusin'
var eventOut = trigger == 'hover' ? 'mouseleave' : 'focusout'
this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this))
this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this))
}
}
this.options.selector ?
(this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) :
this.fixTitle()
}
Tooltip.prototype.getDefaults = function () {
return Tooltip.DEFAULTS
}
Tooltip.prototype.getOptions = function (options) {
options = $.extend({}, this.getDefaults(), this.$element.data(), options)
if (options.delay && typeof options.delay == 'number') {
options.delay = {
show: options.delay,
hide: options.delay
}
}
return options
}
Tooltip.prototype.getDelegateOptions = function () {
var options = {}
var defaults = this.getDefaults()
this._options && $.each(this._options, function (key, value) {
if (defaults[key] != value) options[key] = value
})
return options
}
Tooltip.prototype.enter = function (obj) {
var self = obj instanceof this.constructor ?
obj : $(obj.currentTarget).data('bs.' + this.type)
if (!self) {
self = new this.constructor(obj.currentTarget, this.getDelegateOptions())
$(obj.currentTarget).data('bs.' + this.type, self)
}
if (obj instanceof $.Event) {
self.inState[obj.type == 'focusin' ? 'focus' : 'hover'] = true
}
if (self.tip().hasClass('in') || self.hoverState == 'in') {
self.hoverState = 'in'
return
}
clearTimeout(self.timeout)
self.hoverState = 'in'
if (!self.options.delay || !self.options.delay.show) return self.show()
self.timeout = setTimeout(function () {
if (self.hoverState == 'in') self.show()
}, self.options.delay.show)
}
Tooltip.prototype.isInStateTrue = function () {
for (var key in this.inState) {
if (this.inState[key]) return true
}
return false
}
Tooltip.prototype.leave = function (obj) {
var self = obj instanceof this.constructor ?
obj : $(obj.currentTarget).data('bs.' + this.type)
if (!self) {
self = new this.constructor(obj.currentTarget, this.getDelegateOptions())
$(obj.currentTarget).data('bs.' + this.type, self)
}
if (obj instanceof $.Event) {
self.inState[obj.type == 'focusout' ? 'focus' : 'hover'] = false
}
if (self.isInStateTrue()) return
clearTimeout(self.timeout)
self.hoverState = 'out'
if (!self.options.delay || !self.options.delay.hide) return self.hide()
self.timeout = setTimeout(function () {
if (self.hoverState == 'out') self.hide()
}, self.options.delay.hide)
}
Tooltip.prototype.show = function () {
var e = $.Event('show.bs.' + this.type)
if (this.hasContent() && this.enabled) {
this.$element.trigger(e)
var inDom = $.contains(this.$element[0].ownerDocument.documentElement, this.$element[0])
if (e.isDefaultPrevented() || !inDom) return
var that = this
var $tip = this.tip()
var tipId = this.getUID(this.type)
this.setContent()
$tip.attr('id', tipId)
this.$element.attr('aria-describedby', tipId)
if (this.options.animation) $tip.addClass('fade')
var placement = typeof this.options.placement == 'function' ?
this.options.placement.call(this, $tip[0], this.$element[0]) :
this.options.placement
var autoToken = /\s?auto?\s?/i
var autoPlace = autoToken.test(placement)
if (autoPlace) placement = placement.replace(autoToken, '') || 'top'
$tip
.detach()
.css({ top: 0, left: 0, display: 'block' })
.addClass(placement)
.data('bs.' + this.type, this)
this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element)
this.$element.trigger('inserted.bs.' + this.type)
var pos = this.getPosition()
var actualWidth = $tip[0].offsetWidth
var actualHeight = $tip[0].offsetHeight
if (autoPlace) {
var orgPlacement = placement
var viewportDim = this.getPosition(this.$viewport)
placement = placement == 'bottom' && pos.bottom + actualHeight > viewportDim.bottom ? 'top' :
placement == 'top' && pos.top - actualHeight < viewportDim.top ? 'bottom' :
placement == 'right' && pos.right + actualWidth > viewportDim.width ? 'left' :
placement == 'left' && pos.left - actualWidth < viewportDim.left ? 'right' :
placement
$tip
.removeClass(orgPlacement)
.addClass(placement)
}
var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight)
this.applyPlacement(calculatedOffset, placement)
var complete = function () {
var prevHoverState = that.hoverState
that.$element.trigger('shown.bs.' + that.type)
that.hoverState = null
if (prevHoverState == 'out') that.leave(that)
}
$.support.transition && this.$tip.hasClass('fade') ?
$tip
.one('bsTransitionEnd', complete)
.emulateTransitionEnd(Tooltip.TRANSITION_DURATION) :
complete()
}
}
Tooltip.prototype.applyPlacement = function (offset, placement) {
var $tip = this.tip()
var width = $tip[0].offsetWidth
var height = $tip[0].offsetHeight
// manually read margins because getBoundingClientRect includes difference
var marginTop = parseInt($tip.css('margin-top'), 10)
var marginLeft = parseInt($tip.css('margin-left'), 10)
// we must check for NaN for ie 8/9
if (isNaN(marginTop)) marginTop = 0
if (isNaN(marginLeft)) marginLeft = 0
offset.top += marginTop
offset.left += marginLeft
// $.fn.offset doesn't round pixel values
// so we use setOffset directly with our own function B-0
$.offset.setOffset($tip[0], $.extend({
using: function (props) {
$tip.css({
top: Math.round(props.top),
left: Math.round(props.left)
})
}
}, offset), 0)
$tip.addClass('in')
// check to see if placing tip in new offset caused the tip to resize itself
var actualWidth = $tip[0].offsetWidth
var actualHeight = $tip[0].offsetHeight
if (placement == 'top' && actualHeight != height) {
offset.top = offset.top + height - actualHeight
}
var delta = this.getViewportAdjustedDelta(placement, offset, actualWidth, actualHeight)
if (delta.left) offset.left += delta.left
else offset.top += delta.top
var isVertical = /top|bottom/.test(placement)
var arrowDelta = isVertical ? delta.left * 2 - width + actualWidth : delta.top * 2 - height + actualHeight
var arrowOffsetPosition = isVertical ? 'offsetWidth' : 'offsetHeight'
$tip.offset(offset)
this.replaceArrow(arrowDelta, $tip[0][arrowOffsetPosition], isVertical)
}
Tooltip.prototype.replaceArrow = function (delta, dimension, isVertical) {
this.arrow()
.css(isVertical ? 'left' : 'top', 50 * (1 - delta / dimension) + '%')
.css(isVertical ? 'top' : 'left', '')
}
Tooltip.prototype.setContent = function () {
var $tip = this.tip()
var title = this.getTitle()
$tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title)
$tip.removeClass('fade in top bottom left right')
}
Tooltip.prototype.hide = function (callback) {
var that = this
var $tip = $(this.$tip)
var e = $.Event('hide.bs.' + this.type)
function complete() {
if (that.hoverState != 'in') $tip.detach()
that.$element
.removeAttr('aria-describedby')
.trigger('hidden.bs.' + that.type)
callback && callback()
}
this.$element.trigger(e)
if (e.isDefaultPrevented()) return
$tip.removeClass('in')
$.support.transition && $tip.hasClass('fade') ?
$tip
.one('bsTransitionEnd', complete)
.emulateTransitionEnd(Tooltip.TRANSITION_DURATION) :
complete()
this.hoverState = null
return this
}
Tooltip.prototype.fixTitle = function () {
var $e = this.$element
if ($e.attr('title') || typeof $e.attr('data-original-title') != 'string') {
$e.attr('data-original-title', $e.attr('title') || '').attr('title', '')
}
}
Tooltip.prototype.hasContent = function () {
return this.getTitle()
}
Tooltip.prototype.getPosition = function ($element) {
$element = $element || this.$element
var el = $element[0]
var isBody = el.tagName == 'BODY'
var elRect = el.getBoundingClientRect()
if (elRect.width == null) {
// width and height are missing in IE8, so compute them manually; see https://github.com/twbs/bootstrap/issues/14093
elRect = $.extend({}, elRect, { width: elRect.right - elRect.left, height: elRect.bottom - elRect.top })
}
var elOffset = isBody ? { top: 0, left: 0 } : $element.offset()
var scroll = { scroll: isBody ? document.documentElement.scrollTop || document.body.scrollTop : $element.scrollTop() }
var outerDims = isBody ? { width: $(window).width(), height: $(window).height() } : null
return $.extend({}, elRect, scroll, outerDims, elOffset)
}
Tooltip.prototype.getCalculatedOffset = function (placement, pos, actualWidth, actualHeight) {
return placement == 'bottom' ? { top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2 } :
placement == 'top' ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2 } :
placement == 'left' ? { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth } :
/* placement == 'right' */ { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width }
}
Tooltip.prototype.getViewportAdjustedDelta = function (placement, pos, actualWidth, actualHeight) {
var delta = { top: 0, left: 0 }
if (!this.$viewport) return delta
var viewportPadding = this.options.viewport && this.options.viewport.padding || 0
var viewportDimensions = this.getPosition(this.$viewport)
if (/right|left/.test(placement)) {
var topEdgeOffset = pos.top - viewportPadding - viewportDimensions.scroll
var bottomEdgeOffset = pos.top + viewportPadding - viewportDimensions.scroll + actualHeight
if (topEdgeOffset < viewportDimensions.top) { // top overflow
delta.top = viewportDimensions.top - topEdgeOffset
} else if (bottomEdgeOffset > viewportDimensions.top + viewportDimensions.height) { // bottom overflow
delta.top = viewportDimensions.top + viewportDimensions.height - bottomEdgeOffset
}
} else {
var leftEdgeOffset = pos.left - viewportPadding
var rightEdgeOffset = pos.left + viewportPadding + actualWidth
if (leftEdgeOffset < viewportDimensions.left) { // left overflow
delta.left = viewportDimensions.left - leftEdgeOffset
} else if (rightEdgeOffset > viewportDimensions.right) { // right overflow
delta.left = viewportDimensions.left + viewportDimensions.width - rightEdgeOffset
}
}
return delta
}
Tooltip.prototype.getTitle = function () {
var title
var $e = this.$element
var o = this.options
title = $e.attr('data-original-title')
|| (typeof o.title == 'function' ? o.title.call($e[0]) : o.title)
return title
}
Tooltip.prototype.getUID = function (prefix) {
do prefix += ~~(Math.random() * 1000000)
while (document.getElementById(prefix))
return prefix
}
Tooltip.prototype.tip = function () {
if (!this.$tip) {
this.$tip = $(this.options.template)
if (this.$tip.length != 1) {
throw new Error(this.type + ' `template` option must consist of exactly 1 top-level element!')
}
}
return this.$tip
}
Tooltip.prototype.arrow = function () {
return (this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow'))
}
Tooltip.prototype.enable = function () {
this.enabled = true
}
Tooltip.prototype.disable = function () {
this.enabled = false
}
Tooltip.prototype.toggleEnabled = function () {
this.enabled = !this.enabled
}
Tooltip.prototype.toggle = function (e) {
var self = this
if (e) {
self = $(e.currentTarget).data('bs.' + this.type)
if (!self) {
self = new this.constructor(e.currentTarget, this.getDelegateOptions())
$(e.currentTarget).data('bs.' + this.type, self)
}
}
if (e) {
self.inState.click = !self.inState.click
if (self.isInStateTrue()) self.enter(self)
else self.leave(self)
} else {
self.tip().hasClass('in') ? self.leave(self) : self.enter(self)
}
}
Tooltip.prototype.destroy = function () {
var that = this
clearTimeout(this.timeout)
this.hide(function () {
that.$element.off('.' + that.type).removeData('bs.' + that.type)
if (that.$tip) {
that.$tip.detach()
}
that.$tip = null
that.$arrow = null
that.$viewport = null
})
}
// TOOLTIP PLUGIN DEFINITION
// =========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.tooltip')
var options = typeof option == 'object' && option
if (!data && /destroy|hide/.test(option)) return
if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.tooltip
$.fn.tooltip = Plugin
$.fn.tooltip.Constructor = Tooltip
// TOOLTIP NO CONFLICT
// ===================
$.fn.tooltip.noConflict = function () {
$.fn.tooltip = old
return this
}
}(jQuery);
/* ========================================================================
* Bootstrap: popover.js v3.3.5
* http://getbootstrap.com/javascript/#popovers
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// POPOVER PUBLIC CLASS DEFINITION
// ===============================
var Popover = function (element, options) {
this.init('popover', element, options)
}
if (!$.fn.tooltip) throw new Error('Popover requires tooltip.js')
Popover.VERSION = '3.3.5'
Popover.DEFAULTS = $.extend({}, $.fn.tooltip.Constructor.DEFAULTS, {
placement: 'right',
trigger: 'click',
content: '',
template: '<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'
})
// NOTE: POPOVER EXTENDS tooltip.js
// ================================
Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype)
Popover.prototype.constructor = Popover
Popover.prototype.getDefaults = function () {
return Popover.DEFAULTS
}
Popover.prototype.setContent = function () {
var $tip = this.tip()
var title = this.getTitle()
var content = this.getContent()
$tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title)
$tip.find('.popover-content').children().detach().end()[ // we use append for html objects to maintain js events
this.options.html ? (typeof content == 'string' ? 'html' : 'append') : 'text'
](content)
$tip.removeClass('fade top bottom left right in')
// IE8 doesn't accept hiding via the `:empty` pseudo selector, we have to do
// this manually by checking the contents.
if (!$tip.find('.popover-title').html()) $tip.find('.popover-title').hide()
}
Popover.prototype.hasContent = function () {
return this.getTitle() || this.getContent()
}
Popover.prototype.getContent = function () {
var $e = this.$element
var o = this.options
return $e.attr('data-content')
|| (typeof o.content == 'function' ?
o.content.call($e[0]) :
o.content)
}
Popover.prototype.arrow = function () {
return (this.$arrow = this.$arrow || this.tip().find('.arrow'))
}
// POPOVER PLUGIN DEFINITION
// =========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.popover')
var options = typeof option == 'object' && option
if (!data && /destroy|hide/.test(option)) return
if (!data) $this.data('bs.popover', (data = new Popover(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.popover
$.fn.popover = Plugin
$.fn.popover.Constructor = Popover
// POPOVER NO CONFLICT
// ===================
$.fn.popover.noConflict = function () {
$.fn.popover = old
return this
}
}(jQuery);
/* ========================================================================
* Bootstrap: scrollspy.js v3.3.5
* http://getbootstrap.com/javascript/#scrollspy
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// SCROLLSPY CLASS DEFINITION
// ==========================
function ScrollSpy(element, options) {
this.$body = $(document.body)
this.$scrollElement = $(element).is(document.body) ? $(window) : $(element)
this.options = $.extend({}, ScrollSpy.DEFAULTS, options)
this.selector = (this.options.target || '') + ' .nav li > a'
this.offsets = []
this.targets = []
this.activeTarget = null
this.scrollHeight = 0
this.$scrollElement.on('scroll.bs.scrollspy', $.proxy(this.process, this))
this.refresh()
this.process()
}
ScrollSpy.VERSION = '3.3.5'
ScrollSpy.DEFAULTS = {
offset: 10
}
ScrollSpy.prototype.getScrollHeight = function () {
return this.$scrollElement[0].scrollHeight || Math.max(this.$body[0].scrollHeight, document.documentElement.scrollHeight)
}
ScrollSpy.prototype.refresh = function () {
var that = this
var offsetMethod = 'offset'
var offsetBase = 0
this.offsets = []
this.targets = []
this.scrollHeight = this.getScrollHeight()
if (!$.isWindow(this.$scrollElement[0])) {
offsetMethod = 'position'
offsetBase = this.$scrollElement.scrollTop()
}
this.$body
.find(this.selector)
.map(function () {
var $el = $(this)
var href = $el.data('target') || $el.attr('href')
var $href = /^#./.test(href) && $(href)
return ($href
&& $href.length
&& $href.is(':visible')
&& [[$href[offsetMethod]().top + offsetBase, href]]) || null
})
.sort(function (a, b) { return a[0] - b[0] })
.each(function () {
that.offsets.push(this[0])
that.targets.push(this[1])
})
}
ScrollSpy.prototype.process = function () {
var scrollTop = this.$scrollElement.scrollTop() + this.options.offset
var scrollHeight = this.getScrollHeight()
var maxScroll = this.options.offset + scrollHeight - this.$scrollElement.height()
var offsets = this.offsets
var targets = this.targets
var activeTarget = this.activeTarget
var i
if (this.scrollHeight != scrollHeight) {
this.refresh()
}
if (scrollTop >= maxScroll) {
return activeTarget != (i = targets[targets.length - 1]) && this.activate(i)
}
if (activeTarget && scrollTop < offsets[0]) {
this.activeTarget = null
return this.clear()
}
for (i = offsets.length; i--;) {
activeTarget != targets[i]
&& scrollTop >= offsets[i]
&& (offsets[i + 1] === undefined || scrollTop < offsets[i + 1])
&& this.activate(targets[i])
}
}
ScrollSpy.prototype.activate = function (target) {
this.activeTarget = target
this.clear()
var selector = this.selector +
'[data-target="' + target + '"],' +
this.selector + '[href="' + target + '"]'
var active = $(selector)
.parents('li')
.addClass('active')
if (active.parent('.dropdown-menu').length) {
active = active
.closest('li.dropdown')
.addClass('active')
}
active.trigger('activate.bs.scrollspy')
}
ScrollSpy.prototype.clear = function () {
$(this.selector)
.parentsUntil(this.options.target, '.active')
.removeClass('active')
}
// SCROLLSPY PLUGIN DEFINITION
// ===========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.scrollspy')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.scrollspy', (data = new ScrollSpy(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.scrollspy
$.fn.scrollspy = Plugin
$.fn.scrollspy.Constructor = ScrollSpy
// SCROLLSPY NO CONFLICT
// =====================
$.fn.scrollspy.noConflict = function () {
$.fn.scrollspy = old
return this
}
// SCROLLSPY DATA-API
// ==================
$(window).on('load.bs.scrollspy.data-api', function () {
$('[data-spy="scroll"]').each(function () {
var $spy = $(this)
Plugin.call($spy, $spy.data())
})
})
}(jQuery);
/* ========================================================================
* Bootstrap: tab.js v3.3.5
* http://getbootstrap.com/javascript/#tabs
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// TAB CLASS DEFINITION
// ====================
var Tab = function (element) {
// jscs:disable requireDollarBeforejQueryAssignment
this.element = $(element)
// jscs:enable requireDollarBeforejQueryAssignment
}
Tab.VERSION = '3.3.5'
Tab.TRANSITION_DURATION = 150
Tab.prototype.show = function () {
var $this = this.element
var $ul = $this.closest('ul:not(.dropdown-menu)')
var selector = $this.data('target')
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
if ($this.parent('li').hasClass('active')) return
var $previous = $ul.find('.active:last a')
var hideEvent = $.Event('hide.bs.tab', {
relatedTarget: $this[0]
})
var showEvent = $.Event('show.bs.tab', {
relatedTarget: $previous[0]
})
$previous.trigger(hideEvent)
$this.trigger(showEvent)
if (showEvent.isDefaultPrevented() || hideEvent.isDefaultPrevented()) return
var $target = $(selector)
this.activate($this.closest('li'), $ul)
this.activate($target, $target.parent(), function () {
$previous.trigger({
type: 'hidden.bs.tab',
relatedTarget: $this[0]
})
$this.trigger({
type: 'shown.bs.tab',
relatedTarget: $previous[0]
})
})
}
Tab.prototype.activate = function (element, container, callback) {
var $active = container.find('> .active')
var transition = callback
&& $.support.transition
&& ($active.length && $active.hasClass('fade') || !!container.find('> .fade').length)
function next() {
$active
.removeClass('active')
.find('> .dropdown-menu > .active')
.removeClass('active')
.end()
.find('[data-toggle="tab"]')
.attr('aria-expanded', false)
element
.addClass('active')
.find('[data-toggle="tab"]')
.attr('aria-expanded', true)
if (transition) {
element[0].offsetWidth // reflow for transition
element.addClass('in')
} else {
element.removeClass('fade')
}
if (element.parent('.dropdown-menu').length) {
element
.closest('li.dropdown')
.addClass('active')
.end()
.find('[data-toggle="tab"]')
.attr('aria-expanded', true)
}
callback && callback()
}
$active.length && transition ?
$active
.one('bsTransitionEnd', next)
.emulateTransitionEnd(Tab.TRANSITION_DURATION) :
next()
$active.removeClass('in')
}
// TAB PLUGIN DEFINITION
// =====================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.tab')
if (!data) $this.data('bs.tab', (data = new Tab(this)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.tab
$.fn.tab = Plugin
$.fn.tab.Constructor = Tab
// TAB NO CONFLICT
// ===============
$.fn.tab.noConflict = function () {
$.fn.tab = old
return this
}
// TAB DATA-API
// ============
var clickHandler = function (e) {
e.preventDefault()
Plugin.call($(this), 'show')
}
$(document)
.on('click.bs.tab.data-api', '[data-toggle="tab"]', clickHandler)
.on('click.bs.tab.data-api', '[data-toggle="pill"]', clickHandler)
}(jQuery);
/* ========================================================================
* Bootstrap: affix.js v3.3.5
* http://getbootstrap.com/javascript/#affix
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// AFFIX CLASS DEFINITION
// ======================
var Affix = function (element, options) {
this.options = $.extend({}, Affix.DEFAULTS, options)
this.$target = $(this.options.target)
.on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this))
.on('click.bs.affix.data-api', $.proxy(this.checkPositionWithEventLoop, this))
this.$element = $(element)
this.affixed = null
this.unpin = null
this.pinnedOffset = null
this.checkPosition()
}
Affix.VERSION = '3.3.5'
Affix.RESET = 'affix affix-top affix-bottom'
Affix.DEFAULTS = {
offset: 0,
target: window
}
Affix.prototype.getState = function (scrollHeight, height, offsetTop, offsetBottom) {
var scrollTop = this.$target.scrollTop()
var position = this.$element.offset()
var targetHeight = this.$target.height()
if (offsetTop != null && this.affixed == 'top') return scrollTop < offsetTop ? 'top' : false
if (this.affixed == 'bottom') {
if (offsetTop != null) return (scrollTop + this.unpin <= position.top) ? false : 'bottom'
return (scrollTop + targetHeight <= scrollHeight - offsetBottom) ? false : 'bottom'
}
var initializing = this.affixed == null
var colliderTop = initializing ? scrollTop : position.top
var colliderHeight = initializing ? targetHeight : height
if (offsetTop != null && scrollTop <= offsetTop) return 'top'
if (offsetBottom != null && (colliderTop + colliderHeight >= scrollHeight - offsetBottom)) return 'bottom'
return false
}
Affix.prototype.getPinnedOffset = function () {
if (this.pinnedOffset) return this.pinnedOffset
this.$element.removeClass(Affix.RESET).addClass('affix')
var scrollTop = this.$target.scrollTop()
var position = this.$element.offset()
return (this.pinnedOffset = position.top - scrollTop)
}
Affix.prototype.checkPositionWithEventLoop = function () {
setTimeout($.proxy(this.checkPosition, this), 1)
}
Affix.prototype.checkPosition = function () {
if (!this.$element.is(':visible')) return
var height = this.$element.height()
var offset = this.options.offset
var offsetTop = offset.top
var offsetBottom = offset.bottom
var scrollHeight = Math.max($(document).height(), $(document.body).height())
if (typeof offset != 'object') offsetBottom = offsetTop = offset
if (typeof offsetTop == 'function') offsetTop = offset.top(this.$element)
if (typeof offsetBottom == 'function') offsetBottom = offset.bottom(this.$element)
var affix = this.getState(scrollHeight, height, offsetTop, offsetBottom)
if (this.affixed != affix) {
if (this.unpin != null) this.$element.css('top', '')
var affixType = 'affix' + (affix ? '-' + affix : '')
var e = $.Event(affixType + '.bs.affix')
this.$element.trigger(e)
if (e.isDefaultPrevented()) return
this.affixed = affix
this.unpin = affix == 'bottom' ? this.getPinnedOffset() : null
this.$element
.removeClass(Affix.RESET)
.addClass(affixType)
.trigger(affixType.replace('affix', 'affixed') + '.bs.affix')
}
if (affix == 'bottom') {
this.$element.offset({
top: scrollHeight - height - offsetBottom
})
}
}
// AFFIX PLUGIN DEFINITION
// =======================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.affix')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.affix', (data = new Affix(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.affix
$.fn.affix = Plugin
$.fn.affix.Constructor = Affix
// AFFIX NO CONFLICT
// =================
$.fn.affix.noConflict = function () {
$.fn.affix = old
return this
}
// AFFIX DATA-API
// ==============
$(window).on('load', function () {
$('[data-spy="affix"]').each(function () {
var $spy = $(this)
var data = $spy.data()
data.offset = data.offset || {}
if (data.offsetBottom != null) data.offset.bottom = data.offsetBottom
if (data.offsetTop != null) data.offset.top = data.offsetTop
Plugin.call($spy, data)
})
})
}(jQuery);
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const wildemitter = require("wildemitter");
const ApiBase_1 = require("../ApiBase");
/**
* AddressBook api implementation.
*/
class AddressBook {
/**
* AddressBook api implementation.
*
* @param {Object} addressBookOptions A collection of options.
*
* @example
* options = {
* debug: true,
* domainURIPath: "https://api-a32.nice-incontact.com/inContactAPI",
* baseURIPath: "/services/v15.0/",
* authorization: "Bearer [Token Value]",
* timeout: 10000, // default is '0' (0 seconds timeout)
* }
*/
constructor(addressBookOptions) {
this.addressBookOptions = addressBookOptions;
// local.
let self = this;
let parent = addressBookOptions.parent;
let uniqueID = "Admin.AddressBook.";
let item;
let options = addressBookOptions || {};
let config = this.config = {
debug: false,
domainURIPath: "https://api-a32.nice-incontact.com/inContactAPI",
baseURIPath: "/services/v15.0/",
authorization: "Bearer [Token Value]",
timeout: 0
};
// Assign global.
this.parent = parent;
this.logger = parent.logger;
this.uniqueID = uniqueID;
// set our config from options
for (item in options) {
if (options.hasOwnProperty(item)) {
this.config[item] = options[item];
}
}
// Call WildEmitter constructor.
wildemitter.mixin(AddressBook);
// Create the request instance.
this.apirequest = new ApiBase_1.ApiRequest(this.config);
}
/**
* Get the address book list.
*
* @param {Object} requestOptions A collection of request options.
*
* @example
* options = {
* timeout: 10000, // default is '0' (0 seconds timeout),
* cancelToken: new CancelToken(function (cancel) {}) // 'cancelToken' specifies a cancel token that can be used to cancel the request (see Cancellation section below for details)
*
* // 'params' are the URL parameters to be sent with the request
* // Must be a plain object or a URLSearchParams object
* params: { ID: 12345 },
*
* // 'data' is the data to be sent as the request body.
* data: { ID: 'Unique' },
* }
*/
getAsync(requestOptions) {
// Create local refs.
let localExecute = 'Get the address book list';
let localUniqueID = this.uniqueID + "getAsync";
let localUrl = 'address-books';
let localTimeout = this.config.timeout;
// Assign the request options.
let options = requestOptions || {};
let requestConfig = {
url: localUrl,
method: 'GET',
baseURL: this.config.domainURIPath + this.config.baseURIPath,
headers: {
'Authorization': this.config.authorization,
'Content-Type': 'application/x-www-form-urlencoded'
},
timeout: localTimeout
};
// Execute the request.
this.apirequest.request(localExecute, localUniqueID, requestConfig, options);
}
/**
* Create the address book list.
*
* @param {Object} requestOptions A collection of request options.
*
* @example
* options = {
* timeout: 10000, // default is '0' (0 seconds timeout),
* cancelToken: new CancelToken(function (cancel) {}) // 'cancelToken' specifies a cancel token that can be used to cancel the request (see Cancellation section below for details)
*
* // 'params' are the URL parameters to be sent with the request
* // Must be a plain object or a URLSearchParams object
* params: { ID: 12345 },
*
* // 'data' is the data to be sent as the request body.
* data: { ID: 'Unique' },
* }
*/
createAsync(requestOptions) {
// Create local refs.
let localExecute = 'Create the address book list';
let localUniqueID = this.uniqueID + "createAsync";
let localUrl = 'address-books';
let localTimeout = this.config.timeout;
// Assign the request options.
let options = requestOptions || {};
let requestConfig = {
url: localUrl,
method: 'POST',
baseURL: this.config.domainURIPath + this.config.baseURIPath,
headers: {
'Authorization': this.config.authorization,
'Content-Type': 'application/json'
},
timeout: localTimeout
};
// Execute the request.
this.apirequest.request(localExecute, localUniqueID, requestConfig, options);
}
/**
* Delete the address book list.
*
* @param {number} addressBookId The address book id.
* @param {Object} requestOptions A collection of request options.
*
* @example
* options = {
* timeout: 10000, // default is '0' (0 seconds timeout),
* cancelToken: new CancelToken(function (cancel) {}) // 'cancelToken' specifies a cancel token that can be used to cancel the request (see Cancellation section below for details)
*
* // 'params' are the URL parameters to be sent with the request
* // Must be a plain object or a URLSearchParams object
* params: { ID: 12345 },
*
* // 'data' is the data to be sent as the request body.
* data: { ID: 'Unique' },
* }
*/
deleteAsync(addressBookId, requestOptions) {
// Create local refs.
let localExecute = 'Delete the address book list';
let localUniqueID = this.uniqueID + "deleteAsync";
let localUrl = 'address-books/' + addressBookId.toString();
let localTimeout = this.config.timeout;
// Assign the request options.
let options = requestOptions || {};
let requestConfig = {
url: localUrl,
method: 'DELETE',
baseURL: this.config.domainURIPath + this.config.baseURIPath,
headers: {
'Authorization': this.config.authorization,
'Content-Type': 'application/x-www-form-urlencoded'
},
timeout: localTimeout
};
// Execute the request.
this.apirequest.request(localExecute, localUniqueID, requestConfig, options);
}
/**
* Assign Entities to an address book.
*
* @param {number} addressBookId The address book id.
* @param {Object} requestOptions A collection of request options.
*
* @example
* options = {
* timeout: 10000, // default is '0' (0 seconds timeout),
* cancelToken: new CancelToken(function (cancel) {}) // 'cancelToken' specifies a cancel token that can be used to cancel the request (see Cancellation section below for details)
*
* // 'params' are the URL parameters to be sent with the request
* // Must be a plain object or a URLSearchParams object
* params: { ID: 12345 },
*
* // 'data' is the data to be sent as the request body.
* data: { ID: 'Unique' },
* }
*/
assignEntitiesAsync(addressBookId, requestOptions) {
// Create local refs.
let localExecute = 'Assign Entities to an address book';
let localUniqueID = this.uniqueID + "assignEntitiesAsync";
let localUrl = 'address-books/' + addressBookId.toString() + '/assignment';
let localTimeout = this.config.timeout;
// Assign the request options.
let options = requestOptions || {};
let requestConfig = {
url: localUrl,
method: 'POST',
baseURL: this.config.domainURIPath + this.config.baseURIPath,
headers: {
'Authorization': this.config.authorization,
'Content-Type': 'application/x-www-form-urlencoded'
},
timeout: localTimeout
};
// Execute the request.
this.apirequest.request(localExecute, localUniqueID, requestConfig, options);
}
/**
* Get entries for a dynamic address book.
*
* @param {number} addressBookId The address book id.
* @param {Object} requestOptions A collection of request options.
*
* @example
* options = {
* timeout: 10000, // default is '0' (0 seconds timeout),
* cancelToken: new CancelToken(function (cancel) {}) // 'cancelToken' specifies a cancel token that can be used to cancel the request (see Cancellation section below for details)
*
* // 'params' are the URL parameters to be sent with the request
* // Must be a plain object or a URLSearchParams object
* params: { ID: 12345 },
*
* // 'data' is the data to be sent as the request body.
* data: { ID: 'Unique' },
* }
*/
dynamicEntitiesAsync(addressBookId, requestOptions) {
// Create local refs.
let localExecute = 'Get entries for a dynamic address book';
let localUniqueID = this.uniqueID + "dynamicEntitiesAsync";
let localUrl = 'address-books/' + addressBookId.toString() + '/dynamic-entries';
let localTimeout = this.config.timeout;
// Assign the request options.
let options = requestOptions || {};
let requestConfig = {
url: localUrl,
method: 'GET',
baseURL: this.config.domainURIPath + this.config.baseURIPath,
headers: {
'Authorization': this.config.authorization,
'Content-Type': 'application/x-www-form-urlencoded'
},
timeout: localTimeout
};
// Execute the request.
this.apirequest.request(localExecute, localUniqueID, requestConfig, options);
}
/**
* Create entries for a dynamic address book.
*
* @param {number} addressBookId The address book id.
* @param {Object} requestOptions A collection of request options.
*
* @example
* options = {
* timeout: 10000, // default is '0' (0 seconds timeout),
* cancelToken: new CancelToken(function (cancel) {}) // 'cancelToken' specifies a cancel token that can be used to cancel the request (see Cancellation section below for details)
*
* // 'params' are the URL parameters to be sent with the request
* // Must be a plain object or a URLSearchParams object
* params: { ID: 12345 },
*
* // 'data' is the data to be sent as the request body.
* data: { ID: 'Unique' },
* }
*/
createDynamicEntitiesAsync(addressBookId, requestOptions) {
// Create local refs.
let localExecute = 'Create entries for a dynamic address book';
let localUniqueID = this.uniqueID + "createDynamicEntitiesAsync";
let localUrl = 'address-books/' + addressBookId.toString() + '/dynamic-entries';
let localTimeout = this.config.timeout;
// Assign the request options.
let options = requestOptions || {};
let requestConfig = {
url: localUrl,
method: 'PUT',
baseURL: this.config.domainURIPath + this.config.baseURIPath,
headers: {
'Authorization': this.config.authorization,
'Content-Type': 'application/x-www-form-urlencoded'
},
timeout: localTimeout
};
// Execute the request.
this.apirequest.request(localExecute, localUniqueID, requestConfig, options);
}
/**
* Delete a dynamic address book entry.
*
* @param {number} addressBookId The address book id.
* @param {string} externalId The address book entry external id.
* @param {Object} requestOptions A collection of request options.
*
* @example
* options = {
* timeout: 10000, // default is '0' (0 seconds timeout),
* cancelToken: new CancelToken(function (cancel) {}) // 'cancelToken' specifies a cancel token that can be used to cancel the request (see Cancellation section below for details)
*
* // 'params' are the URL parameters to be sent with the request
* // Must be a plain object or a URLSearchParams object
* params: { ID: 12345 },
*
* // 'data' is the data to be sent as the request body.
* data: { ID: 'Unique' },
* }
*/
deleteDynamicEntitiesAsync(addressBookId, externalId, requestOptions) {
// Create local refs.
let localExecute = 'Delete a dynamic address book entry';
let localUniqueID = this.uniqueID + "deleteDynamicEntitiesAsync";
let localUrl = 'address-books/' + addressBookId.toString() + '/dynamic-entries/' + externalId;
let localTimeout = this.config.timeout;
// Assign the request options.
let options = requestOptions || {};
let requestConfig = {
url: localUrl,
method: 'DELETE',
baseURL: this.config.domainURIPath + this.config.baseURIPath,
headers: {
'Authorization': this.config.authorization,
'Content-Type': 'application/x-www-form-urlencoded'
},
timeout: localTimeout
};
// Execute the request.
this.apirequest.request(localExecute, localUniqueID, requestConfig, options);
}
/**
* Lists all standard address book entries for an address book.
*
* @param {number} addressBookId The address book id.
* @param {Object} requestOptions A collection of request options.
*
* @example
* options = {
* timeout: 10000, // default is '0' (0 seconds timeout),
* cancelToken: new CancelToken(function (cancel) {}) // 'cancelToken' specifies a cancel token that can be used to cancel the request (see Cancellation section below for details)
*
* // 'params' are the URL parameters to be sent with the request
* // Must be a plain object or a URLSearchParams object
* params: { ID: 12345 },
*
* // 'data' is the data to be sent as the request body.
* data: { ID: 'Unique' },
* }
*/
standardEntitiesAsync(addressBookId, requestOptions) {
// Create local refs.
let localExecute = 'Lists all standard address book entries for an address book';
let localUniqueID = this.uniqueID + "standardEntitiesAsync";
let localUrl = 'address-books/' + addressBookId.toString() + '/entries';
let localTimeout = this.config.timeout;
// Assign the request options.
let options = requestOptions || {};
let requestConfig = {
url: localUrl,
method: 'GET',
baseURL: this.config.domainURIPath + this.config.baseURIPath,
headers: {
'Authorization': this.config.authorization,
'Content-Type': 'application/x-www-form-urlencoded'
},
timeout: localTimeout
};
// Execute the request.
this.apirequest.request(localExecute, localUniqueID, requestConfig, options);
}
/**
* Create standard address book entries.
*
* @param {number} addressBookId The address book id.
* @param {Object} requestOptions A collection of request options.
*
* @example
* options = {
* timeout: 10000, // default is '0' (0 seconds timeout),
* cancelToken: new CancelToken(function (cancel) {}) // 'cancelToken' specifies a cancel token that can be used to cancel the request (see Cancellation section below for details)
*
* // 'params' are the URL parameters to be sent with the request
* // Must be a plain object or a URLSearchParams object
* params: { ID: 12345 },
*
* // 'data' is the data to be sent as the request body.
* data: { ID: 'Unique' },
* }
*/
createStandardEntitiesAsync(addressBookId, requestOptions) {
// Create local refs.
let localExecute = 'Create standard address book entries';
let localUniqueID = this.uniqueID + "createStandardEntitiesAsync";
let localUrl = 'address-books/' + addressBookId.toString() + '/entries';
let localTimeout = this.config.timeout;
// Assign the request options.
let options = requestOptions || {};
let requestConfig = {
url: localUrl,
method: 'POST',
baseURL: this.config.domainURIPath + this.config.baseURIPath,
headers: {
'Authorization': this.config.authorization,
'Content-Type': 'application/x-www-form-urlencoded'
},
timeout: localTimeout
};
// Execute the request.
this.apirequest.request(localExecute, localUniqueID, requestConfig, options);
}
/**
* Update standard address book entries.
*
* @param {number} addressBookId The address book id.
* @param {Object} requestOptions A collection of request options.
*
* @example
* options = {
* timeout: 10000, // default is '0' (0 seconds timeout),
* cancelToken: new CancelToken(function (cancel) {}) // 'cancelToken' specifies a cancel token that can be used to cancel the request (see Cancellation section below for details)
*
* // 'params' are the URL parameters to be sent with the request
* // Must be a plain object or a URLSearchParams object
* params: { ID: 12345 },
*
* // 'data' is the data to be sent as the request body.
* data: { ID: 'Unique' },
* }
*/
updateStandardEntitiesAsync(addressBookId, requestOptions) {
// Create local refs.
let localExecute = 'Update standard address book entries';
let localUniqueID = this.uniqueID + "updateStandardEntitiesAsync";
let localUrl = 'address-books/' + addressBookId.toString() + '/entries';
let localTimeout = this.config.timeout;
// Assign the request options.
let options = requestOptions || {};
let requestConfig = {
url: localUrl,
method: 'PUT',
baseURL: this.config.domainURIPath + this.config.baseURIPath,
headers: {
'Authorization': this.config.authorization,
'Content-Type': 'application/x-www-form-urlencoded'
},
timeout: localTimeout
};
// Execute the request.
this.apirequest.request(localExecute, localUniqueID, requestConfig, options);
}
/**
* Delete a standard address book entry.
*
* @param {number} addressBookId The address book id.
* @param {string} addressBookEntryId The address book entry id to delete.
* @param {Object} requestOptions A collection of request options.
*
* @example
* options = {
* timeout: 10000, // default is '0' (0 seconds timeout),
* cancelToken: new CancelToken(function (cancel) {}) // 'cancelToken' specifies a cancel token that can be used to cancel the request (see Cancellation section below for details)
*
* // 'params' are the URL parameters to be sent with the request
* // Must be a plain object or a URLSearchParams object
* params: { ID: 12345 },
*
* // 'data' is the data to be sent as the request body.
* data: { ID: 'Unique' },
* }
*/
deleteStandardEntitiesAsync(addressBookId, addressBookEntryId, requestOptions) {
// Create local refs.
let localExecute = 'Delete a standard address book entry';
let localUniqueID = this.uniqueID + "deleteStandardEntitiesAsync";
let localUrl = 'address-books/' + addressBookId.toString() + '/entries/' + addressBookEntryId;
let localTimeout = this.config.timeout;
// Assign the request options.
let options = requestOptions || {};
let requestConfig = {
url: localUrl,
method: 'DELETE',
baseURL: this.config.domainURIPath + this.config.baseURIPath,
headers: {
'Authorization': this.config.authorization,
'Content-Type': 'application/x-www-form-urlencoded'
},
timeout: localTimeout
};
// Execute the request.
this.apirequest.request(localExecute, localUniqueID, requestConfig, options);
}
/**
* Get address books for an agent.
*
* @param {number} agentId The agent id.
* @param {Object} requestOptions A collection of request options.
*
* @example
* options = {
* timeout: 10000, // default is '0' (0 seconds timeout),
* cancelToken: new CancelToken(function (cancel) {}) // 'cancelToken' specifies a cancel token that can be used to cancel the request (see Cancellation section below for details)
*
* // 'params' are the URL parameters to be sent with the request
* // Must be a plain object or a URLSearchParams object
* params: { ID: 12345 },
*
* // 'data' is the data to be sent as the request body.
* data: { ID: 'Unique' },
* }
*/
getAgentsAsync(agentId, requestOptions) {
// Create local refs.
let localExecute = 'Get address books for an agent';
let localUniqueID = this.uniqueID + "getAgentsAsync";
let localUrl = 'agents/' + agentId.toString() + '/address-books';
let localTimeout = this.config.timeout;
// Assign the request options.
let options = requestOptions || {};
let requestConfig = {
url: localUrl,
method: 'GET',
baseURL: this.config.domainURIPath + this.config.baseURIPath,
headers: {
'Authorization': this.config.authorization,
'Content-Type': 'application/x-www-form-urlencoded'
},
timeout: localTimeout
};
// Execute the request.
this.apirequest.request(localExecute, localUniqueID, requestConfig, options);
}
/**
* Get address books for a campaign.
*
* @param {number} campaignId The campaign id.
* @param {Object} requestOptions A collection of request options.
*
* @example
* options = {
* timeout: 10000, // default is '0' (0 seconds timeout),
* cancelToken: new CancelToken(function (cancel) {}) // 'cancelToken' specifies a cancel token that can be used to cancel the request (see Cancellation section below for details)
*
* // 'params' are the URL parameters to be sent with the request
* // Must be a plain object or a URLSearchParams object
* params: { ID: 12345 },
*
* // 'data' is the data to be sent as the request body.
* data: { ID: 'Unique' },
* }
*/
getCampaignsAsync(campaignId, requestOptions) {
// Create local refs.
let localExecute = 'Get address books for a campaign';
let localUniqueID = this.uniqueID + "getCampaignsAsync";
let localUrl = 'campaigns/' + campaignId.toString() + '/address-books';
let localTimeout = this.config.timeout;
// Assign the request options.
let options = requestOptions || {};
let requestConfig = {
url: localUrl,
method: 'GET',
baseURL: this.config.domainURIPath + this.config.baseURIPath,
headers: {
'Authorization': this.config.authorization,
'Content-Type': 'application/x-www-form-urlencoded'
},
timeout: localTimeout
};
// Execute the request.
this.apirequest.request(localExecute, localUniqueID, requestConfig, options);
}
/**
* Get address books for a skill.
*
* @param {number} skillId The skill id.
* @param {Object} requestOptions A collection of request options.
*
* @example
* options = {
* timeout: 10000, // default is '0' (0 seconds timeout),
* cancelToken: new CancelToken(function (cancel) {}) // 'cancelToken' specifies a cancel token that can be used to cancel the request (see Cancellation section below for details)
*
* // 'params' are the URL parameters to be sent with the request
* // Must be a plain object or a URLSearchParams object
* params: { ID: 12345 },
*
* // 'data' is the data to be sent as the request body.
* data: { ID: 'Unique' },
* }
*/
getSkillsAsync(skillId, requestOptions) {
// Create local refs.
let localExecute = 'Get address books for a skill';
let localUniqueID = this.uniqueID + "getSkillsAsync";
let localUrl = 'skills/' + skillId.toString() + '/address-books';
let localTimeout = this.config.timeout;
// Assign the request options.
let options = requestOptions || {};
let requestConfig = {
url: localUrl,
method: 'GET',
baseURL: this.config.domainURIPath + this.config.baseURIPath,
headers: {
'Authorization': this.config.authorization,
'Content-Type': 'application/x-www-form-urlencoded'
},
timeout: localTimeout
};
// Execute the request.
this.apirequest.request(localExecute, localUniqueID, requestConfig, options);
}
/**
* Get address books for a team.
*
* @param {number} teamId The team id.
* @param {Object} requestOptions A collection of request options.
*
* @example
* options = {
* timeout: 10000, // default is '0' (0 seconds timeout),
* cancelToken: new CancelToken(function (cancel) {}) // 'cancelToken' specifies a cancel token that can be used to cancel the request (see Cancellation section below for details)
*
* // 'params' are the URL parameters to be sent with the request
* // Must be a plain object or a URLSearchParams object
* params: { ID: 12345 },
*
* // 'data' is the data to be sent as the request body.
* data: { ID: 'Unique' },
* }
*/
getTeamsAsync(teamId, requestOptions) {
// Create local refs.
let localExecute = 'Get address books for a team';
let localUniqueID = this.uniqueID + "getTeamsAsync";
let localUrl = 'teams/' + teamId.toString() + '/address-books';
let localTimeout = this.config.timeout;
// Assign the request options.
let options = requestOptions || {};
let requestConfig = {
url: localUrl,
method: 'GET',
baseURL: this.config.domainURIPath + this.config.baseURIPath,
headers: {
'Authorization': this.config.authorization,
'Content-Type': 'application/x-www-form-urlencoded'
},
timeout: localTimeout
};
// Execute the request.
this.apirequest.request(localExecute, localUniqueID, requestConfig, options);
}
}
exports.AddressBook = AddressBook;
|
var assert = require('better-assert')
var Evaluator = require('..')
it('should maintain scope between iterations', function(){
var ctx = new Evaluator(__dirname + '/path')
assert(ctx.eval('var a=1;a') == 1)
assert(ctx.eval('a') == 1)
})
it('should protect against variable overriding', function(){
var ctx = new Evaluator(__dirname + '/path')
assert(ctx.eval('var eval=1;eval') == 1)
try {
assert(ctx.eval('eval') == 1)
} catch (e) {
if (/number is not a function/.test(e.message)) {
throw new Error('eval has been overridden')
} else {
throw e
}
}
})
it('should provide a working `require`', function(){
var ctx = new Evaluator(__dirname + '/path')
assert(ctx.eval('require("..")') == Evaluator)
})
|
/************************************************************************
## Signs Module
The Signs Module can be used by plugin authors to create interactive
signs - that is - signs which display a list of choices which can be
changed by interacting (right-clicking) with the sign.
### signs.menu() function
This function is used to construct a new interactive menu on top of an
existing sign in the game world.
#### Parameters
* Label : A string which will be displayed in the topmost line of the
sign. This label is not interactive.
* options : An array of strings which can be selected on the sign by
right-clicking/interacting.
* callback : A function which will be called whenever a player
interacts (changes selection) on a sign. This callback in turn
takes as its parameter, an object with the following properties...
* player : The player who interacted with the sign.
* sign : The [org.bukkit.block.Sign][buksign] which the player interacted with.
* text : The text for the currently selected option on the sign.
* number : The index of the currently selected option on the sign.
* selectedIndex : optional: A number (starting at 0) indicating which
of the options should be selected by default. 0 is the default.
#### Returns
This function does not itself do much. It does however return a
function which when invoked with a given
[org.bukkit.block.Sign][buksign] object, will convert that sign into
an interactive sign.
#### Example: Create a sign which changes the time of day.
##### plugins/signs/time-of-day.js
```javascript
var utils = require('utils'),
signs = require('signs');
var onTimeChoice = function(event){
var selectedIndex = event.number;
// convert to Minecraft time 0 = Dawn, 6000 = midday, 12000 = dusk, 18000 = midnight
var time = selectedIndex * 6000;
event.player.location.world.setTime(time);
};
// signs.menu returns a function which can be called for one or more signs in the game.
var convertToTimeMenu = signs.menu('Time of Day',
['Dawn', 'Midday', 'Dusk', 'Midnight'],
onTimeChoice);
exports.time_sign = function( player ){
var sign = signs.getTargetedBy(player);
if ( !sign ) {
throw new Error('You must look at a sign');
}
convertToTimeMenu(sign);
};
```
To use the above function at the in-game prompt, look at an existing
sign and type...
/js time_sign(self);
... and the sign you're looking at will become an interactive sign
which changes the time each time you interact (right-click) with it.
### signs.getTargetedBy() function
This function takes a [org.bukkit.entity.LivingEntity][bukle] as a
parameter and returns a [org.bukkit.block.Sign][buksign] object which
the entity has targeted. It is a utility function for use by plugin authors.
#### Example
```javascript
var signs = require('signs'),
utils = require('utils');
var player = utils.player('tom1234');
var sign = signs.getTargetedBy( player );
if ( !sign ) {
player.sendMessage('Not looking at a sign');
}
```
[buksign]: http://jd.bukkit.org/dev/apidocs/org/bukkit/block/Sign.html
***/
var utils = require('utils');
var menu = require('./menu');
// include all menu exports
for ( var i in menu ) {
exports[i] = menu[i];
}
exports.getTargetedBy = function( livingEntity ) {
var location = utils.getMousePos( livingEntity );
if ( !location ) {
return null;
}
var state = location.block.state;
if ( ! (state || state.setLine) ) {
return null;
}
return state;
};
|
import { get } from '@ember/object';
import { typeOf } from '@ember/utils';
const DEFAULTS = {
defaultUUID: true
};
/**
Ember CLI UUID's configuration object (borrowed from Ember Simple Auth).
To change any of these values, set them on the application's environment
object, e.g.:
```js
// config/environment.js
ENV['ember-cli-uuid'] = {
defaultUUID: false
};
```
@class Configuration
@extends Object
@module ember-cli-uuid/configuration
@public
*/
export default {
/**
If `defaultUUID` is set to `true`, all Ember-Data generated records will
have an automated UUID v4 set as their primary key.
@property defaultUUID
@readOnly
@static
@type Boolean
@default false
@public
*/
defaultUUID: DEFAULTS.defaultUUID,
load(config) {
for (let property in this) {
if (
Object.prototype.hasOwnProperty.call(this, property)
&& typeOf(this[property]) !== 'function'
) {
const value = get(config, property);
this[property] = value === undefined ? DEFAULTS[property] : value;
}
}
}
};
|
var len = 0;
setTimeout(function() {
len = 10;
}, 0);
setTimeout(function() {
len = 20;
}, 100);
console.log(len);
setTimeout(function() {
console.log(len);
}, 0);
|
/* Copyright (c) 2011 Srikanth Raju, http://srikanthraju.in/scrobbleware
* Released under MIT license. See LICENSE file for more information */
function save_func() {
localStorage.username = document.getElementById("username").value;
localStorage.password = document.getElementById("password").value;
chrome.extension.getBackgroundPage().window.location.reload();
}
function clear_func() {
localStorage.clear();
chrome.extension.getBackgroundPage().window.location.reload();
document.getElementById("username").removeAttribute("disabled");
document.getElementById("password").removeAttribute("disabled");
document.getElementById("submit").removeAttribute("disabled");
document.getElementById("status").style.display='none';
}
function update( msg ) {
document.getElementById("status").innerHTML=msg;
}
function load() {
if (localStorage.username != null) {
update("User set to " + localStorage.username + ". "
+ ( localStorage.auth_success == 1 ? "Auth success. Hit Clear to unregister" : "Auth failed. Try Again" ) );
}
if( localStorage.auth_success == 1 )
{
document.getElementById("username").setAttribute("disabled","disabled");
document.getElementById("password").setAttribute("disabled","disabled");
document.getElementById("submit").setAttribute("disabled","disabled");
document.getElementById("status").style.display='';
}
else if( localStorage.auth_success == 2 )
{
localStorage.clear();
document.getElementById("status").style.display='';
}
else
{
document.getElementById("status").style.display='none';
}
}
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
load();
sendResponse({});
}
);
|
'use strict';
describe('Directive: rdPagination', function () {
beforeEach(module('angularjsRundownApp'));
var element;
// it('should make hidden element visible', inject(function ($rootScope, $compile) {
// element = angular.element('<rd-pagination></rd-pagination>');
// element = $compile(element)($rootScope);
// expect(element.text()).toBe('this is the rdPagination directive');
// }));
});
|
"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 _templateObject = _taggedTemplateLiteral(["\n position: relative;\n display: inline-block;\n width: inherit;\n\n &.active {\n .ra-tooltip {\n display: block;\n }\n }\n"], ["\n position: relative;\n display: inline-block;\n width: inherit;\n\n &.active {\n .ra-tooltip {\n display: block;\n }\n }\n"]);
var _react = require("react");
var _react2 = _interopRequireDefault(_react);
var _propTypes = require("prop-types");
var _propTypes2 = _interopRequireDefault(_propTypes);
var _tooltipContent = require("./tooltip-content");
var _tooltipContent2 = _interopRequireDefault(_tooltipContent);
var _styledComponents = require("styled-components");
var _styledComponents2 = _interopRequireDefault(_styledComponents);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _taggedTemplateLiteral(strings, raw) { return Object.freeze(Object.defineProperties(strings, { raw: { value: Object.freeze(raw) } })); }
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 tooltipIdCounter = 0;
var ReactARIAToolTip = function (_React$Component) {
_inherits(ReactARIAToolTip, _React$Component);
function ReactARIAToolTip(props, context) {
_classCallCheck(this, ReactARIAToolTip);
var _this = _possibleConstructorReturn(this, (ReactARIAToolTip.__proto__ || Object.getPrototypeOf(ReactARIAToolTip)).call(this, props, context));
_this.handleWindowClick = function (e) {
if (_this.state.active) {
if (_this.node.contains(e.target)) {
return;
}
_this.setState({ active: false });
}
};
_this.state = {
active: false,
direction: props.direction,
duration: props.duration,
id: props.id
};
return _this;
}
_createClass(ReactARIAToolTip, [{
key: "componentDidMount",
value: function componentDidMount() {
var id = this.props.id || this.uniqueID("ra-tooltip-");
this.setState({ id: id });
if (!this.state.duration) {
document.addEventListener("mousedown", this.handleWindowClick, false);
}
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
this.timer && clearTimeout(this.timer);
this.timer = false;
document.removeEventListener("mousedown", this.handleWindowClick, false);
}
}, {
key: "startTimer",
value: function startTimer() {
var _this2 = this;
var duration = this.props.duration;
this.timer = setTimeout(function () {
return _this2.setState({ active: false });
}, duration);
}
}, {
key: "handleClick",
value: function handleClick() {
if (this.props.allowClickOnSelf) {
this.setState({ active: !this.state.active });
} else {
this.setState({ active: true });
if (this.state.duration) {
clearTimeout(this.timer);
this.startTimer();
}
}
}
}, {
key: "handleMouseOver",
value: function handleMouseOver() {
this.setState({ active: true });
}
}, {
key: "handleMouseLeave",
value: function handleMouseLeave() {
this.setState({ active: false });
}
}, {
key: "handleFocus",
value: function handleFocus() {
this.handleClick();
}
// create unique id so multiple tooltips can be used in the same view
}, {
key: "uniqueID",
value: function uniqueID(prefix) {
var id = ++tooltipIdCounter + "";
return prefix ? prefix + id : id;
}
// adds tooltip 'aria-describedby' attribute to child element
}, {
key: "addDescribedBy",
value: function addDescribedBy(tooltipID) {
return _react2.default.Children.map(this.props.children, function (e) {
return _react2.default.cloneElement(e, {
"aria-describedby": tooltipID
});
});
}
}, {
key: "render",
value: function render() {
var _this3 = this;
var _props = this.props,
message = _props.message,
bgcolor = _props.bgcolor,
direction = _props.direction,
className = _props.className;
var active = this.state.active;
var containerClass = "ra-tooltip-wrapper " + className;
containerClass += active ? " active" : "";
var tooltipID = this.state.id;
if (this.props.eventType == "hover") {
return _react2.default.createElement(
"div",
{
onMouseOver: this.handleMouseOver.bind(this),
onMouseLeave: this.handleMouseLeave.bind(this),
role: "tooltip",
id: tooltipID,
onFocus: this.handleFocus.bind(this),
className: containerClass
},
_react2.default.createElement(_tooltipContent2.default, {
message: message,
bgcolor: bgcolor,
direction: direction,
active: active
}),
this.addDescribedBy(tooltipID)
);
}
return _react2.default.createElement(
"div",
{
ref: function ref(node) {
return _this3.node = node;
},
onClick: this.handleClick.bind(this),
role: "tooltip",
className: containerClass
},
_react2.default.createElement(_tooltipContent2.default, {
message: message,
bgcolor: bgcolor,
direction: direction,
active: active
}),
this.addDescribedBy(tooltipID)
);
}
}]);
return ReactARIAToolTip;
}(_react2.default.Component);
ReactARIAToolTip.displayName = "ReactARIAToolTip";
ReactARIAToolTip.defaultProps = {
direction: "top",
duration: 2000,
eventType: "click",
allowClickOnSelf: false,
bgcolor: "#000"
};
ReactARIAToolTip.propTypes = {
message: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.object, _propTypes2.default.element]).isRequired,
direction: _propTypes2.default.string,
duration: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.number, _propTypes2.default.bool]),
children: _propTypes2.default.node,
eventType: _propTypes2.default.oneOf(["hover", "click", "outside"]),
allowClickOnSelf: _propTypes2.default.bool,
id: _propTypes2.default.string,
bgcolor: _propTypes2.default.string
};
exports.default = (0, _styledComponents2.default)(ReactARIAToolTip)(_templateObject);
|
var ssMenu=function(){};ssMenu.templates={buttonReveal:'<span class="navButton"><ss-icon type="menu" scheme="{{scheme}}"></ss-icon>{{label}}</span><nav><content></content></nav><div class="menuCover"></div>'},ssMenu.config={tag:"ss-menu",template:ssMenu.templates.buttonReveal,attributes:["direction","label","scheme"],init:function(a){"right"===a.getAttribute("direction")&&fw("body").addClass("right"),a.find(".navButton").addListener("click",function(){fw("body").toggleClass("menuOpen")})}},sandlestrap.register(ssMenu);
|
this.NesDb = this.NesDb || {};
NesDb[ '1BF9A2D3DB587F309D0E9D0A76FC9CA92530BBD4' ] = {
"$": {
"name": "Shanghai",
"altname": "上海",
"class": "Licensed",
"subclass": "3rd-Party",
"catalog": "SUN-SS9-5300",
"publisher": "Sunsoft",
"developer": "Sunsoft",
"region": "Japan",
"players": "1",
"date": "1987-12-04"
},
"cartridge": [
{
"$": {
"system": "Famicom",
"crc": "B20C1030",
"sha1": "1BF9A2D3DB587F309D0E9D0A76FC9CA92530BBD4",
"dump": "ok",
"dumper": "bootgod",
"datedumped": "2009-02-17"
},
"board": [
{
"$": {
"type": "SUNSOFT-2",
"pcb": "SUNSOFT-3R",
"mapper": "93"
},
"prg": [
{
"$": {
"name": "SUNSOFT-9",
"size": "128k",
"crc": "B20C1030",
"sha1": "1BF9A2D3DB587F309D0E9D0A76FC9CA92530BBD4"
}
}
],
"vram": [
{
"$": {
"size": "8k"
}
}
],
"chip": [
{
"$": {
"type": "Sunsoft-2"
}
}
],
"pad": [
{
"$": {
"h": "1",
"v": "0"
}
}
]
}
]
}
]
};
|
import { mutationTypes } from '../mutation_types';
const types = [
'RESET',
'SET_ERROR',
'SET_RETRIEVED',
'SET_UPDATED',
'SET_VIOLATIONS',
'TOGGLE_LOADING',
];
export default m => mutationTypes(m, 'UPDATE', types);
|
'use strict';
var THREE = require('three');
//
// STL Loader added
//
/**
* @author aleeper / http://adamleeper.com/
* @author mrdoob / http://mrdoob.com/
* @author gero3 / https://github.com/gero3
*
* Description: A THREE loader for STL ASCII files, as created by Solidworks and other CAD programs.
*
* Supports both binary and ASCII encoded files, with automatic detection of type.
*
* Limitations:
* Binary decoding supports "Magics" color format (http://en.wikipedia.org/wiki/STL_(file_format)#Color_in_binary_STL).
* There is perhaps some question as to how valid it is to always assume little-endian-ness.
* ASCII decoding assumes file is UTF-8. Seems to work for the examples...
*
* Usage:
* var loader = new THREE.STLLoader();
* loader.load( './models/stl/slotted_disk.stl', function ( geometry ) {
* scene.add( new THREE.Mesh( geometry ) );
* });
*
* For binary STLs geometry might contain colors for vertices. To use it:
* // use the same code to load STL as above
* if (geometry.hasColors) {
* material = new THREE.MeshPhongMaterial({ opacity: geometry.alpha, vertexColors: THREE.VertexColors });
* } else { .... }
* var mesh = new THREE.Mesh( geometry, material );
*/
THREE.STLLoader = function (manager) {
this.manager = manager !== undefined ? manager : THREE.DefaultLoadingManager;
};
THREE.STLLoader.prototype = {
constructor: THREE.STLLoader,
loadFromUrl: function loadFromUrl(url, onLoad, onProgress, onError) {
var scope = this;
var loader = new THREE.XHRLoader(scope.manager);
loader.setCrossOrigin(this.crossOrigin);
loader.setResponseType('arraybuffer');
loader.load(url, function (text) {
onLoad(scope.parse(text));
}, onProgress, onError);
},
loadFromFile: function loadFromFile(buffer, onLoad) {
var scope = this;
onLoad(scope.parse(buffer));
},
parse: function parse(data) {
var isBinary = function isBinary() {
var expect, face_size, n_faces, reader;
reader = new DataView(binData);
face_size = 32 / 8 * 3 + 32 / 8 * 3 * 3 + 16 / 8;
n_faces = reader.getUint32(80, true);
expect = 80 + 32 / 8 + n_faces * face_size;
if (expect === reader.byteLength) {
return true;
}
// some binary files will have different size from expected,
// checking characters higher than ASCII to confirm is binary
var fileLength = reader.byteLength;
for (var index = 0; index < fileLength; index++) {
if (reader.getUint8(index, false) > 127) {
return true;
}
}
return false;
};
var binData = this.ensureBinary(data);
return isBinary() ? this.parseBinary(binData) : this.parseASCII(this.ensureString(data));
},
parseBinary: function parseBinary(data) {
var reader = new DataView(data);
var faces = reader.getUint32(80, true);
var r,
g,
b,
hasColors = false,
colors;
var defaultR, defaultG, defaultB, alpha;
// process STL header
// check for default color in header ("COLOR=rgba" sequence).
for (var index = 0; index < 80 - 10; index++) {
if (reader.getUint32(index, false) == 0x434f4c4f /*COLO*/ && reader.getUint8(index + 4) == 0x52 /*'R'*/ && reader.getUint8(index + 5) == 0x3d /*'='*/
) {
hasColors = true;
colors = new Float32Array(faces * 3 * 3);
defaultR = reader.getUint8(index + 6) / 255;
defaultG = reader.getUint8(index + 7) / 255;
defaultB = reader.getUint8(index + 8) / 255;
alpha = reader.getUint8(index + 9) / 255;
}
}
var dataOffset = 84;
var faceLength = 12 * 4 + 2;
var offset = 0;
var geometry = new THREE.BufferGeometry();
var vertices = new Float32Array(faces * 3 * 3);
var normals = new Float32Array(faces * 3 * 3);
for (var face = 0; face < faces; face++) {
var start = dataOffset + face * faceLength;
var normalX = reader.getFloat32(start, true);
var normalY = reader.getFloat32(start + 4, true);
var normalZ = reader.getFloat32(start + 8, true);
if (hasColors) {
var packedColor = reader.getUint16(start + 48, true);
if ((packedColor & 0x8000) === 0) {
// facet has its own unique color
r = (packedColor & 0x1f) / 31;
g = (packedColor >> 5 & 0x1f) / 31;
b = (packedColor >> 10 & 0x1f) / 31;
} else {
r = defaultR;
g = defaultG;
b = defaultB;
}
}
for (var i = 1; i <= 3; i++) {
var vertexstart = start + i * 12;
vertices[offset] = reader.getFloat32(vertexstart, true);
vertices[offset + 1] = reader.getFloat32(vertexstart + 4, true);
vertices[offset + 2] = reader.getFloat32(vertexstart + 8, true);
normals[offset] = normalX;
normals[offset + 1] = normalY;
normals[offset + 2] = normalZ;
if (hasColors) {
colors[offset] = r;
colors[offset + 1] = g;
colors[offset + 2] = b;
}
offset += 3;
}
}
geometry.addAttribute('position', new THREE.BufferAttribute(vertices, 3));
geometry.addAttribute('normal', new THREE.BufferAttribute(normals, 3));
if (hasColors) {
geometry.addAttribute('color', new THREE.BufferAttribute(colors, 3));
geometry.hasColors = true;
geometry.alpha = alpha;
}
return geometry;
},
parseASCII: function parseASCII(data) {
var geometry, length, normal, patternFace, patternNormal, patternVertex, result, text;
geometry = new THREE.Geometry();
patternFace = /facet([\s\S]*?)endfacet/g;
while ((result = patternFace.exec(data)) !== null) {
text = result[0];
patternNormal = /normal[\s]+([\-+]?[0-9]+\.?[0-9]*([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+/g;
while ((result = patternNormal.exec(text)) !== null) {
normal = new THREE.Vector3(parseFloat(result[1]), parseFloat(result[3]), parseFloat(result[5]));
}
patternVertex = /vertex[\s]+([\-+]?[0-9]+\.?[0-9]*([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+/g;
while ((result = patternVertex.exec(text)) !== null) {
geometry.vertices.push(new THREE.Vector3(parseFloat(result[1]), parseFloat(result[3]), parseFloat(result[5])));
}
length = geometry.vertices.length;
geometry.faces.push(new THREE.Face3(length - 3, length - 2, length - 1, normal));
}
geometry.computeBoundingBox();
geometry.computeBoundingSphere();
return geometry;
},
ensureString: function ensureString(buf) {
if (typeof buf !== 'string') {
var array_buffer = new Uint8Array(buf);
var str = '';
for (var i = 0; i < buf.byteLength; i++) {
str += String.fromCharCode(array_buffer[i]); // implicitly assumes little-endian
}
return str;
} else {
return buf;
}
},
ensureBinary: function ensureBinary(buf) {
if (typeof buf === 'string') {
var array_buffer = new Uint8Array(buf.length);
for (var i = 0; i < buf.length; i++) {
array_buffer[i] = buf.charCodeAt(i) & 0xff; // implicitly assumes little-endian
}
return array_buffer.buffer || array_buffer;
} else {
return buf;
}
}
};
if (typeof DataView === 'undefined') {
DataView = function DataView(buffer, byteOffset, byteLength) {
this.buffer = buffer;
this.byteOffset = byteOffset || 0;
this.byteLength = byteLength || buffer.byteLength || buffer.length;
this._isString = typeof buffer === 'string';
};
DataView.prototype = {
_getCharCodes: function _getCharCodes(buffer, start, length) {
start = start || 0;
length = length || buffer.length;
var end = start + length;
var codes = [];
for (var i = start; i < end; i++) {
codes.push(buffer.charCodeAt(i) & 0xff);
}
return codes;
},
_getBytes: function _getBytes(length, byteOffset, littleEndian) {
var result;
// Handle the lack of endianness
if (littleEndian === undefined) {
littleEndian = this._littleEndian;
}
// Handle the lack of byteOffset
if (byteOffset === undefined) {
byteOffset = this.byteOffset;
} else {
byteOffset = this.byteOffset + byteOffset;
}
if (length === undefined) {
length = this.byteLength - byteOffset;
}
// Error Checking
if (typeof byteOffset !== 'number') {
throw new TypeError('DataView byteOffset is not a number');
}
if (length < 0 || byteOffset + length > this.byteLength) {
throw new Error('DataView length or (byteOffset+length) value is out of bounds');
}
if (this.isString) {
result = this._getCharCodes(this.buffer, byteOffset, byteOffset + length);
} else {
result = this.buffer.slice(byteOffset, byteOffset + length);
}
if (!littleEndian && length > 1) {
if (!(result instanceof Array)) {
result = Array.prototype.slice.call(result);
}
result.reverse();
}
return result;
},
// Compatibility functions on a String Buffer
getFloat64: function getFloat64(byteOffset, littleEndian) {
var b = this._getBytes(8, byteOffset, littleEndian),
sign = 1 - 2 * (b[7] >> 7),
exponent = ((b[7] << 1 & 0xff) << 3 | b[6] >> 4) - ((1 << 10) - 1),
// Binary operators such as | and << operate on 32 bit values, using + and Math.pow(2) instead
mantissa = (b[6] & 0x0f) * Math.pow(2, 48) + b[5] * Math.pow(2, 40) + b[4] * Math.pow(2, 32) + b[3] * Math.pow(2, 24) + b[2] * Math.pow(2, 16) + b[1] * Math.pow(2, 8) + b[0];
if (exponent === 1024) {
if (mantissa !== 0) {
return NaN;
} else {
return sign * Infinity;
}
}
if (exponent === -1023) {
// Denormalized
return sign * mantissa * Math.pow(2, -1022 - 52);
}
return sign * (1 + mantissa * Math.pow(2, -52)) * Math.pow(2, exponent);
},
getFloat32: function getFloat32(byteOffset, littleEndian) {
var b = this._getBytes(4, byteOffset, littleEndian),
sign = 1 - 2 * (b[3] >> 7),
exponent = (b[3] << 1 & 0xff | b[2] >> 7) - 127,
mantissa = (b[2] & 0x7f) << 16 | b[1] << 8 | b[0];
if (exponent === 128) {
if (mantissa !== 0) {
return NaN;
} else {
return sign * Infinity;
}
}
if (exponent === -127) {
// Denormalized
return sign * mantissa * Math.pow(2, -126 - 23);
}
return sign * (1 + mantissa * Math.pow(2, -23)) * Math.pow(2, exponent);
},
getInt32: function getInt32(byteOffset, littleEndian) {
var b = this._getBytes(4, byteOffset, littleEndian);
return b[3] << 24 | b[2] << 16 | b[1] << 8 | b[0];
},
getUint32: function getUint32(byteOffset, littleEndian) {
return this.getInt32(byteOffset, littleEndian) >>> 0;
},
getInt16: function getInt16(byteOffset, littleEndian) {
return this.getUint16(byteOffset, littleEndian) << 16 >> 16;
},
getUint16: function getUint16(byteOffset, littleEndian) {
var b = this._getBytes(2, byteOffset, littleEndian);
return b[1] << 8 | b[0];
},
getInt8: function getInt8(byteOffset) {
return this.getUint8(byteOffset) << 24 >> 24;
},
getUint8: function getUint8(byteOffset) {
return this._getBytes(1, byteOffset)[0];
}
};
}
module.exports = THREE;
|
import { combineReducers } from 'redux';
import Mail from './mail.js';
import Auth from './auth.js';
const rootReducer = combineReducers({
mail: Mail,
logging: Auth
});
export default rootReducer;
|
var path = require("path"),
fs = require("fs");
var vows = require("vows"),
should = require("should"),
moment = require("moment");
var AutoIngestTool = require("../index");
var TMP_DIR = path.join(__dirname, "..", "tmp");
var suite = vows.describe("Download sales report using promise");
suite
.addBatch({
"when downloading the latest available daily sales report": {
topic: function () {
var self = this,
paths = {
archive: TMP_DIR,
report: TMP_DIR,
json_report: TMP_DIR
},
params = {
username: process.env.USERNAME,
password: process.env.PASSWORD,
vendor_number: process.env.VENDOR_NUMBER,
report_type: "Sales",
report_subtype: "Summary",
date_type: "Daily",
report_date: moment().subtract(2, "days").format("YYYYMMDD")
};
AutoIngestTool
.downloadSalesReport(params, paths)
.then(
function (paths) { self.callback(null, paths); },
function (err) { self.callback(err); }
);
},
"we can open the JSON file": {
topic: function (paths) {
fs.readFile(paths.json_report, { encoding: "utf8" }, this.callback);
},
"and parse it": {
topic: function (data) {
return JSON.parse(data);
},
"the json should be an array": function (json) {
json.should.be.an.Array();
},
"the json should not be empty": function (json) {
json.should.not.be.empty();
}
}
}
}
})
.addBatch({
"when downloading the latest available weekly sales report": {
topic: function () {
var self = this,
paths = {
archive: TMP_DIR,
report: TMP_DIR,
json_report: TMP_DIR
},
params = {
username: process.env.USERNAME,
password: process.env.PASSWORD,
vendor_number: process.env.VENDOR_NUMBER,
report_type: "Sales",
report_subtype: "Summary",
date_type: "Weekly",
report_date: moment().day(-7).format("YYYYMMDD")
};
AutoIngestTool
.downloadSalesReport(params, paths)
.then(
function (paths) { self.callback(null, paths); },
function (err) { self.callback(err); }
);
},
"we can open the JSON file": {
topic: function (paths) {
fs.readFile(paths.json_report, { encoding: "utf8" }, this.callback);
},
"and parse it": {
topic: function (data) {
return JSON.parse(data);
},
"the json should be an array": function (json) {
json.should.be.an.Array();
},
"the json should not be empty": function (json) {
json.should.not.be.empty();
}
}
}
}
})
.addBatch({
"when downloading the latest available monthly sales report": {
topic: function () {
var self = this,
paths = {
archive: TMP_DIR,
report: TMP_DIR,
json_report: TMP_DIR
},
params = {
username: process.env.USERNAME,
password: process.env.PASSWORD,
vendor_number: process.env.VENDOR_NUMBER,
report_type: "Sales",
report_subtype: "Summary",
date_type: "Monthly",
report_date: moment().subtract(1, "months").format("YYYYMM")
};
AutoIngestTool
.downloadSalesReport(params, paths)
.then(
function (paths) { self.callback(null, paths); },
function (err) { self.callback(err); }
);
},
"we can open the JSON file": {
topic: function (paths) {
fs.readFile(paths.json_report, { encoding: "utf8" }, this.callback);
},
"and parse it": {
topic: function (data) {
return JSON.parse(data);
},
"the json should be an array": function (json) {
json.should.be.an.Array();
},
"the json should not be empty": function (json) {
json.should.not.be.empty();
}
}
}
}
})
.addBatch({
"when downloading the latest available yearly sales report": {
topic: function () {
var self = this,
paths = {
archive: TMP_DIR,
report: TMP_DIR,
json_report: TMP_DIR
},
params = {
username: process.env.USERNAME,
password: process.env.PASSWORD,
vendor_number: process.env.VENDOR_NUMBER,
report_type: "Sales",
report_subtype: "Summary",
date_type: "Yearly",
report_date: moment().subtract(1, "years").format("YYYY")
};
AutoIngestTool
.downloadSalesReport(params, paths)
.then(
function (paths) { self.callback(null, paths); },
function (err) { self.callback(err); }
);
},
"we can open the JSON file": {
topic: function (paths) {
fs.readFile(paths.json_report, { encoding: "utf8" }, this.callback);
},
"and parse it": {
topic: function (data) {
return JSON.parse(data);
},
"the json should be an array": function (json) {
json.should.be.an.Array();
},
"the json should not be empty": function (json) {
json.should.not.be.empty();
}
}
}
}
});
suite.export(module);
|
import net from 'net';
import fs from 'fs';
var port = 22112;
var server = net.createServer(function(socket) {
console.log('user connected: ' + socket.remoteAddress + ":" + socket.remotePort);
var fileWriteStream = fs.createWriteStream(basepath + 'received.png');
socket.on('data', function(data) {
console.log('# socket data |', data.length);
fileWriteStream.write(data);
fileWriteStream.end();
});
socket.on('drain', () => {
console.log('socket drain');
})
socket.on('end', function () {
console.log('socket end');
});
socket.on('close', function() {
console.log('socket close');
});
socket.on('error', function(err) {
console.log('socket ERROR', err.code, err.syscall);
});
});
server.on('listening', function() {
console.log('server listening');
});
server.on('connection', function(socket) {
console.log('server connection', socket.remoteAddress + ":" + socket.remotePort);
});
server.on('close', function() {
console.log('server close');
});
server.on('error', function(err) {
console.log('server ERROR', err.code, err.syscall);
});
server.listen(port, function() {
console.log('server.listen callback')
});
|
FoCUS = window.FoCUS || {};
FoCUS.ui = (function() {
// Base elements
var body, article, uiContainer, overlay, aboutButton, descriptionModal, header;
// Buttons
var screenSizeElement, colorLayoutElement, targetElement, saveElement;
// Word Counter
var wordCountValue, wordCountBox, wordCountElement, wordCounter, wordCounterProgress;
//save support
var supportSave, saveFormat, textToWrite;
var expandScreenIcon = '';
var shrinkScreenIcon = '';
var darkLayout = false;
function init() {
supportsSave = !!new Blob()?true:false;
bindElements();
wordCountActive = false;
if ( FoCUS.util.supportsHtmlStorage() ) {
loadState();
}
}
function loadState() {
// Activate word counter
if ( localStorage['wordCount'] && localStorage['wordCount'] !== "0") {
wordCountValue = parseInt(localStorage['wordCount']);
wordCountElement.value = localStorage['wordCount'];
wordCounter.className = "word-counter active";
updateWordCount();
}
// Activate color switch
if ( localStorage['darkLayout'] === 'true' ) {
if ( darkLayout === false ) {
document.body.className = 'yang';
} else {
document.body.className = 'yin';
}
darkLayout = !darkLayout;
}
}
function saveState() {
if ( FoCUS.util.supportsHtmlStorage() ) {
localStorage[ 'darkLayout' ] = darkLayout;
localStorage[ 'wordCount' ] = wordCountElement.value;
}
}
function bindElements() {
// Body element for light/dark styles
body = document.body;
uiContainer = document.querySelector( '.ui' );
// UI element for color flip
colorLayoutElement = document.querySelector( '.color-flip' );
colorLayoutElement.onclick = onColorLayoutClick;
// UI element for full screen
screenSizeElement = document.querySelector( '.fullscreen' );
screenSizeElement.onclick = onScreenSizeClick;
targetElement = document.querySelector( '.target ');
targetElement.onclick = onTargetClick;
//init event listeners only if browser can save
if (supportsSave) {
saveElement = document.querySelector( '.save' );
saveElement.onclick = onSaveClick;
var formatSelectors = document.querySelectorAll( '.saveselection span' );
for( var i in formatSelectors ) {
formatSelectors[i].onclick = selectFormat;
}
document.querySelector('.savebutton').onclick = saveText;
} else {
document.querySelector('.save.useicons').style.display = "none";
}
// Overlay when modals are active
overlay = document.querySelector( '.overlay' );
overlay.onclick = onOverlayClick;
article = document.querySelector( '.content' );
article.onkeyup = onArticleKeyUp;
wordCountBox = overlay.querySelector( '.wordcount' );
wordCountElement = wordCountBox.querySelector( 'input' );
wordCountElement.onchange = onWordCountChange;
wordCountElement.onkeyup = onWordCountKeyUp;
descriptionModal = overlay.querySelector( '.description' );
saveModal = overlay.querySelector('.saveoverlay');
aboutButton = document.querySelector( '.about' );
aboutButton.onclick = onAboutButtonClick;
header = document.querySelector( '.header' );
header.onkeypress = onHeaderKeyPress;
}
function onScreenSizeClick( event ) {
screenfull.toggle();
if ( screenfull.enabled ) {
document.addEventListener( screenfull.raw.fullscreenchange, function () {
if ( screenfull.isFullscreen ) {
screenSizeElement.innerHTML = shrinkScreenIcon;
} else {
screenSizeElement.innerHTML = expandScreenIcon;
}
});
}
};
function onColorLayoutClick( event ) {
if ( darkLayout === false ) {
document.body.className = 'yang';
} else {
document.body.className = 'yin';
}
darkLayout = !darkLayout;
saveState();
}
function onAboutButtonClick( event ) {
overlay.style.display = "block";
descriptionModal.style.display = "block";
}
function onSaveClick( event ) {
overlay.style.display = "block";
saveModal.style.display = "block";
}
function saveText( event ) {
if (typeof saveFormat != 'undefined' && saveFormat != '') {
var blob = new Blob([textToWrite], {type: "text/plain;charset=utf-8"});
/* remove tabs and line breaks from header */
var headerText = header.innerHTML.replace(/(\t|\n|\r)/gm,"");
if (headerText === "") {
headerText = "FoCUS";
}
saveAs(blob, headerText + '.txt');
} else {
document.querySelector('.saveoverlay h1').style.color = '#FC1E1E';
}
}
/* Allows the user to press enter to tab from the title */
function onHeaderKeyPress( event ) {
if ( event.keyCode === 13 ) {
event.preventDefault();
article.focus();
}
}
/* Allows the user to press enter to tab from the word count modal */
function onWordCountKeyUp( event ) {
if ( event.keyCode === 13 ) {
event.preventDefault();
setWordCount( parseInt(this.value) );
removeOverlay();
article.focus();
}
}
function onArticleKeyUp( event ) {
if ( wordCountValue > 0 ) {
updateWordCount();
}
}
function selectFormat( e ) {
if ( document.querySelectorAll('span.activesave').length > 0 ) {
document.querySelector('span.activesave').className = '';
}
document.querySelector('.saveoverlay h1').style.cssText = '';
var targ;
if (!e) var e = window.event;
if (e.target) targ = e.target;
else if (e.srcElement) targ = e.srcElement;
// defeat Safari bug
if (targ.nodeType == 3) {
targ = targ.parentNode;
}
targ.className ='activesave';
saveFormat = targ.getAttribute('data-format');
var header = document.querySelector('header.header');
var headerText = header.innerHTML.replace(/(\r\n|\n|\r)/gm,"") + "\n";
var body = document.querySelector('article.content');
var bodyText = body.innerHTML;
textToWrite = formatText(saveFormat,headerText,bodyText);
var textArea = document.querySelector('.hiddentextbox');
textArea.value = textToWrite;
textArea.focus();
textArea.select();
}
function formatText( type, header, body ) {
var text;
switch( type ) {
case 'html':
header = "<h1>" + header + "</h1>";
text = header + body;
text = text.replace(/\t/g, '');
break;
case 'markdown':
header = header.replace(/\t/g, '');
header = header.replace(/\n$/, '');
header = "#" + header + "#";
text = body.replace(/\t/g, '');
text = text.replace(/<b>|<\/b>/g,"**")
.replace(/\r\n+|\r+|\n+|\t+/ig,"")
.replace(/<i>|<\/i>/g,"_")
.replace(/<blockquote>/g,"> ")
.replace(/<\/blockquote>/g,"")
.replace(/<p>|<\/p>/gi,"\n")
.replace(/<br>/g,"\n");
var links = text.match(/<a href="(.+)">(.+)<\/a>/gi);
if (links !== null) {
for ( var i = 0; i<links.length; i++ ) {
var tmpparent = document.createElement('div');
tmpparent.innerHTML = links[i];
var tmp = tmpparent.firstChild;
var href = tmp.getAttribute('href');
var linktext = tmp.textContent || tmp.innerText || "";
text = text.replace(links[i],'['+linktext+']('+href+')');
}
}
text = header +"\n\n"+ text;
break;
case 'plain':
header = header.replace(/\t/g, '');
var tmp = document.createElement('div');
tmp.innerHTML = body;
text = tmp.textContent || tmp.innerText || "";
text = text.replace(/\t/g, '')
.replace(/\n{3}/g,"\n")
.replace(/\n/,""); //replace the opening line break
text = header + text;
break;
default:
break;
}
return text;
}
function onOverlayClick( event ) {
if ( event.target.className === "overlay" ) {
removeOverlay();
}
}
function removeOverlay() {
overlay.style.display = "none";
wordCountBox.style.display = "none";
descriptionModal.style.display = "none";
saveModal.style.display = "none";
if ( document.querySelectorAll('span.activesave' ).length > 0) {
document.querySelector('span.activesave').className = '';
}
saveFormat='';
}
return {
init: init
}
})();
|
import { normalizeString2 } from './-utils';
export default normalizeString2('lastIndexOf');
|
var categories = [{
"title": "Mexican",
"link": "mexican.html"
}, {
"title": "American",
"link": "american.html"
}, {
"title": "Italian",
"link": "italian.html"
}, {
"title": "Indian",
"link": "indian.html"
}, {
"title": "Japanese",
"link": "japanese.html"
}, {
"title": "Chinese",
"link": "chinese.html"
}, {
"title": "Vietnamese",
"link": "vietnamese.html"
}, {
"title": "Korean",
"link": "korean.html"
}, {
"title": "Greek",
"link": "greek.html"
}, {
"title": "French",
"link": "french.html"
}, {
"title": "Thai",
"link": "thai.html"
}];
var easeOutExpo = function easeOutExpo(t, b, c, d) {
return c * Math.pow(2, 10 * (t / d - 1)) + b;
};
var newFood = function newFood(elem) {
var food = categories[Math.floor(Math.random() * categories.length)];
elem.innerHTML = food.title;
elem.href = food.link;
};
for (var i = 0; i < 100; i++) {
var delay = easeOutExpo(i, 0, 3000, 100);
setTimeout(function () {
return newFood(document.querySelector('.food'));
}, delay);
}
|
import selector from '../../../../lib/modules/badges/selectors/getBadge';
describe('Select badge from state ', () => {
const state = {
badges: { 3: { id: 3 } }
};
it('returns badge if exist', () => {
const value = selector(state, { badgeId: 3 });
expect(value).to.deep.equal({ id: 3 });
});
it('returns undefined if badge does not exist', () => {
const value = selector(state, { badgeId: 5 });
expect(value).to.equal(undefined);
});
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:a30912f5da6f671b354a1b52e20b9194eaada009881a1f1de900a74e009b53fa
size 78480
|
/*! jQuery UI - v1.10.4 - 2014-03-23
* http://jqueryui.com
* Copyright 2014 jQuery Foundation and other contributors; Licensed MIT */
jQuery(function(t){t.datepicker.regional.pl={closeText:"Zamknij",prevText:"<Poprzedni",nextText:"Następny>",currentText:"Dziś",monthNames:["Styczeń","Luty","Marzec","Kwiecień","Maj","Czerwiec","Lipiec","Sierpień","Wrzesień","Październik","Listopad","Grudzień"],monthNamesShort:["Sty","Lu","Mar","Kw","Maj","Cze","Lip","Sie","Wrz","Pa","Lis","Gru"],dayNames:["Niedziela","Poniedziałek","Wtorek","Środa","Czwartek","Piątek","Sobota"],dayNamesShort:["Nie","Pn","Wt","Śr","Czw","Pt","So"],dayNamesMin:["N","Pn","Wt","Śr","Cz","Pt","So"],weekHeader:"Tydz",dateFormat:"dd.mm.yy",firstDay:1,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},t.datepicker.setDefaults(t.datepicker.regional.pl)});
|
/**
* Copyright (C) 2013 Emay Komarudin
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @author Emay Komarudin
*
**/
Ext.define('App.view.pradjustment.warehouse', {
extend: 'Ext.panel.Panel',
alias: 'widget.apppradjustmentvpradjustmentWarehouse',
title: 'Tujuan Pengiriman',
layout: { type: 'fit', align: 'stretch'},
initComponent: function () {
var me = this;
Ext.apply(me, {
items: [
{
xtype: 'container', flex:1,
html: ' Berisi Warehouse, Menampilkan Semua Warehouse yang ada di System'
}
]
});
me.callParent(arguments);
}
});
|
const _ = require('underscore');
const AgendaCard = require('../../agendacard.js');
class Treaty extends AgendaCard {
constructor(owner, cardData) {
super(owner, cardData);
this.registerEvents(['onDecksPrepared']);
}
setupCardAbilities(ability) {
this.action({
title: 'Draw card then discard card',
cost: ability.costs.kneelFactionCard(),
handler: () => {
this.controller.drawCardsToHand(1);
this.game.addMessage('{0} uses {1} and kneels their faction card to draw 1 card', this.controller, this);
this.game.promptForSelect(this.controller, {
activePromptTitle: 'Select a card',
source: this,
cardCondition: card => card.location === 'hand' && card.controller === this.controller,
onSelect: (player, card) => this.cardSelected(player, card)
});
}
});
}
cardSelected(player, card) {
player.discardCard(card);
this.game.addMessage('{0} then discards {1} for {2}', this.controller, card, this);
return true;
}
onDecksPrepared() {
let factionsInDecks = [];
for(const card of this.game.allCards) {
if(card.owner === this.owner && !factionsInDecks.includes(card.getPrintedFaction())) {
factionsInDecks.push(card.getPrintedFaction());
}
}
let factionsToAnnounce = _.filter(factionsInDecks, faction => faction !== this.controller.getFaction() && faction !== 'neutral');
let message = '{0} names {1} as their {2} for {3}';
if(factionsToAnnounce.length > 2) {
message += ' (this exceeds the maximum allowed number of factions)';
}
if(_.isEmpty(factionsToAnnounce)) {
//Don't print any message: allows the player to bluff any faction
return;
}
this.game.addMessage(message, this.controller, factionsToAnnounce, factionsToAnnounce.length > 1 ? 'factions' : 'faction', this);
}
}
Treaty.code = '00003';
module.exports = Treaty;
|
'use strict';
// originally from https://github.com/thiagodemellobueno/metalsmith-packagejson
// ported into this project because of https://github.com/thiagodemellobueno/metalsmith-packagejson/issues/4
const fs = require('fs');
const path = require('path');
function importFile(path) {
try {
const content = fs.readFileSync(path, { encoding: 'utf8' });
return JSON.parse(content);
} catch (error) {
/* eslint-disable no-console */
console.error('could not parse ', path, 'as JSON');
console.error(error);
/* eslint-enable no-console */
}
return null;
}
function extractMetalsmithFile(files, name) {
let data = null;
if (!files[name]) {
return data;
}
try {
const content = files[name].contents.toString();
data = JSON.parse(content);
} catch (error) {
/* eslint-disable no-console */
console.error('could not parse ', name, 'as JSON');
console.error(error);
/* eslint-enable no-console */
}
delete files[name];
return data;
}
module.exports = function(options) {
if (!options) {
options = {};
}
if (!options.file) {
throw new Error('importJson() needs a file to load');
}
if (!options.key) {
throw new Error('importJson() needs a key to store the data under');
}
const filename = path.basename(options.file);
const filepath = path.join('.', options.file);
return function(files, metalsmith, done) {
const metadata = metalsmith.metadata();
const data = extractMetalsmithFile(files, filename) || importFile(filepath);
metadata[options.key] = data;
done();
};
};
|
var paperWidth = 320, paperHeight = 320;
var paper, dragAndDrop;
var w = 300, h = 30;
var actions = [
];
var texts = [
"Fireworks",
"Announce prize winner",
"Thank everyone",
"Long speech",
"Drum rolls",
"Minute of silence",
"Sing a song",
"10 minutes break",
"Play the clairon",
"Dance performance"
];
var nb = texts.length;
function getObject(id) {
var r = paper.rect(-w/2,-h/2,w,h, h/5).attr('fill','#E0E0F8');
var t = paper.text(0,0,texts[id]).attr({'font-size' : 15, 'font-weight' : 'bold'});
$(t.node).css({
"-webkit-touch-callout": "none",
"-webkit-user-select": "none",
"-khtml-user-select": "none",
"-moz-user-select": "none",
"-ms-user-select": "none",
"user-select": "none",
"cursor" : "default"
});
return [r, t];
}
function Task() {
this.mode = "";
this.interval_id = -1;
this.reset();
};
Task.prototype.load = function(random_seed, mode) {
this.mode = mode;
paper = Raphael(document.getElementById('anim'),paperWidth, paperHeight);
paper.rect(0,0,paperWidth, paperHeight);
dragAndDrop = DragAndDropSystem({
paper : paper,
actionIfDropped : function(srcCont, srcPos, dstCont, dstPos, type) {
if (dstCont == null)
return false;
return true;
}
});
dragAndDrop.addContainer({
ident : 'seq',
cx : paperWidth/2, cy : paperHeight/2,
widthPlace : w, heightPlace : h,
nbPlaces : nb,
direction : 'vertical',
dropMode : 'insertBefore',
placeBackgroundArray : []
});
for (var i = 0; i < nb; i++) {
dragAndDrop.insertObject('seq',i, {ident : i, elements : getObject(i)});
}
this.reset();
$('#execute').click(execute(this));
};
Task.prototype.unload = function() {
task.interval_id = clearInterval(task.interval_id);
return true;
};
Task.prototype.getAnswer = function() {
return JSON.stringify(dragAndDrop.getObjects('seq'));
}
Task.prototype.reloadAnswer = function(strAnswer) {
var answer = [0, 1, 2, 3, 4, 5, 6, 7];
if (strAnswer != "") {
answer = $.parseJSON(strAnswer);
}
for (var i = 0; i < nb; i++) {
dragAndDrop.removeObject('seq', i);
}
for (var i = 0; i < nb; i++) {
dragAndDrop.insertObject('seq',i, {ident : answer[i], elements : getObject(answer[i])});
}
}
Task.prototype.draw = function () {
}
Task.prototype.reset_play = function () {
window.clearInterval(this.interval_id)
this.interval_id = -1;
this.draw();
}
Task.prototype.reset = function () {
$("#success, #error").html("");
this.reset_play();
}
function execute(task) {
return function() {
Tracker.trackData({dataType:"clickitem", item:"execute"});
task.reset();
//task.interval_id = window.setInterval(tick(task), 300);
};
}
function tick(task) {
return function() {
task.tick();
};
}
var task = new Task();
|
(function(){
angular.module( 'sunshine.test', [
'ui.router',
'ui.bootstrap'
])
.config(function config( $stateProvider ) {
$stateProvider.state( 'admin.test', {
url: '/test',
ncyBreadcrumb: {
label: 'Recommendations Edit',
parent: 'admin.edit'
},
views: {
"admin": {
//controller: 'DashBoardCtrl',
templateUrl: 'test/test.tpl.html'
}
},
data:{ pageTitle: 'Administration - Dashboard',
authorizedRoles: ['Everyone'] }
});
})
.controller('testCtrl', function testCtrl( $rootScope, Schedule, Template,
testEdit, HOTHelper) {
var self = this;
var test_Handsontable;
self.draft_dept = $rootScope.selected_draft_dept;
self.test_grid = document.getElementById('test-grid');
self.test_count = document.getElementById("test-count");
self.searchResults = [];
self.selSearchResult = -1;
self.status = "saved";
Template.get()
.then(function (data){
var template = Template.all;
//Add runtime settings
var settings = HOTHelper.config();
// var l = HOTHelper.getFittedWidths.call(test_Handsontable, template, settings.columns);
// settings.search = {callback: HOTHelper.searchResultCounter};
// settings.manualColumnResize = [1, l.category, l.title, l.link, l.retention, l.on_site, l.off_site, l.total, l.remarks, l.is_visible ];
settings.data = template;
//Display Table
self.test_grid.style.visibility = 'hidden';
if(typeof test_Handsontable == 'undefined'){
test_Handsontable = new Handsontable(self.test_grid, settings);
}
self.test_grid.style.visibility = 'visible';
});
// self.next = function(){
//
// if (self.searchResults.length < 1 ){return;}
//
// self.selSearchResult++;
//
// if(self.selSearchResult > (self.searchResults.length - 1))
// {
// self.selSearchResult = 0;
// }
//
// var sel = self.searchResults[self.selSearchResult];
// test_Handsontable.selectCell(sel.row, sel.col);
//
// };
//
// self.previous = function(){
// if (self.searchResults.length < 1 ){return;}
//
// self.selSearchResult--;
//
// if(self.selSearchResult < 0 )
// {
// self.selSearchResult = self.searchResults.length - 1;
// }
//
// var sel = self.searchResults[self.selSearchResult];
// test_Handsontable.selectCell(sel.row, sel.col);
//
// };
// add listener to test_search field to cause the grid to
// be searched
// var test_search = document.getElementById('test-search');
// Handsontable.Dom.addEvent(test_search, 'keyup', function (event) {
// self.searchResults = test_Handsontable.search.query(this.value);
// self.test_count.innerHTML = self.searchResults.length;
// test_Handsontable.render();
// });
})
.factory('testEdit', ["Template", "RetentionCategories", "HOTHelper",
function (Template, RetentionCategories, HOTHelper) {
//Before Save
var beforeSave = function(change, source){
var test_status = document.getElementById("test-status");
test_status.innerHTML = "saving";
};
var setStatus = function(str){
var test_status = document.getElementById("test-status");
test_status.innerHTML = str;
};
//Autosave function
var autoSave = function(change,source){
var self = this;
if(change == null){return;}
var data = change[0];
if (source === 'loadData') {return;} //dont' save this change
if (source === 'insertId') {return;} // stops an endless loop when the new record id is added after an insert
// transform sorted row to original row
var rowNumber = this.sortIndex[data[0]] ? this.sortIndex[data[0]][0] : data[0];
var row = this.getSourceDataAtRow(rowNumber);
var colCount = this.countCols();
//set visibility
row.is_visible = "Visible";
for(var i = 0; i< colCount; i++){
if(!this.getCellMeta(rowNumber, i).valid){
row.is_visible = "Hidden";
break;
}
if(row.title == null){
row.is_visible = "Hidden";
break;
}
}
Template.upsert(row).then(function(res){
if(row._id == null){
self.setDataAtCell(rowNumber,8, res.data.is_visible, "fixValidationOfNewRow");
}
self.setDataAtCell(rowNumber,0, res.data._id, "insertId");
setStatus("saved");
});
};
//remove one record from the database
var beforeRemoveRow = function(index, amount){
var rowNumber = this.sortIndex[index] ? this.sortIndex[index][0] : index;
var row = this.getSourceDataAtRow(rowNumber);
Template.del(row)
.success(function(res){
})
.error(function(err){
console.log(err);
});
};
var afterRender = function(){
this.validateCells(function(){});
};
return {
config : function(){
var config = {};
// config.columns = [];
// config.minSpareRows = 1;
// config.contextMenu = ["row_above", "row_below", "remove_row"];
// config.colHeaders = ["_id","Category", "Title", "Link", "Retention", "On-site", "Off-site", "Total", "Remarks", "Visibility"];
//
// //schema for empty row
// config.dataSchema={_id:null, category:null, title:null, link:null, retention:null, on_site:null, off_site:null, total:null, remarks:null, is_visible: null};
//
// //_id Column (hidden)
// config.columns.push({"data":"_id"});
//
// //Category Column
// var categoryConfig = {};
// categoryConfig.data = "category";
// categoryConfig.type = "autocomplete";
// categoryConfig.source = HOTHelper.categoryAutoComplete;
// categoryConfig.strict = false;
// categoryConfig.validator = HOTHelper.isRequired;
// config.columns.push(categoryConfig);
//
// //Title Column
// var titleConfig = {};
// titleConfig.data = "title";
// titleConfig.validator = HOTHelper.isRequired;
// config.columns.push(titleConfig);
//
// //Link Column
// config.columns.push({"data":"link"});
//
// // Retention Column
// var retentionConfig = {};
// retentionConfig.data = "retention";
// retentionConfig.type = "autocomplete";
// retentionConfig.source = RetentionCategories;
// retentionConfig.allowInvalid = true;
// retentionConfig.validator = HOTHelper.retentionValidator;
// config.columns.push(retentionConfig);
//
// // On-site Column
// var onSiteConfig = {};
// onSiteConfig.data = "on_site";
// onSiteConfig.validator = HOTHelper.isRequired;
// config.columns.push(onSiteConfig);
//
// // Off-site Column
// var offSiteConfig = {};
// offSiteConfig.data = "off_site";
// offSiteConfig.validator = HOTHelper.isRequired;
// config.columns.push(offSiteConfig);
// // Total Column
// config.columns.push({"data":"total"});
//
// // Remarks Column
// config.columns.push({"data":"remarks"});
//
// // Visibility Column
// var isVisibleConfig = {};
// isVisibleConfig.data = "is_visible";
// isVisibleConfig.readOnly = true;
// config.columns.push(isVisibleConfig);
//Add Event Functions
// config.afterChange = autoSave;
// config.beforeRemoveRow = beforeRemoveRow;
// config.beforeChange = beforeSave;
// config.afterRender = afterRender;
return config;
}
};
}])
.factory("HOTHelper", ["RetentionCategories", function(RetentionCategories){
//This is a collections of functions and
//configurations used in Handsontable (HOT)
// throughout this app.
return{
// Division Autocomplete Function
divisionAutoComplete : function(query, process){
var vals = this.instance.getDataAtCol(1);
var uniqueVals = vals.unique().sort().nulless();
process(uniqueVals);
},
// Division Autocomplete Function
categoryAutoComplete : function(query, process){
var vals = this.instance.getDataAtCol(2);
var uniqueVals = vals.unique().sort().nulless();
process(uniqueVals);
},
retentionValidator : function(value, callback){
//Had to write custom function for strict autocomplete
//because the built in validation does not skip the spare row
var row = this.row + 1;
var rowCount = this.instance.countRows();
//skip minSpareRow
if(row == rowCount){
callback(true);
return;
}
//validation: field required
if(!value){
callback(false);
return;
}
//validation: value must match RetentionCategories
for(var i = 0; i<RetentionCategories.length; i++ ){
if(RetentionCategories[i] == value){
callback(true);
return;
}
}
//value was NOT in RetentionCategories
callback(false);
},
isRequired : function(value, callback){
//Skip the spareMinRow when validating
var row = this.row + 1;
var rowCount = this.instance.countRows();
if(row == rowCount){
//ignore validating minSpareRow
callback(true);
return;
}else if(!value){
callback(false);
return;
}else{
callback (true);
}
},
searchResultCounter : function (instance, row, col, value, result) {
Handsontable.Search.DEFAULT_CALLBACK.apply(this, arguments);
// if (result) {
// searchResultCount++;
// }
},
config: function(addOns){
// basic config
var config = {};
// config.colHeaders = true;
// config.rowHeaders = true;
// config.autoColumnSize = false;
// config.manualColumnResize = true;
// config.currentRowClassName = "current-row";
config.minSpareRows = 1;
// config.columnSorting = true;
// config.fixedRowsTop = false;
// config.autoWrapRow = true;
// config.search = true;
//config.contextMenu = ['row_below', 'remove_row'];
//config.contextMenu = ["row_above", "row_below", "col_left", "sep1", "col_right", "remove_row" ];
config.contextMenu = true;
if(typeof addOns != 'undefined'){
for(var prop in addOns){
config[prop] = addOns[prop];
}
}
return config;
// },
//
// getFittedWidths : function(){
// var recordArr = arguments[0].slice();
// var maxColWidth = 800;
// var minColWidth = 120;
// var padding = 50; //accounts for arrow on dropdown fields
// var fittedColumnWidths = {};
// var longestPerField = {};
// var cols = arguments[1];
// var col;
// var sorter = function (property) {
// return function (a,b) {
// if(b[property] != null){bLength = b[property].length;}else{bLength = 0;}
// if(a[property] != null){aLength = a[property].length;}else{aLength = 0;}
// return bLength - aLength;
// };
// };
//
// for(var i = 0; i < cols.length; i++){
// longestPerField = recordArr.sort(sorter(cols[i].data))[0];
// col = cols[i].data;
//
// //no records in the record array, so column does not exits
// if(typeof longestPerField == 'undefined'){
// fittedColumnWidths[col] = minColWidth;
// continue;
// }
//
// // all values for the column are null; set minWidth
// if(longestPerField[col] == null){
// fittedColumnWidths[col] = minColWidth;
// continue;
// }
//
// if(typeof longestPerField[col] == "boolean"){
// fittedColumnWidths[col] = minColWidth;
// continue;
// }
//
// //visual field length greater than maxColWidth
// if (longestPerField[col].visualLength() > maxColWidth) {
// fittedColumnWidths[col] = maxColWidth;
// continue;
// }
//
// fittedColumnWidths[col] = longestPerField[col].visualLength() + padding;
// }
//
// return fittedColumnWidths;
}
};
}])
;
})();
|
// Generated on 2016-03-03 using generator-angular 0.11.1
'use strict';
// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'
module.exports = function (grunt) {
// Load grunt tasks automatically
require('load-grunt-tasks')(grunt);
// Time how long tasks take. Can help when optimizing build times
require('time-grunt')(grunt);
// Configurable paths for the application
var appConfig = {
app: require('./bower.json').appPath || 'app',
dist: 'dist'
};
// Define the configuration for all the tasks
grunt.initConfig({
// Project settings
yeoman: appConfig,
// Watches files for changes and runs tasks based on the changed files
watch: {
bower: {
files: ['bower.json'],
tasks: ['wiredep']
},
js: {
files: ['<%= yeoman.app %>/scripts/{,*/}*.js'],
tasks: ['newer:jshint:all'],
options: {
livereload: '<%= connect.options.livereload %>'
}
},
jsTest: {
files: ['test/spec/{,*/}*.js'],
tasks: ['newer:jshint:test', 'karma']
},
styles: {
files: ['<%= yeoman.app %>/styles/{,*/}*.css'],
tasks: ['newer:copy:styles', 'autoprefixer']
},
gruntfile: {
files: ['Gruntfile.js']
},
livereload: {
options: {
livereload: '<%= connect.options.livereload %>'
},
files: [
'<%= yeoman.app %>/{,*/}*.html',
'.tmp/styles/{,*/}*.css',
'<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
]
}
},
// The actual grunt server settings
connect: {
options: {
port: 9000,
// Change this to '0.0.0.0' to access the server from outside.
hostname: 'localhost',
livereload: 35729
},
livereload: {
options: {
open: true,
middleware: function (connect) {
return [
connect.static('.tmp'),
connect().use(
'/bower_components',
connect.static('./bower_components')
),
connect().use(
'/app/styles',
connect.static('./app/styles')
),
connect.static(appConfig.app)
];
}
}
},
test: {
options: {
port: 9001,
middleware: function (connect) {
return [
connect.static('.tmp'),
connect.static('test'),
connect().use(
'/bower_components',
connect.static('./bower_components')
),
connect.static(appConfig.app)
];
}
}
},
dist: {
options: {
open: true,
base: '<%= yeoman.dist %>'
}
}
},
// Make sure code styles are up to par and there are no obvious mistakes
jshint: {
options: {
jshintrc: '.jshintrc',
reporter: require('jshint-stylish')
},
all: {
src: [
'Gruntfile.js',
'<%= yeoman.app %>/scripts/{,*/}*.js'
]
},
test: {
options: {
jshintrc: 'test/.jshintrc'
},
src: ['test/spec/{,*/}*.js']
}
},
// Empties folders to start fresh
clean: {
dist: {
files: [{
dot: true,
src: [
'.tmp',
'<%= yeoman.dist %>/{,*/}*',
'!<%= yeoman.dist %>/.git{,*/}*'
]
}]
},
server: '.tmp'
},
// Add vendor prefixed styles
autoprefixer: {
options: {
browsers: ['last 1 version']
},
server: {
options: {
map: true,
},
files: [{
expand: true,
cwd: '.tmp/styles/',
src: '{,*/}*.css',
dest: '.tmp/styles/'
}]
},
dist: {
files: [{
expand: true,
cwd: '.tmp/styles/',
src: '{,*/}*.css',
dest: '.tmp/styles/'
}]
}
},
// Automatically inject Bower components into the app
wiredep: {
app: {
src: ['<%= yeoman.app %>/index.html'],
ignorePath: /\.\.\//
},
test: {
devDependencies: true,
src: '<%= karma.unit.configFile %>',
ignorePath: /\.\.\//,
fileTypes:{
js: {
block: /(([\s\t]*)\/{2}\s*?bower:\s*?(\S*))(\n|\r|.)*?(\/{2}\s*endbower)/gi,
detect: {
js: /'(.*\.js)'/gi
},
replace: {
js: '\'{{filePath}}\','
}
}
}
}
},
// Renames files for browser caching purposes
filerev: {
dist: {
src: [
'<%= yeoman.dist %>/scripts/{,*/}*.js',
'<%= yeoman.dist %>/styles/{,*/}*.css',
'<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',
'<%= yeoman.dist %>/styles/fonts/*'
]
}
},
// Reads HTML for usemin blocks to enable smart builds that automatically
// concat, minify and revision files. Creates configurations in memory so
// additional tasks can operate on them
useminPrepare: {
html: '<%= yeoman.app %>/index.html',
options: {
dest: '<%= yeoman.dist %>',
flow: {
html: {
steps: {
js: ['concat', 'uglifyjs'],
css: ['cssmin']
},
post: {}
}
}
}
},
// Performs rewrites based on filerev and the useminPrepare configuration
usemin: {
html: ['<%= yeoman.dist %>/{,*/}*.html'],
css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
options: {
assetsDirs: [
'<%= yeoman.dist %>',
'<%= yeoman.dist %>/images',
'<%= yeoman.dist %>/styles'
]
}
},
// The following *-min tasks will produce minified files in the dist folder
// By default, your `index.html`'s <!-- Usemin block --> will take care of
// minification. These next options are pre-configured if you do not wish
// to use the Usemin blocks.
// cssmin: {
// dist: {
// files: {
// '<%= yeoman.dist %>/styles/main.css': [
// '.tmp/styles/{,*/}*.css'
// ]
// }
// }
// },
// uglify: {
// dist: {
// files: {
// '<%= yeoman.dist %>/scripts/scripts.js': [
// '<%= yeoman.dist %>/scripts/scripts.js'
// ]
// }
// }
// },
// concat: {
// dist: {}
// },
imagemin: {
dist: {
files: [{
expand: true,
cwd: '<%= yeoman.app %>/images',
src: '{,*/}*.{png,jpg,jpeg,gif}',
dest: '<%= yeoman.dist %>/images'
}]
}
},
svgmin: {
dist: {
files: [{
expand: true,
cwd: '<%= yeoman.app %>/images',
src: '{,*/}*.svg',
dest: '<%= yeoman.dist %>/images'
}]
}
},
htmlmin: {
dist: {
options: {
collapseWhitespace: true,
conservativeCollapse: true,
collapseBooleanAttributes: true,
removeCommentsFromCDATA: true,
removeOptionalTags: true
},
files: [{
expand: true,
cwd: '<%= yeoman.dist %>',
src: ['*.html', 'views/{,*/}*.html'],
dest: '<%= yeoman.dist %>'
}]
}
},
// ng-annotate tries to make the code safe for minification automatically
// by using the Angular long form for dependency injection.
ngAnnotate: {
dist: {
files: [{
expand: true,
cwd: '.tmp/concat/scripts',
src: '*.js',
dest: '.tmp/concat/scripts'
}]
}
},
// Replace Google CDN references
cdnify: {
dist: {
html: ['<%= yeoman.dist %>/*.html']
}
},
// Copies remaining files to places other tasks can use
copy: {
dist: {
files: [{
expand: true,
dot: true,
cwd: '<%= yeoman.app %>',
dest: '<%= yeoman.dist %>',
src: [
'*.{ico,png,txt}',
'.htaccess',
'*.html',
'views/{,*/}*.html',
'images/{,*/}*.{webp}',
'styles/fonts/{,*/}*.*'
]
}, {
expand: true,
cwd: '.tmp/images',
dest: '<%= yeoman.dist %>/images',
src: ['generated/*']
}, {
expand: true,
cwd: 'bower_components/bootstrap/dist',
src: 'fonts/*',
dest: '<%= yeoman.dist %>'
}]
},
styles: {
expand: true,
cwd: '<%= yeoman.app %>/styles',
dest: '.tmp/styles/',
src: '{,*/}*.css'
}
},
// Run some tasks in parallel to speed up the build process
concurrent: {
server: [
'copy:styles'
],
test: [
'copy:styles'
],
dist: [
'copy:styles',
'imagemin',
'svgmin'
]
},
// Test settings
karma: {
unit: {
configFile: 'test/karma.conf.js',
singleRun: true
}
}
});
grunt.registerTask('serve', 'Compile then start a connect web server', function (target) {
if (target === 'dist') {
return grunt.task.run(['build', 'connect:dist:keepalive']);
}
grunt.task.run([
'clean:server',
'wiredep',
'concurrent:server',
'autoprefixer:server',
'connect:livereload',
'watch'
]);
});
grunt.registerTask('server', 'DEPRECATED TASK. Use the "serve" task instead', function (target) {
grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
grunt.task.run(['serve:' + target]);
});
grunt.registerTask('test', [
'clean:server',
'wiredep',
'concurrent:test',
'autoprefixer',
'connect:test',
'karma'
]);
grunt.registerTask('build', [
'clean:dist',
'wiredep',
'useminPrepare',
'concurrent:dist',
'autoprefixer',
'concat',
'ngAnnotate',
'copy:dist',
'cdnify',
'cssmin',
'uglify',
'filerev',
'usemin',
'htmlmin'
]);
grunt.registerTask('default', [
'newer:jshint',
'test',
'build'
]);
};
|
'use strict';
angular.module('pollariseApp', [
'ngCookies',
'ngResource',
'ngSanitize',
'ngRoute',
'btford.socket-io',
'ui.bootstrap'
])
.config(function ($routeProvider, $locationProvider, $httpProvider) {
$routeProvider
.otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(true);
$httpProvider.interceptors.push('authInterceptor');
})
.factory('authInterceptor', function ($rootScope, $q, $cookieStore, $location) {
return {
// Add authorization token to headers
request: function (config) {
config.headers = config.headers || {};
if ($cookieStore.get('token')) {
config.headers.Authorization = 'Bearer ' + $cookieStore.get('token');
}
return config;
},
// Intercept 401s and redirect you to login
responseError: function(response) {
if(response.status === 401) {
$location.path('/login');
// remove any stale tokens
$cookieStore.remove('token');
return $q.reject(response);
}
else {
return $q.reject(response);
}
}
};
})
.run(function ($rootScope, $location, Auth) {
// Redirect to login if route requires auth and you're not logged in
$rootScope.$on('$routeChangeStart', function (event, next) {
Auth.isLoggedInAsync(function(loggedIn) {
if (next.authenticate && !loggedIn) {
event.preventDefault();
$location.path('/login');
}
});
});
});
|
'use strict';
angular.module('quakeStatsApp')
.controller('DashboardCtrl', ['$scope', '$routeParams', 'gamesLog', 'qconsoleLog', 'KillsService', 'FlagsService',
function ($scope, $routeParams, gamesLog, qconsoleLog, KillsService, FlagsService) {
$scope.gameId = $routeParams.gameId;
$scope.flagsStats = {};
if (gamesLog.success === false) {
console.log('Cannot load games.log - you wil not be able to see kills stats');
return;
}
if (qconsoleLog.success === false) {
console.log('Cannot load qconsole - you wil not be able to see Flag stats');
return;
}
$scope.killsStats = KillsService.getKillsStats(gamesLog.result, $scope.gameId);
$scope.flagsStats = FlagsService.getFlagsStats(qconsoleLog.result, $scope.gameId);
$scope.playersCount = Object.keys($scope.killsStats.players).length;
$scope.dashboardItems = [
{
playersList: $scope.killsStats.topKillers,
title: 'Top Killer',
property: 'kills.length'
},
{
title: 'Wins',
isCustom: true,
template: '/templates/custom-dashboard-item-wins-tmpl.html',
type: 'neutral'
},
{
playersList: $scope.flagsStats.topOverallScorers,
title: 'Top Scorer',
property: 'value',
icon: 'medal_frags'
},
{
playersList: $scope.killsStats.topVictims,
title: 'Top Victim',
property: 'deaths.length',
type: 'bad'
},
{
playersList: $scope.killsStats.topHumilators,
title: 'Top Humiliator',
property: 'humiliations.length',
icon: 'gauntlet'
},
{
playersList: $scope.killsStats.topImmortal,
title: 'Top Immortal',
property: 'killsDeathDiff',
description: '/templates/description-dashboard-item-immortal-tmpl.html'
},
{
playersList: $scope.killsStats.topFifthColumns,
title: 'Top Fifth Column',
property: 'teammatesKills.length',
type: 'bad'
},
{
playersList: $scope.killsStats.topQScorer,
title: 'Best Quake Scorer',
property: 'qscore',
description: '/templates/custom-dashboard-item-qscore-tmpl.html'
},
{
playersList: $scope.flagsStats.topOverallFetchToCaptureRatioPlayers,
title: 'Top Fetch To Capture Ratio',
property: 'value',
description: '/templates/description-dashboard-item-fetch-to-capture-ratio-tmpl.html'
},
{
title: 'Total Players',
isCustom: true,
template: '/templates/custom-dashboard-item-players-count-tmpl.html',
type: 'neutral'
}
];
}]);
|
import React from 'react';
import {Router} from 'react-router';
import {Provider} from 'react-redux';
const Root = React.createClass({
render() {
const {store, history, routes} = this.props;
return (
<Provider store={store}>
<div className="root">
<Router history={history}>
{routes}
</Router>
</div>
</Provider>
);
}
});
export default Root;
|
'use strict';
angular.module('Authentication')
.factory('AuthenticationService',
['Base64', '$http', '$cookieStore', '$rootScope', '$timeout',
function (Base64, $http, $cookieStore, $rootScope) {
var service = {};
service.Login = function (username, password, callback) {
$http.post('http://localhost:8080/users/authenticate', { username: username, password: password })
.then(function successCallback(response) {
callback(response);
}, function errorCallback(response) {
console.log("ERROR " + response.status);
});
};
service.SetCredentials = function (username, password) {
var authdata = Base64.encode(username + ':' + password);
$rootScope.globals = {
currentUser: {
username: username,
authdata: authdata
}
};
$http.defaults.headers.common['Authorization'] = 'Basic ' + authdata; // jshint ignore:line
$cookieStore.put('globals', $rootScope.globals);
};
service.ClearCredentials = function () {
$rootScope.globals = {};
$cookieStore.remove('globals');
$http.defaults.headers.common.Authorization = 'Basic ';
};
return service;
}])
.factory('Base64', function () {
/* jshint ignore:start */
var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
return {
encode: function (input) {
var output = "";
var chr1, chr2, chr3 = "";
var enc1, enc2, enc3, enc4 = "";
var i = 0;
do {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
keyStr.charAt(enc1) +
keyStr.charAt(enc2) +
keyStr.charAt(enc3) +
keyStr.charAt(enc4);
chr1 = chr2 = chr3 = "";
enc1 = enc2 = enc3 = enc4 = "";
} while (i < input.length);
return output;
},
decode: function (input) {
var output = "";
var chr1, chr2, chr3 = "";
var enc1, enc2, enc3, enc4 = "";
var i = 0;
// remove all characters that are not A-Z, a-z, 0-9, +, /, or =
var base64test = /[^A-Za-z0-9\+\/\=]/g;
if (base64test.exec(input)) {
window.alert("There were invalid base64 characters in the input text.\n" +
"Valid base64 characters are A-Z, a-z, 0-9, '+', '/',and '='\n" +
"Expect errors in decoding.");
}
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
do {
enc1 = keyStr.indexOf(input.charAt(i++));
enc2 = keyStr.indexOf(input.charAt(i++));
enc3 = keyStr.indexOf(input.charAt(i++));
enc4 = keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
chr1 = chr2 = chr3 = "";
enc1 = enc2 = enc3 = enc4 = "";
} while (i < input.length);
return output;
}
};
});
|
'use strict';
/**
* @ngdoc function
* @name mapp.controller:MainCtrl
* @description
* # MainCtrl
* Controller of the app
*/
angular.module('app')
.filter('to_trusted', ['$sce', function ($sce) {
return function (text) {
return $sce.trustAsHtml(text);
};
}])
.controller('MainCtrl', function($scope,$http) {
//变量的申明
$scope.curTime = 0; //时间数字
$scope.timeRate = 0 //时间进度
let limitPoint = 5;// 每个模块下注的最大金额限制
let rate = 1; //筹码的倍率,默认是1
let myStake = 1 * rate; //默认的押注是 1;
let myStakeLeft = $(".chip-item").eq(0).offset().left//默认筹码的起始位置-x
let curStake = "chip-2";//选中筹码的类名
let myStakeTop = $(".chip-item").eq(0).offset().top //默认筹码的起始位置-y
//获取用户信息
socket.emit("connectGame");
socket.on("userinfo",function(user){
$scope.selfname = user.name;
$scope.selfimg = user.imgUrl;
$scope.selfbean = user.bean;
})
// 获取用户的下注数组
//var myChip = {};
socket.on("ChipArr",function(myChip,totalChip){
myChip = myChip;
totalChip = totalChip;
console.log(myChip);
$scope.selfPoint = myChip;
$scope.totalPoint = totalChip;
})
// $http({
// method: "GET",
// url: "../data/user.json",
// }).then(function(response){
// $scope.selfname = response.data.name;
// $scope.selfimg = response.data.imgUrl;
// $scope.selfbean = response.data.bean;
// },function(){
// console.log("获取用户头像和昵称失败");
//});
//设置当前页面类名
$scope.pageclass = "index-page";
//设置下注的类型
$scope.chipTypeArrOut = ["num-A","num-2","num-3","num-4","num-5","num-6","num-7","num-8","num-9","num-10","num-J","num-Q","num-K"];
$scope.chipTypeArrMid = ["suit-spade","suit-hearts","suit-plum","suit-square"]
$scope.chipTypeArrCen = ["suit-small","suit-big"]
//规则弹窗
$scope.hideRule = () => {
$(".game_rule_box").toggleClass("db");
}
//往期开奖
$scope.pastLottery = () => {
$(".panel-lottery").toggleClass("db");
$(".past-lottery i").toggleClass("arrow-up");
}
//充值弹窗
$scope.showCharge = () => {
$(".hidebg,.get-bean-box").addClass("db");
};
//隐藏充值弹窗
$scope.hideCharge = () => {
$(".hidebg,.get-bean-box").removeClass("db");
};
//修改筹码
$scope.changeChip = (event) => {
let _self = event.target;
$(".chip-item").removeClass("fadeUp");
$(_self).addClass("fadeUp");
myStakeLeft = $(_self).offset().left; //重置筹码的起始位置-x
myStakeTop = $(_self).offset().top; //重置筹码的起始位置-y
myStake = parseInt($(_self).attr("data-stake")*rate); //重置筹码的点数
};
// //读取当期的下注数据;
// let totalChip = {};
// $http({
// method: "GET",
// url: "../data/totalChip.json",
// }).then(function(response){
// totalChip = response.data;
// $scope.totalPoint = totalChip;
// },function(){
// console.log("获取用户下注信息失败");
// });
//读取我的下注数据;
// let myChip = {};
// $http({
// method: "GET",
// url: "../data/myChip.json",
// }).then(function(response){
// myChip = response.data;
// $scope.selfPoint = myChip;
// },function(){
// console.log("获取用户下注信息失败");
// });
//下注函数
let clickTimes = 0;//点击次数,赋值给新产生的移动筹码,方面移动和删除操作
$scope.ct = 0;
$scope.myClickChip = function(param){
console.log(param)
//alert()
chipFun(param);
//console.log(param)
};
socket.on("othersClip", function(param,stake){
console.log(param);
moveChipFun(param, stake);
})
var moveChipFun =function(param,stake){
//console.log(stake/rate);
var newSmallStakeEl = '<span style="position:fixed; top:'+myStakeTop+'px; left:'+myStakeLeft+'px" class="t'+clickTimes+' chip-item-small chip-'+(stake/rate)+'"></span>';
$(".chip-list").append(newSmallStakeEl);
let targetLeft = $("."+param).offset().left + $("."+param).width()/4;
let targetTop = $("."+param).offset().top + $("."+param).height()/4;
$(".t"+clickTimes).animate({"left":targetLeft,"top":targetTop},500,function(){
setTimeout(function(){
$(".chip-item-small").eq(0).remove();
})
})
}
var chipFun = function(param){
let myChip = $scope.selfPoint;
let totalChip = $scope.totalPoint;
socket.on("ChipArr",function(myChip,totalChip){
myChip = myChip;
totalChip = totalChip;
})
let curStake = myChip[param] + myStake;
let curTotal = totalChip[param] + myStake;
let JudgeGold = judgeGoldFun(); //判断玩家金币是否足够
let limitPoint = limitPointFun(curStake)//判断当前下注是否超出模块最大限制
if(!JudgeGold) {
$scope.showCharge();
return;
}
if(!limitPoint){
overLimitTsFun();
return;
}
myChip[param] = curStake; //点击一次下注,更新我的下注数组;
totalChip[param] = curTotal; //点击一次下注,更新当期总的下注数组;
moveChipFun(param,myStake);
console.log(myChip);
//更新用户筹码和下注数组
$scope.selfbean = $scope.selfbean - myStake;
socket.emit("userclip",param,myStake,curStake,curTotal);
//socket.emit("userclip")
}
/*判断玩家的金币是否足够*/
let judgeGoldFun = () => {
//mymoney = $scope.selfbean;
if(myStake > $scope.selfbean) //筹码大于玩家所有的金币
{
return false;
}
if(myStake <= $scope.selfbean) //筹码小于等于玩家所有的金币
{
return true;
}
}
//判断下注上限,玩家该点投注太多就不能投注
let limitPointFun = (points) => {
if(points > limitPoint)
{
return false; //我的当前点数大于最大限制点数,就不能投注
}
if(points <= limitPoint)
{
return true; //我的当前小于等于最大限制点数,就能投注
}
}
/*新一期将开始提示*/
let newOneTsFun = () => {
$(".ts").text("新一期即将开始,请去投注");
$(".ts").addClass("db");
setTimeout(function(){
$(".ts").removeClass("db");
},1000)
}
/*投注结束,准备开奖提示*/
let clipEndTsFun = () => {
$(".ts").text("即将揭晓开奖结果,请耐心等待");
$(".ts").addClass("db");
setTimeout(function(){
$(".ts").removeClass("db");
},1000)
}
/*超出每个模块的最大投注限额*/
let overLimitTsFun = () => {
$(".ts").text("单个模块最大投注不能超过"+limitPoint);
$(".ts").addClass("db");
setTimeout(function(){
$(".ts").removeClass("db");
},2000)
}
//读取游戏规则
$http({
method: "GET",
url: "../data/rule.txt",
}).then(function(response){
$scope.rule = response.data
},function(){
console.log("获取用户头像和昵称失败")
});
});
|
'use strict';
/**
* Dependencies
*/
const installScript = require('../');
const removeFile = require('fs').unlinkSync;
const writeFile = require('fs').writeFileSync;
const exec = require('mz/child_process').exec;
const join = require('path').join;
const test = require('ava');
/**
* Tests
*/
test ('build a script', function (t) {
let script = installScript({ name: 'ava' });
// save script
let path = join(__dirname, 'install-script.sh');
writeFile(path, script, 'utf-8');
// build docker container
let options = {
cwd: __dirname
};
return exec('docker build -t test-install-script .', options)
.then(function () {
// test if npm module installed
return exec('docker run test-install-script ava --help');
})
.then(function () {
removeFile(path);
});
});
|
function send_data() {
$.ajax({
url: "http://localhost:8181/tnfindhouse/changePass/get_newPass",
type: 'POST',
dataType: 'json',
enctype:'multipart/form-data',
data: $('#form_register').submit(),
encode:true,
success:function(data) {
if(!data.success){
if(data.errors){
$('#message').html(data.errors).addClass('alert alert-danger');
// $('#message').hide(1000);
$('#message').show(2000);
}
}else {
alert(data.message);
setTimeout(function() {
window.location.reload()
}, 400);
}
}
})
}
function send_login() {
$.ajax({
url: "http://localhost:8181/tnfindhouse/login/chk_login",
type: 'POST',
dataType: 'json',
data: $('#form_login').serialize(),
encode:true,
success:function(data) {
if(!data.success){
if(data.errors){
$('#error').html(data.errors).addClass('alert alert-danger');
// $('#message').hide(1000);
$('#error').show(2000);
}
}else {
alert(data.message);
setTimeout(function() {
window.location.reload()
}, 400);
}
}
})
}
function send_forgot() {
$.ajax({
url: "http://localhost:8181/tnfindhouse/login/chk_forgot",
type: 'POST',
dataType: 'json',
data: $('#form_forgot').serialize(),
encode:true,
success:function(data) {
if(!data.success){
if(data.errors){
$('#error').html(data.errors).addClass('alert alert-danger');
// $('#message').hide(1000);
$('#error').show(2000);
}
}else {
alert(data.message);
setTimeout(function() {
window.location.reload()
}, 400);
}
}
})
}
|
module.exports ={
methods: {
getMessage: require('../methods/get-message'),
validateRemote: require('../methods/validate-remote'),
validate: require('../methods/validate'),
addFormError: require('../methods/add-form-error'),
removeFormError: require('../methods/remove-form-error'),
inForm: require('../methods/in-form'),
triggerOn: require('../methods/trigger-on'),
handleTriggeredFields: require('../methods/handle-triggered-fields'),
getForm: require('../methods/get-form'),
getField: require('../methods/get-field'),
dispatch: require('../methods/dispatch')
}
}
|
import React from "react";
import App from "../src/components/App";
export default function Home() {
return <App />;
}
|
'use strict';
describe('Filter: commitSummary', function () {
// load the filter's module
beforeEach(module('slipflowApp'));
// initialize a new instance of the filter before each test
var commitSummary;
beforeEach(inject(function ($filter) {
commitSummary = $filter('commitSummary');
}));
it('should return the commit summary', function () {
var text = 'This is a commit summary.\n\nThis is the commit body.';
expect(commitSummary(text)).toBe('This is a commit summary.');
});
});
|
import url from 'url';
import Utils from './Utils';
import { request } from '../dependencies/request';
import RequestError from './RequestError';
const { getHeaders } = Utils;
/**
* Get range information from either request headers or query parameters.
* @private
* @param {Object} req - HTTP request.
* @param {Object} query - Query string data.
* @returns {Object} Range information or null if none.
*/
export const getRange = (req, query) => {
const { headers } = req;
const range = headers.range || query.range;
if (!range) {
return null;
}
const rangeInfo = /([a-z]+)+\W*(\d*)-(\d*)/gi.exec(range);
return {
unit: rangeInfo[1],
start: +rangeInfo[2] || 0,
end: +rangeInfo[3] || undefined,
};
};
/**
* @private
* @param {String} title - Log section title.
* @returns {String} Formatted log header.
*/
const getLogHeader = (title) => {
const header = `=============== ${title.toUpperCase()} ===============`;
return process.env.isProduction ? header : `\n${header}\n`;
};
/**
* Log request options.
* @private
* @param {Object} req - HTTP request.
* @param {Object} config - Orchestrator configuration.
* @param {Object} options - Request options.
*/
const logRequest = (req, config, options) => {
if (config.log.showCredentialsAsClearText) {
req.log.info(options, getLogHeader('request'));
} else {
req.log.info({
...options,
auth: {
user: '********',
pass: '********',
},
}, getLogHeader('request'));
}
};
/**
* @private
* Get login path information.
* @param {Object} config - Orchestrator config.
* @returns {String} Login url.
*/
const getLoginPath = config => `${config.loginPath}?service=${config.cas.servicePrefix}${config.cas.paths.validate}`;
/**
* Handles response standardisation as well as http responses and requests.
* @class
* @param {Object} req - {@link https://expressjs.com/en/4x/api.html#req HTTP request}.
* @param {Object} res - {@link https://expressjs.com/en/4x/api.html#res HTTP response}.
* @param {Config} config - Orchestrator configuration.
* @throws {Error} If `req`, `res` or `config` argument is null.
*/
export class ResponseHelper {
constructor(req, res, config) {
this.req = req;
this.res = res;
this.config = config;
}
/**
* Add auth information to HTTP request options based on auth method of the called URL.
* @private
* @param {Object} options - HTTP request options.
* @param {Boolean} isFirstAttempt - True if is first HTTP call.
* @returns {Promise} Promise represents requests options with auth info.
*/
appendAuthOptions = async (options, isFirstAttempt) => {
const authPattern = this.config.authPatterns.find(({ path }) => options.url.match(new RegExp(path)));
if (authPattern) {
this.req.session.apiSessionUrl = authPattern.sessionUrl;
this.req.session.path = authPattern.path;
this.req.session.targetService = authPattern.targetService;
const Plugin = authPattern.plugin;
return (new Plugin()).authenticate(this.req.session, options, isFirstAttempt);
}
return options;
}
/**
* Format options for API call.
* @private
* @async
* @param {Object} options - Request options.
* @param {Boolean} isFirstAttempt - True if is first HTTP call.
* @returns {Promise} Promise object represents request options.
*/
formatRequestOptions = (options, isFirstAttempt) => {
const { body, headers = getHeaders(), url } = options;
return this.appendAuthOptions({
...options,
body: body && typeof body === 'object' ? JSON.stringify(body) : body,
headers,
url: /^.+:\/\//.test(url) ? url : `${this.config.apiUrl}${url}`,
}, isFirstAttempt);
}
/**
* Extract meta-data from response.
* @private
* @param {Object} response - HTTP response.
* @returns {Object} Response meta data
*/
getResponseMetaData = (response) => {
const meta = {
debug: {
'x-TempsMs': this.callDuration,
},
status: response.statusCode,
};
this.config.customHeaders.forEach(({ header, property }) => {
meta[property || header] = response.headers[header];
});
return meta;
}
/**
* Extract response data from response.
* @private
* @param {Object} response - HTTP response.
* @returns {Object} Response data.
*/
getResponseData = (response) => {
let data;
try {
data = JSON.parse(response.body);
} catch (error) {
data = response.body;
}
if (this.config.appendMetaData) {
const meta = this.getResponseMetaData(response);
// Array and primitives
if (Array.isArray(data) || !(data instanceof Object)) {
return { data, meta };
}
return { ...data, meta };
}
return data;
}
/**
* Get file from server and send it as response.
* @param {Object} options - Request options.
* @param {Object} options.body - Request body.
* @param {('DELETE'|'GET'|'POST'|'PUT')} options.method - Request method.
* @param {String} options.url - Request URL.
* @param {Object} [options.headers=getHeaders()] - Request headers.
* @param {Boolean} [isFirstAttempt=true] - True if is first HTTP call.
* @returns {Promise} Promise object represents server response.
*/
fetch = (options, isFirstAttempt = true) => new Promise(async (resolve, reject) => {
const requestOptions = await this.formatRequestOptions(options, isFirstAttempt);
logRequest(this.req, this.config, requestOptions);
this.callTimestamp = +(new Date());
request(requestOptions, async (error, response) => {
this.callDuration = +(new Date()) - this.callTimestamp;
const isUnauthorized = () => response.statusCode === 401;
const isStatusOk = () => response.statusCode >= 200 && response.statusCode < 300;
if (error) {
this.req.log.error(error, getLogHeader('error'));
reject(new RequestError(error, 500));
} else if (isStatusOk()) {
const data = this.getResponseData(response);
this.req.log.debug(data, getLogHeader('response'));
resolve(data);
} else if (isUnauthorized()) {
if (isFirstAttempt) {
try {
resolve(await this.fetch(options, false));
} catch (error) {
reject(error);
}
} else {
this.req.log.error('401 - Unauthorized access', getLogHeader('error'));
reject(new RequestError({ loginPath: getLoginPath(this.config) }, 401));
}
} else {
this.req.log.error(response.body || response, getLogHeader('error'));
reject(new RequestError(response.body || response, response.statusCode || 500));
}
});
})
/**
* Get file from server and send it as response.
* @async
* @param {Object} options - Request options.
* @param {String} options.url - URL to access the file.
* @param {Object} [options.headers=getHeaders()] - Request headers.
*/
getFile = async (options) => {
const requestOptions = await this.formatRequestOptions(options);
logRequest(this.req, this.config, requestOptions);
Object.keys(requestOptions.headers).forEach(key => this.res.set(key, requestOptions.headers[key]));
request.get(requestOptions).pipe(this.res);
}
/**
* Creates a usable object from the request URL parameters.
* @returns {Object} Parameters in the request URL.
*/
getQueryParameters = () => url.parse(this.req.url, true).query
/**
* Creates a usable object from the request's URL parameters and body.
* @returns {Object} Parameters in the request URL and body.
*/
getRequestParameters = () => ({
...this.getQueryParameters(),
...this.req.body,
})
/**
* Set error status code and send response data.
* @param {Object|String} error - Error encountered.
* @param {Number} [error.statusCode=500] - Error status code (3xx-5xx).
* @param {String} [error.message=error] - Error message. Value of error if it's a string.
*/
handleError = (error) => {
const ErrorFormatter = this.config.errorFormatter;
const errorData = ErrorFormatter ? (new ErrorFormatter()).format(error) : error.message || error;
this.res.status(error.statusCode || 500).send(errorData);
}
/**
* Set response headers, status code and send response data.
* @param {Object} data - Data to be sent as response.
* @param {Object} [options={}] - Additional options for response.
* @param {Object} [options.headers={}] - Response headers.
* @param {Boolean} [options.formatData=true] - True to standardise response format.
*/
handleResponse = (data, options = {}) => {
const { formatData = true, headers = {} } = options;
const range = getRange(this.req, this.getQueryParameters());
Object.keys(headers).forEach(key => this.res.set(key, headers[key]));
if (range) {
const key = Object.keys(data)[0];
const values = Object.values(data)[0];
const size = values.length;
const { start, end = size - 1, unit } = range;
if (start > end || start >= size) {
this.res.set('Content-Range', `${unit} */${size}`);
this.handleError({ statusCode: 416, message: `Cannot get range ${start}-${end} of ${size}` });
return;
}
if (end - start < size - 1) {
this.res.set('Content-Range', `${unit} ${start}-${end}/${size}`);
const partialData = { [key]: values.splice(start, end) };
const responseData = formatData ? this.formatResponse(partialData) : partialData;
this.res.status(206).send(responseData);
return;
}
this.res.set('Content-Range', `${unit} 0-${size - 1}/${size}`);
}
this.res.status(200).send(formatData ? this.formatResponse(data) : data);
}
/**
* Standardize response format.
* @private
* @param {Object} data={} - Response data.
* @returns {Object} Formatted response data.
*/
formatResponse = (data = {}) => {
const ResponseFormatter = this.config.responseFormatter;
if (ResponseFormatter) {
return (new ResponseFormatter()).format(data);
}
return data;
}
}
|
(function(d3, fc) {
'use strict';
var chartConfig = [
{label: 'y orient', value: 'right'},
{label: 'x orient', value: 'bottom'},
{label: 'y label', value: 'sin'},
{label: 'x label', value: 'value'},
{label: 'chart label', value: 'A sine wave'},
{label: 'margin', value: JSON.stringify({bottom: 40, right: 40, top: 20})},
{label: 'x axis baseline', value: ''},
{label: 'y axis baseline', value: ''},
{label: 'ordinal', value: false, type: 'checkbox'}
];
var chartContainer = d3.select('#chart');
function render() {
renderControls();
renderChart();
}
function updateModel(d) {
d.value = this.type === 'checkbox' ? this.checked : this.value;
renderChart();
}
function renderControls() {
var container = d3.select('#controls');
var yOrientationConfig = container.selectAll('tr')
.data(chartConfig);
var row = yOrientationConfig.enter()
.append('tr');
row.append('th')
.append('span')
.html(function(d) { return d.label; });
row.append('td')
.append('input')
.attr('type', function(d) { return d.type || 'text'; })
.on('blur', updateModel)
.on('click', updateModel);
yOrientationConfig.select('input')
.attr('value', function(d) { return d.value; });
}
function renderChart() {
var data;
var isOrdinal = chartConfig[8].value;
if (isOrdinal) {
data = [
{name: 'bob', size: 45},
{name: 'bill', size: 12},
{name: 'frank', size: 33}
];
} else {
data = d3.range(20).map(function(d) {
return {
x: d,
y: (Math.sin(d) + 1.1)
};
});
}
var chart = fc.chart.cartesianChart(
isOrdinal ? d3.scale.ordinal() : d3.scale.linear(),
d3.scale.linear())
.xDomain(isOrdinal ? data.map(function(d) { return d.name; }) : fc.util.extent(data, 'x'))
.yDomain(isOrdinal ? [0, 50] : fc.util.extent(data, 'y'))
.yOrient(chartConfig[0].value)
.xOrient(chartConfig[1].value)
.yLabel(chartConfig[2].value)
.xLabel(chartConfig[3].value)
.chartLabel(chartConfig[4].value)
.margin(JSON.parse(chartConfig[5].value));
if (chartConfig[6].value) {
chart.xBaseline(chartConfig[6].value);
}
if (chartConfig[7].value) {
chart.yBaseline(chartConfig[7].value);
}
var bar = fc.series.bar()
.xValue(function(d) { return isOrdinal ? d.name : d.x; })
.yValue(function(d) { return isOrdinal ? d.size : d.y; });
chart.plotArea(bar);
chartContainer.datum(data)
.call(chart);
}
render();
})(d3, fc);
|
const http = require("http");
server = http.createServer((request, response) => {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end("Hello, Asynchronites!");
});
server.listen(8000);
setInterval(()=> {console.log('still listening...');}, 2000);
|
'use strict';
describe('Directive: ngCard', function () {
var scope;
var $compile;
var isolatedScope;
beforeEach(angular.mock.module('ngCard'));
beforeEach(inject(function($injector) {
$compile = $injector.get('$compile');
scope = $injector.get('$rootScope').$new();
}));
describe('default', function() {
var element;
var template = '<ng-card ng-model="card"></ng-card>';
beforeEach(function () {
scope.card = {};
scope.form = {};
element = $compile(template)(scope);
scope.$apply();
isolatedScope = element.isolateScope();
});
afterEach(function () {
scope.$destroy();
});
it('should set default placeholder', function() {
expect(isolatedScope.placeholder).toEqual('Card number');
});
});
});
|
/**
*
*/
goog.require('Vizi.Service');
goog.provide('Vizi.TweenService');
/**
* The TweenService.
*
* @extends {Vizi.Service}
*/
Vizi.TweenService = function() {};
goog.inherits(Vizi.TweenService, Vizi.Service);
//---------------------------------------------------------------------
// Initialization/Termination
//---------------------------------------------------------------------
/**
* Initializes the events system.
*/
Vizi.TweenService.prototype.initialize = function(param) {};
/**
* Terminates the events world.
*/
Vizi.TweenService.prototype.terminate = function() {};
/**
* Updates the TweenService.
*/
Vizi.TweenService.prototype.update = function()
{
if (window.TWEEN)
TWEEN.update();
}
|
const {resolve, join} = require('path')
const webpack = require('webpack')
module.exports = env => {
const libraryName = 'console.image'
const addPlugin = (add, plugin) => add ? plugin : undefined
const ifProd = plugin => addPlugin(env.prod, plugin)
const ifDev = plugin => addPlugin(env.dev, plugin)
const removeEmpty = array => array.filter(i => !!i)
return {
devtool: env.prod ? 'source-map' : 'eval',
entry: removeEmpty([
'./src/index.js',
]),
context: resolve(__dirname, ''),
output: {
path: join(__dirname, 'dist'),
filename: libraryName + (env.prod ? '.min.js' : '.js'),
publicPath: '',
library: libraryName,
libraryTarget: 'umd',
umdNamedDefine: true
},
module: {
loaders: [
{ test: /\.js$/, loaders: ['babel-loader'], exclude: /node_modules/ },
{ test: /\.json$/, loaders: ["json-loader"], exclude: /node_modules/},
]
},
plugins: removeEmpty([
ifProd(new webpack.optimize.DedupePlugin()),
ifProd(new webpack.LoaderOptionsPlugin({
minimize : true,
debug: false
})),
ifProd(new webpack.optimize.UglifyJsPlugin({
compress: {
screw_ie8: true,
warnings: false
}
})),
]),
resolve: {
extensions: ['.js', '.json']
}
}
}
|
// Generated by CoffeeScript 1.6.3
(function() {
var Handlebars, fs, methods, _, _names;
Handlebars = require("handlebars");
fs = require("fs");
_ = require("underscore");
_names = ["Year", "Month", "Week", "Day", "Hour", "Minute", "Second"];
methods = _.map(_names, function(aName) {
return {
method: "endOf" + aName,
unit: aName.toLowerCase()
};
});
fs.readFile("./endspec.hbs", "utf8", function(err, cont) {
var locals, rendered, tmpl;
tmpl = Handlebars.compile(cont);
locals = {
toTest: methods
};
rendered = tmpl(locals);
return fs.writeFile("./enders.coffee", rendered, function(err) {
return console.log("written");
});
});
}).call(this);
|
var Some = require('./option').Some;
var None = require('./option').None;
function Iter(values) {
this.values = values !== undefined ? values : [];
this._count = this.values && this.values.length !== undefined ? this.values.length : 0;
this._curr = 0;
}
Iter.prototype.next = function() {
var val = this.values[_curr++];
return val !== undefined ? Some(val) : None;
}
Iter.prototype.count = function() {
return _count;
}
Iter.prototype.last = function() {
var val = this.values[_count-1];
return val !== undefined ? Some(val) : None;
}
Iter.prototype.nth = function(n) {
var val = this.values[n];
return val !== undefined ? Some(val) : None;
}
Iter.prototype.chain = function(other) {
return new Iter(this.values.concat(other.values));
}
exports.Iter = Iter;
|
var TaskList = require('./routes/tasklist');
var taskList = new TaskList('mongodb://shopapp:shopapp123@ds041167.mongolab.com:41167/shopapp');
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var complete = require('./routes/complete');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
//added for functionality to TaskList.JS Model
app.get('/', taskList.showTasks.bind(taskList));
app.get('/complete', taskList.showCompleteTasks.bind(taskList));
app.post('/addtask', taskList.addTask.bind(taskList));
app.post('/completetask', taskList.completeTask.bind(taskList));
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
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) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
|
// connect
// Simple webserver with Grunt
module.exports = {
server: {
options: {
port: 9001,
//base: 'www-root',
hostname: 'localhost'
},
open: {
server: {
url: 'http://localhost:<%= connect.options.port %>/index.html'
}
}
}
};
|
import { expect } from 'chai';
import { describe, it } from 'mocha';
import files from '../../src/core/files'
import fs from 'fs-extra';
import path from 'path';
import sinon from 'sinon';
describe('files', () => {
const testDataDir = path.join('test-data', 'core', 'files');
const testDataDirRegex = /xipcode\/test-data\/core\/files/;
const buildTestOutputDir = './build/test-output';
let sandbox;
beforeEach(() => {
sandbox = sinon.sandbox.create();
});
afterEach(() => {
sandbox.restore();
});
describe('findFileInPath', () => {
it('requires fileName', function() {
expect(() => { files.findFileInPath() }).throw('fileName must be defined');
});
it('requires startPath', function() {
expect(() => { files.findFileInPath('file.txt') }).throw('startPath must be defined');
});
it('returns true for file found in start path', function() {
const searchPath = path.join(testDataDir, 'testDirectory');
const foundFile = files.findFileInPath('file2.txt', searchPath);
expect(foundFile).not.equal(undefined);
const match = /xipcode\/test-data\/core\/files\/testDirectory\/file2.txt/.test(foundFile);
expect(match).equal(true);
});
it('returns true for file found in start path\'s parent', function() {
const searchPath = path.join(testDataDir, 'testDirectory');
const foundFile = files.findFileInPath('file1.txt', searchPath);
expect(foundFile).not.equal(undefined);
const match = /xipcode\/test-data\/core\/files\/file1.txt/.test(foundFile);
expect(match).equal(true);
});
it('throws an exception for file not found', function() {
const searchPath = path.join(testDataDir, 'testDirectory');
const fileName = 'not-a-file-that-will-exist-anywhere';
const expectedMessage = 'File \'not-a-file-that-will-exist-anywhere\' not found';
expect(() => files.findFileInPath(fileName, searchPath)).throw(expectedMessage);
});
});
describe('updateJsonFile', () => {
it('updates a kvp in a given json file', () => {
const jsonFile = path.join(testDataDir, 'test.json');
const testJsonFile = path.join(buildTestOutputDir, 'test.json');
fs.copySync(jsonFile, testJsonFile);
const oldValue = fs.readJSONSync(testJsonFile).someKey;
expect(oldValue).to.equal('someValue');
files.updateJsonFile({
file: testJsonFile,
key: 'someKey',
value: 'newValue'
});
const newValue = fs.readJSONSync(testJsonFile).someKey;
expect(newValue).to.equal('newValue');
});
});
describe('findCodebaseRoot', () => {
it('requires startPath', function() {
expect(() => { files.findCodebaseRoot(undefined) }).throw('startPath must be defined');
});
it('finds codebase root from codebase root', function() {
const codebaseRoot = files.findCodebaseRoot(testDataDir);
expect(testDataDirRegex.test(codebaseRoot)).equals(true);
});
it('finds codebase root from codebase subfolder', function() {
const testDirectory = path.join(testDataDir, 'testDirectory');
const codebaseRoot = files.findCodebaseRoot(testDirectory);
expect(testDataDirRegex.test(codebaseRoot)).equals(true);
});
});
describe('isFileNewer', () => {
it('requires file1', function() {
expect(() => { files.isFileNewer(undefined) }).throw('file1 must be defined');
});
it('requires file2', function() {
expect(() => { files.isFileNewer('file1', undefined) }).throw('file2 must be defined');
});
it('return true for newer file', function() {
const stub = sandbox.stub(fs, 'statSync');
stub.withArgs('file1').returns({ ctime: new Date(100) });
stub.withArgs('file2').returns({ ctime: new Date(50) });
expect(files.isFileNewer('file1', 'file2')).equal(true);
});
it('return false for older file', function() {
const stub = sandbox.stub(fs, 'statSync');
stub.withArgs('file1').returns({ ctime: new Date(50) });
stub.withArgs('file2').returns({ ctime: new Date(100) });
expect(files.isFileNewer('file1', 'file2')).equal(false);
});
it('return false for same timestamp file', function() {
const stub = sandbox.stub(fs, 'statSync');
stub.withArgs('file1').returns({ ctime: new Date(100) });
stub.withArgs('file2').returns({ ctime: new Date(100) });
expect(files.isFileNewer('file1', 'file2')).equal(false);
});
});
describe('walkDirectory', () => {
const walkTestDirectory = path.join(testDataDir, 'walkTestDirectory');
it('recursively lists all files in directory', () => {
const allFiles = files.walkDirectory(walkTestDirectory);
expect(allFiles.length).to.equal(7);
expect(allFiles).to.eql([
'test-data/core/files/walkTestDirectory/top1/middle1/bottom1/bottomFile1',
'test-data/core/files/walkTestDirectory/top1/middle1/middleFile1',
'test-data/core/files/walkTestDirectory/top1/middle1/middleFile2',
'test-data/core/files/walkTestDirectory/top1/topFile1',
'test-data/core/files/walkTestDirectory/top2/middle2/middleFile1',
'test-data/core/files/walkTestDirectory/top2/middle2/middleFile2',
'test-data/core/files/walkTestDirectory/top2/topFile1'
]);
});
});
});
|
const config = require('../../config')
const uFuns = {}
uFuns.setCookies = function setCookies(target, options) {
const keys = Object.keys(options)
keys.map((cookie) => {
typeof target.cookie === 'function' && target.cookie(cookie, options[cookie], {
maxAge: 30 * 24 * 60 * 60 * 1000,
domain: config.app.cookie_domain,
httpOnly: true
})
})
}
uFuns.clearCookies = function clearCookies(target, options) {
const keys = Object.keys(options)
keys.map((cookie) => {
if (typeof target.cookie === 'function') {
if (Array.isArray(options[cookie])) {
options[cookie].map((item) => {
target.clearCookie(cookie, item)
})
} else {
target.clearCookie(cookie, options[cookie])
}
}
})
}
module.exports = uFuns
|
import Ember from 'ember';
import MarkerCollectionLayer from 'ember-leaflet/layers/marker-collection';
import EmptyLayer from 'ember-leaflet/layers/empty';
import { moduleForComponent, test } from 'ember-qunit';
import locationsEqual from '../../helpers/locations-equal';
import locations from '../../helpers/locations';
var component, collection, content;
moduleForComponent('leaflet-map', 'MarkerCollectionLayer', {
beforeEach: function() {
content = Ember.A([
Ember.Object.create({location: locations.nyc}),
Ember.Object.create({location: locations.sf}),
Ember.Object.create({location: locations.chicago}),
Ember.Object.create({location: null})
]);
var collectionClass = MarkerCollectionLayer.extend({
content: content
});
component = this.subject();
component.set('childLayers', [collectionClass]);
this.render();
collection = component._childLayers[0];
}
});
test('child layers are instantiated and added', function(assert) {
assert.equal(collection._childLayers.length, 4,
'three child layers should be created');
});
test('item with location should be added to map', function(assert) {
var firstMarker = collection._childLayers[0];
assert.equal(firstMarker._layer._map, component._layer);
locationsEqual(assert, firstMarker.get('content.location'), locations.nyc);
locationsEqual(assert, firstMarker._layer.getLatLng(), locations.nyc);
});
test('item with null location should be created but not added to map',
function(assert) {
var fourthMarker = collection._childLayers[3];
assert.equal(fourthMarker.get('content.location'), null);
assert.equal(fourthMarker._layer, null);
});
test('adding an object', function(assert) {
content.addObject({location: locations.paris});
assert.equal(collection._childLayers.length, 5);
locationsEqual(assert, collection._childLayers[4].get('content.location'),
locations.paris);
locationsEqual(assert, collection._childLayers[4]._layer.getLatLng(),
locations.paris);
});
test('removing an object', function(assert) {
Ember.run(function() {
content.removeObject(content[1]);
});
assert.equal(collection._childLayers.length, 3);
locationsEqual(assert, collection._childLayers[1].get('content.location'),
locations.chicago);
locationsEqual(assert, collection._childLayers[1]._layer.getLatLng(),
locations.chicago);
});
test('changing object\'s location updates marker', function(assert) {
content.objectAt(0).set('location', locations.paris);
locationsEqual(assert, collection._childLayers[0].get('location'),
locations.paris);
locationsEqual(assert, collection._childLayers[0]._layer.getLatLng(),
locations.paris);
});
test('nullifying object\'s location removes marker', function(assert) {
content.objectAt(0).set('location', null);
assert.equal(collection._childLayers[0].get('location'), null,
'Location should be nullified.');
assert.equal(collection._childLayers[0]._layer, null,
'Marker should be removed.');
assert.equal(Object.keys(component._layer._layers).length, 2, 'two markers left');
});
test('un-nullify objects\' location', function(assert) {
content.objectAt(3).set('location', locations.chicago);
locationsEqual(assert, collection._childLayers[3].get('location'),
locations.chicago, 'Location should be updated');
assert.ok(!!collection._childLayers[3]._layer, 'Marker should be added to map');
assert.equal(collection._childLayers[3]._layer._map, component._layer);
assert.equal(Object.keys(component._layer._layers).length, 4, 'four markers now');
});
test('changing content', function(assert) {
var newContent = Ember.A([
{location: locations.paris},
{location: locations.nyc}]);
Ember.run(function() {
collection.set('content', newContent);
});
assert.equal(collection._childLayers.length, 2);
locationsEqual(assert, collection._childLayers[0].get('content.location'),
locations.paris);
locationsEqual(assert, collection._childLayers[1].get('content.location'),
locations.nyc);
});
test('destroy', function(assert) {
Ember.run(function() {
collection._destroyLayer();
});
assert.equal(collection._childLayers.length, 0);
});
var controller;
moduleForComponent('leaflet-map', 'MarkerCollectionLayer and Controller', {
beforeEach: function() {
content = Ember.A([
Ember.Object.create({location: locations.nyc}),
Ember.Object.create({location: locations.sf}),
Ember.Object.create({location: locations.chicago}),
Ember.Object.create({location: null})
]);
controller = Ember.ArrayProxy.create({
content: content
});
var collectionClass = MarkerCollectionLayer.extend({
contentBinding: 'controller'
});
component = this.subject();
component.setProperties({
controller: controller,
childLayers: [collectionClass]
});
this.render();
collection = component._childLayers[0];
}
});
test('content is bound', function(assert) {
assert.strictEqual(controller.get('content'), content,
'controller content should be original array');
assert.strictEqual(collection.get('content'), controller,
'collection should refer to controller');
assert.strictEqual(collection.get('content.content'), content,
'collection content should be original array');
});
test('child layers are instantiated and added', function(assert) {
assert.equal(collection._childLayers.length, 4,
'three child layers should be created');
});
test('item with location should be added to map', function(assert) {
var firstMarker = collection._childLayers[0];
assert.equal(firstMarker._layer._map, component._layer);
locationsEqual(assert, firstMarker.get('content.location'), locations.nyc);
locationsEqual(assert, firstMarker._layer.getLatLng(), locations.nyc);
});
test('item with null location should be created but not added to map',
function(assert) {
var fourthMarker = collection._childLayers[3];
assert.equal(fourthMarker.get('content.location'), null);
assert.equal(fourthMarker._layer, null);
});
test('adding an object', function(assert) {
content.addObject({location: locations.paris});
assert.equal(collection._childLayers.length, 5);
locationsEqual(assert, collection._childLayers[4].get('content.location'),
locations.paris);
locationsEqual(assert, collection._childLayers[4]._layer.getLatLng(),
locations.paris);
});
test('removing an object', function(assert) {
Ember.run(function() {
content.removeObject(content[1]);
});
assert.equal(collection._childLayers.length, 3);
locationsEqual(assert, collection._childLayers[1].get('content.location'),
locations.chicago);
locationsEqual(assert, collection._childLayers[1]._layer.getLatLng(),
locations.chicago);
});
test('changing object\'s location updates marker', function(assert) {
content.objectAt(0).set('location', locations.paris);
locationsEqual(assert, collection._childLayers[0].get('location'),
locations.paris);
locationsEqual(assert, collection._childLayers[0]._layer.getLatLng(),
locations.paris);
});
test('nullifying object\'s location removes marker', function(assert) {
content.objectAt(0).set('location', null);
assert.equal(collection._childLayers[0].get('location'), null,
'Location should be nullified.');
assert.equal(collection._childLayers[0]._layer, null,
'Marker should be removed.');
});
test('un-nullify objects\' location', function(assert) {
content.objectAt(3).set('location', locations.chicago);
locationsEqual(assert, collection._childLayers[3].get('location'),
locations.chicago, 'Location should be updated');
assert.ok(!!collection._childLayers[3]._layer, 'Marker should be added to map');
assert.equal(collection._childLayers[3]._layer._map, component._layer);
});
test('changing content', function(assert) {
var newContent = Ember.A([
{location: locations.paris},
{location: locations.nyc}]);
Ember.run(function() {
controller.set('content', newContent);
});
assert.equal(collection._childLayers.length, 2);
locationsEqual(assert, collection._childLayers[0].get('content.location'),
locations.paris);
locationsEqual(assert, collection._childLayers[1].get('content.location'),
locations.nyc);
});
|
'use strict';
describe('Controller: CourseSearchCtrl', function () {
// load the controller's module
beforeEach(module('venueApp'));
var CourseSearchCtrl, scope;
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
CourseSearchCtrl = $controller('CourseSearchCtrl', {
$scope: scope
});
}));
it('should ...', function () {
expect(1).to.equal(1);
});
});
|
import styled from 'styled-components';
const Column4 = styled.div`
display: flex;
width: 20%;
`;
export default Column4;
|
/**
* Trimmed service objects mock data getters
*/
var MockHelpers = ( function() {
return {
getShowsMockData: _getShowsMockData,
getShowMockData: _getShowMockData,
getFirebaseUserData: _getFirebaseUserData,
getTvSearchResultsMockData: _getTvSearchResultsMockData,
getUserFavoritesMockData: _getUserFavoritesMockData,
getUserProfileMockData: _getUserProfileMockData
};
/**
* Returns a single-item result object mock data for shows list
*
*/
function _getShowsMockData() {
return {
"page": 1,
"results": [
{
"backdrop_path": "/kohPYEYHuQLWX3gjchmrWWOEycD.jpg",
"id": 62425,
"overview": "The six-person crew of a derelict spaceship awakens from stasis in the farthest reaches of space. Their memories wiped clean, they have no recollection of who they are or how they got on board. The only clue to their identities is a cargo bay full of weaponry and a destination: a remote mining colony that is about to become a war zone. With no idea whose side they are on, they face a deadly decision. Will these amnesiacs turn their backs on history, or will their pasts catch up with them?",
"name": "Dark Matter"
},
{
"backdrop_path": "/jXpndJTekLFYcx3xX0H3sDqFnJU.jpg",
"id": 62196,
"overview": "A young woman is recruited into a secret government agency to be “stitched” into the minds of the recently deceased, using their memories to investigate murders.",
"name": "Stitchers"
}
],
"total_pages": 10,
"total_results": 184
};
}
/**
*
*/
function _getShowMockData() {
return {
"backdrop_path": "/bzoZjhbpriBT2N5kwgK0weUfVOX.jpg",
"id": 1396,
"name": "Breaking Bad",
"overview": "Breaking Bad is an American crime drama television series created and produced by Vince Gilligan. Set and produced in Albuquerque, New Mexico, Breaking Bad is the story of Walter White, a struggling high school chemistry teacher who is diagnosed with inoperable lung cancer at the beginning of the series. He turns to a life of crime, producing and selling methamphetamine, in order to secure his family's financial future before he dies, teaming with his former student, Jesse Pinkman. Heavily serialized, the series is known for positioning its characters in seemingly inextricable corners and has been labeled a contemporary western by its creator.",
"networks": [
{
"id": 49,
"name": "HBO"
}
]
};
}
/**
*
*/
function _getTvSearchResultsMockData() {
return {
"page": 1,
"results": [
{
"backdrop_path": "/rWY8nL277IijjUDGoyrscdPjDiR.jpg",
"id": 40417,
"overview": "Leyla ile Mecnun is a Turkish television comedy series. The show is set in Istanbul, Turkey and premiered in 2011 on TRT. The series is a surreal and absurd comedy that revolves around the fictional love story between Leyla and Mecnun.",
"name": "Leyla ile Mecnun"
},
{
"backdrop_path": null,
"id": 44669,
"overview": "Leyla'nın Evi is a Turkish romantic drama television series which is not broadcast yet in Turkey. The title, which is similar to that of Zülfü Livaneli's book \"Leyla'nın Evi\", is very different and is not an adaptation of that book. It is about a woman, Leyla, who after the murder of her beloved husband, Ramazan, tries to find happiness with her two children, Mehmet and Merve",
"name": "The House of Leyla",
},
{
"backdrop_path": null,
"id": 59441,
"overview": "Ask the Leyland Brothers was an Australian television show that screened between 1976 and 1980, covering 153 episodes. The series followed the Leyland brothers, Mike and Mal, who traveled across Australia and New Zealand in response to questions posed by viewers.",
"name": "Ask the Leyland Brothers",
},
{
"backdrop_path": null,
"id": 23398,
"overview": "",
"name": "Ask The Leyland Brothers",
}
],
"total_results": 5,
"total_pages": 1
};
}
/**
* Returns firebase user data
*/
function _getFirebaseUserData() {
return {
"uid": "0000000000000000001234567890",
"displayName": null,
"photoURL": null,
"email": "jasminetestmail@missofis.com",
"emailVerified": false,
"isAnonymous": false,
"providerData": [
{
"uid": "jasminetestmail@missofis.com",
"displayName": null,
"photoURL": null,
"email": "jasminetestmail@missofis.com",
"providerId": "password"
}
],
"apiKey": "hgfedcba123456789-abcdefg-ABCDEFGHI0123",
"appName": "[DEFAULT]",
"authDomain": "untitled-tv-show-feed.firebaseapp.com",
"stsTokenManager": {
"apiKey": "hgfedcba123456789-abcdefg-ABCDEFGHI0123",
"refreshToken": "00000000001234567890",
"accessToken": "abcdefghijklmnoprstuxwyz",
"expirationTime": 1479398926635
},
"redirectEventId": null
};
}
/**
* Returns user favorites mock data for appState
*/
function _getUserFavoritesMockData() {
return {
"12345": "Some TV Show",
"67890": "Another TV Show",
"00001": "Very Good TV Show",
"99999": "Game of Melons",
"44444": "Fart Matter",
"00008": "Ms. Robot",
"77777": "Harrison Break"
};
}
/**
* Returns user favorites mock data for appState
*/
function _getUserProfileMockData() {
return {
"biography": "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Recusandae, voluptatem.",
"collector": true,
"displayName": "Jane Doe"
};
}
} )();
|
import * as ReactNative from "react-native";
function hasImageForTag(prim, prim$1) {
ReactNative.ImageStore.hasImageForTag(prim, prim$1);
return /* () */0;
}
function removeImageForTag(prim) {
ReactNative.ImageStore.removeImageForTag(prim);
return /* () */0;
}
function addImageFromBase64(prim, prim$1, prim$2) {
ReactNative.ImageStore.addImageFromBase64(prim, prim$1, prim$2);
return /* () */0;
}
function getBase64ForTag(prim, prim$1, prim$2) {
ReactNative.ImageStore.getBase64ForTag(prim, prim$1, prim$2);
return /* () */0;
}
export {
hasImageForTag ,
removeImageForTag ,
addImageFromBase64 ,
getBase64ForTag ,
}
/* react-native Not a pure module */
|
/*! @license Firebase v4.5.0
Build: rev-f49c8b5
Terms: https://firebase.google.com/terms/ */
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ObjectMap = undefined;
var _obj = require('./obj');
var objUtil = _interopRequireWildcard(_obj);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
/**
* A map implementation that uses objects as keys. Objects must implement the
* Equatable interface and must be immutable. Entries in the map are stored
* together with the key being produced from the mapKeyFn. This map
* automatically handles collisions of keys.
*/
var ObjectMap = /** @class */function () {
function ObjectMap(mapKeyFn) {
this.mapKeyFn = mapKeyFn;
/**
* The inner map for a key -> value pair. Due to the possibility of
* collisions we keep a list of entries that we do a linear search through
* to find an actual match. Note that collisions should be rare, so we still
* expect near constant time lookups in practice.
*/
this.inner = {};
}
/** Get a value for this key, or undefined if it does not exist. */
ObjectMap.prototype.get = function (key) {
var id = this.mapKeyFn(key);
var matches = this.inner[id];
if (matches === undefined) {
return undefined;
}
for (var _i = 0, matches_1 = matches; _i < matches_1.length; _i++) {
var _a = matches_1[_i],
otherKey = _a[0],
value = _a[1];
if (otherKey.equals(key)) {
return value;
}
}
return undefined;
};
ObjectMap.prototype.has = function (key) {
return this.get(key) !== undefined;
};
/** Put this key and value in the map. */
ObjectMap.prototype.set = function (key, value) {
var id = this.mapKeyFn(key);
var matches = this.inner[id];
if (matches === undefined) {
this.inner[id] = [[key, value]];
return;
}
for (var i = 0; i < matches.length; i++) {
if (matches[i][0].equals(key)) {
matches[i] = [key, value];
return;
}
}
matches.push([key, value]);
};
/**
* Remove this key from the map. Returns a boolean if anything was deleted.
*/
ObjectMap.prototype.delete = function (key) {
var id = this.mapKeyFn(key);
var matches = this.inner[id];
if (matches === undefined) {
return false;
}
for (var i = 0; i < matches.length; i++) {
if (matches[i][0].equals(key)) {
if (matches.length === 1) {
delete this.inner[id];
} else {
matches.splice(i, 1);
}
return true;
}
}
return false;
};
ObjectMap.prototype.forEach = function (fn) {
objUtil.forEach(this.inner, function (_, entries) {
for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
var _a = entries_1[_i],
k = _a[0],
v = _a[1];
fn(k, v);
}
});
};
ObjectMap.prototype.isEmpty = function () {
return objUtil.isEmpty(this.inner);
};
return ObjectMap;
}(); /**
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
exports.ObjectMap = ObjectMap;
//# sourceMappingURL=obj_map.js.map
|
/*jshint curly:true, eqeqeq:true, laxbreak:true, noempty:false */
"use strict";
const acorn = require("acorn/acorn");
/*
The MIT License (MIT)
Copyright (c) 2007-2013 Einar Lielmanis and contributors.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
JS Beautifier
---------------
Written by Einar Lielmanis, <einar@jsbeautifier.org>
http://jsbeautifier.org/
Originally converted to javascript by Vital, <vital76@gmail.com>
"End braces on own line" added by Chris J. Shull, <chrisjshull@gmail.com>
Parsing improvements for brace-less statements by Liam Newman <bitwiseman@gmail.com>
Usage:
js_beautify(js_source_text);
js_beautify(js_source_text, options);
The options are:
indent_size (default 4) - indentation size,
indent_char (default space) - character to indent with,
preserve_newlines (default true) - whether existing line breaks should be preserved,
max_preserve_newlines (default unlimited) - maximum number of line breaks to be preserved in one chunk,
jslint_happy (default false) - if true, then jslint-stricter mode is enforced.
jslint_happy !jslint_happy
---------------------------------
function () function()
brace_style (default "collapse") - "collapse" | "expand" | "end-expand"
put braces on the same line as control statements (default), or put braces on own line (Allman / ANSI style), or just put end braces on own line.
space_before_conditional (default true) - should the space before conditional statement be added, "if(true)" vs "if (true)",
unescape_strings (default false) - should printable characters in strings encoded in \xNN notation be unescaped, "example" vs "\x65\x78\x61\x6d\x70\x6c\x65"
wrap_line_length (default unlimited) - lines should wrap at next opportunity after this number of characters.
NOTE: This is not a hard limit. Lines will continue until a point where a newline would
be preserved if it were present.
e.g
js_beautify(js_source_text, {
'indent_size': 1,
'indent_char': '\t'
});
*/
var js_beautify = function js_beautify(js_source_text, options) {
var beautifier = new Beautifier(js_source_text, options);
return beautifier.beautify();
};
exports.jsBeautify = js_beautify;
function Beautifier(js_source_text, options) {
var input, output_lines;
var token_text, token_type, last_type, last_last_text, indent_string;
var flags, previous_flags, flag_store;
var whitespace, wordchar, punct, parser_pos, line_starters, reserved_words, digits;
var prefix;
var input_wanted_newline;
var output_space_before_token;
var input_length, n_newlines, whitespace_before_token;
var handlers, MODE, opt;
var preindent_string = '';
whitespace = "\n\r\t ".split('');
wordchar = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_$'.split('');
digits = '0123456789'.split('');
punct = '+ - * / % & ++ -- = += -= *= /= %= == === != !== > < >= <= >> << >>> >>>= >>= <<= && &= | || ! ~ , : ? ^ ^= |= :: =>';
punct += ' <%= <% %> <?= <? ?>'; // try to be a good boy and try not to break the markup language identifiers
punct = punct.split(' ');
// words which should always start on new line.
line_starters = 'continue,try,throw,return,var,let,const,if,switch,case,default,for,while,break,function,yield'.split(',');
reserved_words = line_starters.concat(['do', 'in', 'else', 'get', 'set', 'new', 'catch', 'finally', 'typeof']);
MODE = {
BlockStatement: 'BlockStatement', // 'BLOCK'
Statement: 'Statement', // 'STATEMENT'
ObjectLiteral: 'ObjectLiteral', // 'OBJECT',
ArrayLiteral: 'ArrayLiteral', //'[EXPRESSION]',
ForInitializer: 'ForInitializer', //'(FOR-EXPRESSION)',
Conditional: 'Conditional', //'(COND-EXPRESSION)',
Expression: 'Expression' //'(EXPRESSION)'
};
handlers = {
'TK_START_EXPR': handle_start_expr,
'TK_END_EXPR': handle_end_expr,
'TK_START_BLOCK': handle_start_block,
'TK_END_BLOCK': handle_end_block,
'TK_WORD': handle_word,
'TK_RESERVED': handle_word,
'TK_SEMICOLON': handle_semicolon,
'TK_STRING': handle_string,
'TK_EQUALS': handle_equals,
'TK_OPERATOR': handle_operator,
'TK_COMMA': handle_comma,
'TK_BLOCK_COMMENT': handle_block_comment,
'TK_INLINE_COMMENT': handle_inline_comment,
'TK_COMMENT': handle_comment,
'TK_DOT': handle_dot,
'TK_UNKNOWN': handle_unknown
};
function create_flags(flags_base, mode) {
var next_indent_level = 0;
if (flags_base) {
next_indent_level = flags_base.indentation_level;
if (!just_added_newline() &&
flags_base.line_indent_level > next_indent_level) {
next_indent_level = flags_base.line_indent_level;
}
}
var next_flags = {
mode: mode,
parent: flags_base,
last_text: flags_base ? flags_base.last_text : '', // last token text
last_word: flags_base ? flags_base.last_word : '', // last 'TK_WORD' passed
declaration_statement: false,
declaration_assignment: false,
in_html_comment: false,
multiline_frame: false,
if_block: false,
else_block: false,
do_block: false,
do_while: false,
in_case_statement: false, // switch(..){ INSIDE HERE }
in_case: false, // we're on the exact line with "case 0:"
case_body: false, // the indented case-action block
indentation_level: next_indent_level,
line_indent_level: flags_base ? flags_base.line_indent_level : next_indent_level,
start_line_index: output_lines.length,
had_comment: false,
ternary_depth: 0
};
return next_flags;
}
// Using object instead of string to allow for later expansion of info about each line
function create_output_line() {
return {
text: []
};
}
// Some interpreters have unexpected results with foo = baz || bar;
options = options ? options : {};
opt = {};
// compatibility
if (options.space_after_anon_function !== undefined && options.jslint_happy === undefined) {
options.jslint_happy = options.space_after_anon_function;
}
if (options.braces_on_own_line !== undefined) { //graceful handling of deprecated option
opt.brace_style = options.braces_on_own_line ? "expand" : "collapse";
}
opt.brace_style = options.brace_style ? options.brace_style : (opt.brace_style ? opt.brace_style : "collapse");
// graceful handling of deprecated option
if (opt.brace_style === "expand-strict") {
opt.brace_style = "expand";
}
opt.indent_size = options.indent_size ? parseInt(options.indent_size, 10) : 4;
opt.indent_char = options.indent_char ? options.indent_char : ' ';
opt.preserve_newlines = (options.preserve_newlines === undefined) ? true : options.preserve_newlines;
opt.break_chained_methods = (options.break_chained_methods === undefined) ? false : options.break_chained_methods;
opt.max_preserve_newlines = (options.max_preserve_newlines === undefined) ? 0 : parseInt(options.max_preserve_newlines, 10);
opt.space_in_paren = (options.space_in_paren === undefined) ? false : options.space_in_paren;
opt.space_in_empty_paren = (options.space_in_empty_paren === undefined) ? false : options.space_in_empty_paren;
opt.jslint_happy = (options.jslint_happy === undefined) ? false : options.jslint_happy;
opt.keep_array_indentation = (options.keep_array_indentation === undefined) ? false : options.keep_array_indentation;
opt.space_before_conditional = (options.space_before_conditional === undefined) ? true : options.space_before_conditional;
opt.unescape_strings = (options.unescape_strings === undefined) ? false : options.unescape_strings;
opt.wrap_line_length = (options.wrap_line_length === undefined) ? 0 : parseInt(options.wrap_line_length, 10);
opt.e4x = (options.e4x === undefined) ? false : options.e4x;
if(options.indent_with_tabs){
opt.indent_char = '\t';
opt.indent_size = 1;
}
//----------------------------------
indent_string = '';
while (opt.indent_size > 0) {
indent_string += opt.indent_char;
opt.indent_size -= 1;
}
while (js_source_text && (js_source_text.charAt(0) === ' ' || js_source_text.charAt(0) === '\t')) {
preindent_string += js_source_text.charAt(0);
js_source_text = js_source_text.substring(1);
}
input = js_source_text;
// cache the source's length.
input_length = js_source_text.length;
last_type = 'TK_START_BLOCK'; // last token type
last_last_text = ''; // pre-last token text
output_lines = [create_output_line()];
output_space_before_token = false;
whitespace_before_token = [];
// Stack of parsing/formatting states, including MODE.
// We tokenize, parse, and output in an almost purely a forward-only stream of token input
// and formatted output. This makes the beautifier less accurate than full parsers
// but also far more tolerant of syntax errors.
//
// For example, the default mode is MODE.BlockStatement. If we see a '{' we push a new frame of type
// MODE.BlockStatement on the the stack, even though it could be object literal. If we later
// encounter a ":", we'll switch to to MODE.ObjectLiteral. If we then see a ";",
// most full parsers would die, but the beautifier gracefully falls back to
// MODE.BlockStatement and continues on.
flag_store = [];
set_mode(MODE.BlockStatement);
parser_pos = 0;
this.beautify = function() {
/*jshint onevar:true */
var t, i, keep_whitespace, sweet_code;
while (true) {
t = get_next_token();
token_text = t[0];
token_type = t[1];
if (token_type === 'TK_EOF') {
// Unwind any open statements
while (flags.mode === MODE.Statement) {
restore_mode();
}
break;
}
keep_whitespace = opt.keep_array_indentation && is_array(flags.mode);
input_wanted_newline = n_newlines > 0;
if (keep_whitespace) {
for (i = 0; i < n_newlines; i += 1) {
print_newline(i > 0);
}
} else {
if (opt.max_preserve_newlines && n_newlines > opt.max_preserve_newlines) {
n_newlines = opt.max_preserve_newlines;
}
if (opt.preserve_newlines) {
if (n_newlines > 1) {
print_newline();
for (i = 1; i < n_newlines; i += 1) {
print_newline(true);
}
}
}
}
handlers[token_type]();
// The cleanest handling of inline comments is to treat them as though they aren't there.
// Just continue formatting and the behavior should be logical.
// Also ignore unknown tokens. Again, this should result in better behavior.
if (token_type !== 'TK_INLINE_COMMENT' && token_type !== 'TK_COMMENT' &&
token_type !== 'TK_BLOCK_COMMENT' && token_type !== 'TK_UNKNOWN') {
last_last_text = flags.last_text;
last_type = token_type;
flags.last_text = token_text;
}
flags.had_comment = (token_type === 'TK_INLINE_COMMENT' || token_type === 'TK_COMMENT'
|| token_type === 'TK_BLOCK_COMMENT');
}
sweet_code = output_lines[0].text.join('');
for (var line_index = 1; line_index < output_lines.length; line_index++) {
sweet_code += '\n' + output_lines[line_index].text.join('');
}
sweet_code = sweet_code.replace(/[\r\n ]+$/, '');
return sweet_code;
};
function trim_output(eat_newlines) {
eat_newlines = (eat_newlines === undefined) ? false : eat_newlines;
if (output_lines.length) {
trim_output_line(output_lines[output_lines.length - 1], eat_newlines);
while (eat_newlines && output_lines.length > 1 &&
output_lines[output_lines.length - 1].text.length === 0) {
output_lines.pop();
trim_output_line(output_lines[output_lines.length - 1], eat_newlines);
}
}
}
function trim_output_line(line) {
while (line.text.length &&
(line.text[line.text.length - 1] === ' ' ||
line.text[line.text.length - 1] === indent_string ||
line.text[line.text.length - 1] === preindent_string)) {
line.text.pop();
}
}
function trim(s) {
return s.replace(/^\s+|\s+$/g, '');
}
// we could use just string.split, but
// IE doesn't like returning empty strings
function split_newlines(s) {
//return s.split(/\x0d\x0a|\x0a/);
s = s.replace(/\x0d/g, '');
var out = [],
idx = s.indexOf("\n");
while (idx !== -1) {
out.push(s.substring(0, idx));
s = s.substring(idx + 1);
idx = s.indexOf("\n");
}
if (s.length) {
out.push(s);
}
return out;
}
function just_added_newline() {
var line = output_lines[output_lines.length - 1];
return line.text.length === 0;
}
function just_added_blankline() {
if (just_added_newline()) {
if (output_lines.length === 1) {
return true; // start of the file and newline = blank
}
var line = output_lines[output_lines.length - 2];
return line.text.length === 0;
}
return false;
}
function allow_wrap_or_preserved_newline(force_linewrap) {
force_linewrap = (force_linewrap === undefined) ? false : force_linewrap;
if (opt.wrap_line_length && !force_linewrap) {
var line = output_lines[output_lines.length - 1];
var proposed_line_length = 0;
// never wrap the first token of a line.
if (line.text.length > 0) {
proposed_line_length = line.text.join('').length + token_text.length +
(output_space_before_token ? 1 : 0);
if (proposed_line_length >= opt.wrap_line_length) {
force_linewrap = true;
}
}
}
if (((opt.preserve_newlines && input_wanted_newline) || force_linewrap) && !just_added_newline()) {
print_newline(false, true);
}
}
function print_newline(force_newline, preserve_statement_flags) {
output_space_before_token = false;
if (!preserve_statement_flags) {
if (flags.last_text !== ';' && flags.last_text !== ',' && flags.last_text !== '=' && last_type !== 'TK_OPERATOR') {
while (flags.mode === MODE.Statement && !flags.if_block && !flags.do_block) {
restore_mode();
}
}
}
if (output_lines.length === 1 && just_added_newline()) {
return; // no newline on start of file
}
if (force_newline || !just_added_newline()) {
flags.multiline_frame = true;
output_lines.push(create_output_line());
}
}
function print_token_line_indentation() {
if (just_added_newline()) {
var line = output_lines[output_lines.length - 1];
if (opt.keep_array_indentation && is_array(flags.mode) && input_wanted_newline) {
// prevent removing of this whitespace as redundant
line.text.push('');
for (var i = 0; i < whitespace_before_token.length; i += 1) {
line.text.push(whitespace_before_token[i]);
}
} else {
if (preindent_string) {
line.text.push(preindent_string);
}
print_indent_string(flags.indentation_level);
}
}
}
function print_indent_string(level) {
// Never indent your first output indent at the start of the file
if (output_lines.length > 1) {
var line = output_lines[output_lines.length - 1];
flags.line_indent_level = level;
for (var i = 0; i < level; i += 1) {
line.text.push(indent_string);
}
}
}
function print_token_space_before() {
var line = output_lines[output_lines.length - 1];
if (output_space_before_token && line.text.length) {
var last_output = line.text[line.text.length - 1];
if (last_output !== ' ' && last_output !== indent_string) { // prevent occassional duplicate space
line.text.push(' ');
}
}
}
function print_token(printable_token) {
printable_token = printable_token || token_text;
print_token_line_indentation();
print_token_space_before();
output_space_before_token = false;
output_lines[output_lines.length - 1].text.push(printable_token);
}
function indent() {
flags.indentation_level += 1;
}
function deindent() {
if (flags.indentation_level > 0 &&
((!flags.parent) || flags.indentation_level > flags.parent.indentation_level))
flags.indentation_level -= 1;
}
function remove_redundant_indentation(frame) {
// This implementation is effective but has some issues:
// - less than great performance due to array splicing
// - can cause line wrap to happen too soon due to indent removal
// after wrap points are calculated
// These issues are minor compared to ugly indentation.
if (frame.multiline_frame) return;
// remove one indent from each line inside this section
var index = frame.start_line_index;
var splice_index = 0;
var line;
while (index < output_lines.length) {
line = output_lines[index];
index++;
// skip empty lines
if (line.text.length === 0) {
continue;
}
// skip the preindent string if present
if (preindent_string && line.text[0] === preindent_string) {
splice_index = 1;
} else {
splice_index = 0;
}
// remove one indent, if present
if (line.text[splice_index] === indent_string) {
line.text.splice(splice_index, 1);
}
}
}
function set_mode(mode) {
if (flags) {
flag_store.push(flags);
previous_flags = flags;
} else {
previous_flags = create_flags(null, mode);
}
flags = create_flags(previous_flags, mode);
}
function is_array(mode) {
return mode === MODE.ArrayLiteral;
}
function is_expression(mode) {
return in_array(mode, [MODE.Expression, MODE.ForInitializer, MODE.Conditional]);
}
function restore_mode() {
if (flag_store.length > 0) {
previous_flags = flags;
flags = flag_store.pop();
if (previous_flags.mode === MODE.Statement) {
remove_redundant_indentation(previous_flags);
}
}
}
function start_of_object_property() {
return flags.parent.mode === MODE.ObjectLiteral && flags.mode === MODE.Statement && flags.last_text === ':' &&
flags.ternary_depth === 0;
}
function start_of_statement() {
if (
(last_type === 'TK_RESERVED' && in_array(flags.last_text, ['var', 'let', 'const']) && token_type === 'TK_WORD') ||
(last_type === 'TK_RESERVED' && flags.last_text === 'do') ||
(last_type === 'TK_RESERVED' && flags.last_text === 'return' && !input_wanted_newline) ||
(last_type === 'TK_RESERVED' && flags.last_text === 'else' && !(token_type === 'TK_RESERVED' && token_text === 'if')) ||
(last_type === 'TK_END_EXPR' && (previous_flags.mode === MODE.ForInitializer || previous_flags.mode === MODE.Conditional)) ||
(last_type === 'TK_WORD' && flags.mode === MODE.BlockStatement
&& !flags.in_case
&& !(token_text === '--' || token_text === '++')
&& token_type !== 'TK_WORD' && token_type !== 'TK_RESERVED') ||
(flags.mode === MODE.ObjectLiteral && flags.last_text === ':' && flags.ternary_depth === 0)
) {
set_mode(MODE.Statement);
indent();
if (last_type === 'TK_RESERVED' && in_array(flags.last_text, ['var', 'let', 'const']) && token_type === 'TK_WORD') {
flags.declaration_statement = true;
}
// Issue #276:
// If starting a new statement with [if, for, while, do], push to a new line.
// if (a) if (b) if(c) d(); else e(); else f();
if (!start_of_object_property()) {
allow_wrap_or_preserved_newline(
token_type === 'TK_RESERVED' && in_array(token_text, ['do', 'for', 'if', 'while']));
}
return true;
}
return false;
}
function all_lines_start_with(lines, c) {
for (var i = 0; i < lines.length; i++) {
var line = trim(lines[i]);
if (line.charAt(0) !== c) {
return false;
}
}
return true;
}
function each_line_matches_indent(lines, indent) {
var i = 0,
len = lines.length,
line;
for (; i < len; i++) {
line = lines[i];
// allow empty lines to pass through
if (line && line.indexOf(indent) !== 0) {
return false;
}
}
return true;
}
function is_special_word(word) {
return in_array(word, ['case', 'return', 'do', 'if', 'throw', 'else']);
}
function in_array(what, arr) {
for (var i = 0; i < arr.length; i += 1) {
if (arr[i] === what) {
return true;
}
}
return false;
}
function unescape_string(s) {
var esc = false,
out = '',
pos = 0,
s_hex = '',
escaped = 0,
c;
while (esc || pos < s.length) {
c = s.charAt(pos);
pos++;
if (esc) {
esc = false;
if (c === 'x') {
// simple hex-escape \x24
s_hex = s.substr(pos, 2);
pos += 2;
} else if (c === 'u') {
// unicode-escape, \u2134
s_hex = s.substr(pos, 4);
pos += 4;
} else {
// some common escape, e.g \n
out += '\\' + c;
continue;
}
if (!s_hex.match(/^[0123456789abcdefABCDEF]+$/)) {
// some weird escaping, bail out,
// leaving whole string intact
return s;
}
escaped = parseInt(s_hex, 16);
if (escaped >= 0x00 && escaped < 0x20) {
// leave 0x00...0x1f escaped
if (c === 'x') {
out += '\\x' + s_hex;
} else {
out += '\\u' + s_hex;
}
continue;
} else if (escaped === 0x22 || escaped === 0x27 || escaped === 0x5c) {
// single-quote, apostrophe, backslash - escape these
out += '\\' + String.fromCharCode(escaped);
} else if (c === 'x' && escaped > 0x7e && escaped <= 0xff) {
// we bail out on \x7f..\xff,
// leaving whole string escaped,
// as it's probably completely binary
return s;
} else {
out += String.fromCharCode(escaped);
}
} else if (c === '\\') {
esc = true;
} else {
out += c;
}
}
return out;
}
function is_next(find) {
var local_pos = parser_pos;
var c = input.charAt(local_pos);
while (in_array(c, whitespace) && c !== find) {
local_pos++;
if (local_pos >= input_length) {
return false;
}
c = input.charAt(local_pos);
}
return c === find;
}
function get_next_token() {
var i, resulting_string;
n_newlines = 0;
if (parser_pos >= input_length) {
return ['', 'TK_EOF'];
}
input_wanted_newline = false;
whitespace_before_token = [];
var c = input.charAt(parser_pos);
parser_pos += 1;
while (in_array(c, whitespace)) {
if (c === '\n') {
n_newlines += 1;
whitespace_before_token = [];
} else if (n_newlines) {
if (c === indent_string) {
whitespace_before_token.push(indent_string);
} else if (c !== '\r') {
whitespace_before_token.push(' ');
}
}
if (parser_pos >= input_length) {
return ['', 'TK_EOF'];
}
c = input.charAt(parser_pos);
parser_pos += 1;
}
// NOTE: because beautifier doesn't fully parse, it doesn't use acorn.isIdentifierStart.
// It just treats all identifiers and numbers and such the same.
if (acorn.isIdentifierChar(input.charCodeAt(parser_pos-1))) {
if (parser_pos < input_length) {
while (acorn.isIdentifierChar(input.charCodeAt(parser_pos))) {
c += input.charAt(parser_pos);
parser_pos += 1;
if (parser_pos === input_length) {
break;
}
}
}
// small and surprisingly unugly hack for 1E-10 representation
if (parser_pos !== input_length && c.match(/^[0-9]+[Ee]$/) && (input.charAt(parser_pos) === '-' || input.charAt(parser_pos) === '+')) {
var sign = input.charAt(parser_pos);
parser_pos += 1;
var t = get_next_token();
c += sign + t[0];
return [c, 'TK_WORD'];
}
if (!(last_type === 'TK_DOT' ||
(last_type === 'TK_RESERVED' && in_array(flags.last_text, ['set', 'get'])))
&& in_array(c, reserved_words)) {
if (c === 'in') { // hack for 'in' operator
return [c, 'TK_OPERATOR'];
}
return [c, 'TK_RESERVED'];
}
return [c, 'TK_WORD'];
}
if (c === '(' || c === '[') {
return [c, 'TK_START_EXPR'];
}
if (c === ')' || c === ']') {
return [c, 'TK_END_EXPR'];
}
if (c === '{') {
return [c, 'TK_START_BLOCK'];
}
if (c === '}') {
return [c, 'TK_END_BLOCK'];
}
if (c === ';') {
return [c, 'TK_SEMICOLON'];
}
if (c === '/') {
var comment = '';
// peek for comment /* ... */
var inline_comment = true;
if (input.charAt(parser_pos) === '*') {
parser_pos += 1;
if (parser_pos < input_length) {
while (parser_pos < input_length && !(input.charAt(parser_pos) === '*' && input.charAt(parser_pos + 1) && input.charAt(parser_pos + 1) === '/')) {
c = input.charAt(parser_pos);
comment += c;
if (c === "\n" || c === "\r") {
inline_comment = false;
}
parser_pos += 1;
if (parser_pos >= input_length) {
break;
}
}
}
parser_pos += 2;
if (inline_comment && n_newlines === 0) {
return ['/*' + comment + '*/', 'TK_INLINE_COMMENT'];
} else {
return ['/*' + comment + '*/', 'TK_BLOCK_COMMENT'];
}
}
// peek for comment // ...
if (input.charAt(parser_pos) === '/') {
comment = c;
while (input.charAt(parser_pos) !== '\r' && input.charAt(parser_pos) !== '\n') {
comment += input.charAt(parser_pos);
parser_pos += 1;
if (parser_pos >= input_length) {
break;
}
}
return [comment, 'TK_COMMENT'];
}
}
if (c === '`' || c === "'" || c === '"' || // string
(
(c === '/') || // regexp
(opt.e4x && c === "<" && input.slice(parser_pos - 1).match(/^<([-a-zA-Z:0-9_.]+|{[^{}]*}|!\[CDATA\[[\s\S]*?\]\])\s*([-a-zA-Z:0-9_.]+=('[^']*'|"[^"]*"|{[^{}]*})\s*)*\/?\s*>/)) // xml
) && ( // regex and xml can only appear in specific locations during parsing
(last_type === 'TK_RESERVED' && is_special_word(flags.last_text)) ||
(last_type === 'TK_END_EXPR' && in_array(previous_flags.mode, [MODE.Conditional, MODE.ForInitializer])) ||
(in_array(last_type, ['TK_COMMENT', 'TK_START_EXPR', 'TK_START_BLOCK',
'TK_END_BLOCK', 'TK_OPERATOR', 'TK_EQUALS', 'TK_EOF', 'TK_SEMICOLON', 'TK_COMMA'
]))
)) {
var sep = c,
esc = false,
has_char_escapes = false;
resulting_string = c;
if (parser_pos < input_length) {
if (sep === '/') {
//
// handle regexp
//
var in_char_class = false;
while (esc || in_char_class || input.charAt(parser_pos) !== sep) {
resulting_string += input.charAt(parser_pos);
if (!esc) {
esc = input.charAt(parser_pos) === '\\';
if (input.charAt(parser_pos) === '[') {
in_char_class = true;
} else if (input.charAt(parser_pos) === ']') {
in_char_class = false;
}
} else {
esc = false;
}
parser_pos += 1;
if (parser_pos >= input_length) {
// incomplete string/rexp when end-of-file reached.
// bail out with what had been received so far.
return [resulting_string, 'TK_STRING'];
}
}
} else if (opt.e4x && sep === '<') {
//
// handle e4x xml literals
//
var xmlRegExp = /<(\/?)([-a-zA-Z:0-9_.]+|{[^{}]*}|!\[CDATA\[[\s\S]*?\]\])\s*([-a-zA-Z:0-9_.]+=('[^']*'|"[^"]*"|{[^{}]*})\s*)*(\/?)\s*>/g;
var xmlStr = input.slice(parser_pos - 1);
var match = xmlRegExp.exec(xmlStr);
if (match && match.index === 0) {
var rootTag = match[2];
var depth = 0;
while (match) {
var isEndTag = !! match[1];
var tagName = match[2];
var isSingletonTag = ( !! match[match.length - 1]) || (tagName.slice(0, 8) === "![CDATA[");
if (tagName === rootTag && !isSingletonTag) {
if (isEndTag) {
--depth;
} else {
++depth;
}
}
if (depth <= 0) {
break;
}
match = xmlRegExp.exec(xmlStr);
}
var xmlLength = match ? match.index + match[0].length : xmlStr.length;
parser_pos += xmlLength - 1;
return [xmlStr.slice(0, xmlLength), "TK_STRING"];
}
} else {
//
// handle string
//
while (esc || input.charAt(parser_pos) !== sep) {
resulting_string += input.charAt(parser_pos);
if (esc) {
if (input.charAt(parser_pos) === 'x' || input.charAt(parser_pos) === 'u') {
has_char_escapes = true;
}
esc = false;
} else {
esc = input.charAt(parser_pos) === '\\';
}
parser_pos += 1;
if (parser_pos >= input_length) {
// incomplete string/rexp when end-of-file reached.
// bail out with what had been received so far.
return [resulting_string, 'TK_STRING'];
}
}
}
}
parser_pos += 1;
resulting_string += sep;
if (has_char_escapes && opt.unescape_strings) {
resulting_string = unescape_string(resulting_string);
}
if (sep === '/') {
// regexps may have modifiers /regexp/MOD , so fetch those, too
while (parser_pos < input_length && in_array(input.charAt(parser_pos), wordchar)) {
resulting_string += input.charAt(parser_pos);
parser_pos += 1;
}
}
return [resulting_string, 'TK_STRING'];
}
if (c === '#') {
if (output_lines.length === 1 && output_lines[0].text.length === 0 &&
input.charAt(parser_pos) === '!') {
// shebang
resulting_string = c;
while (parser_pos < input_length && c !== '\n') {
c = input.charAt(parser_pos);
resulting_string += c;
parser_pos += 1;
}
return [trim(resulting_string) + '\n', 'TK_UNKNOWN'];
}
// Spidermonkey-specific sharp variables for circular references
// https://developer.mozilla.org/En/Sharp_variables_in_JavaScript
// http://mxr.mozilla.org/mozilla-central/source/js/src/jsscan.cpp around line 1935
var sharp = '#';
if (parser_pos < input_length && in_array(input.charAt(parser_pos), digits)) {
do {
c = input.charAt(parser_pos);
sharp += c;
parser_pos += 1;
} while (parser_pos < input_length && c !== '#' && c !== '=');
if (c === '#') {
//
} else if (input.charAt(parser_pos) === '[' && input.charAt(parser_pos + 1) === ']') {
sharp += '[]';
parser_pos += 2;
} else if (input.charAt(parser_pos) === '{' && input.charAt(parser_pos + 1) === '}') {
sharp += '{}';
parser_pos += 2;
}
return [sharp, 'TK_WORD'];
}
}
if (c === '<' && input.substring(parser_pos - 1, parser_pos + 3) === '<!--') {
parser_pos += 3;
c = '<!--';
while (input.charAt(parser_pos) !== '\n' && parser_pos < input_length) {
c += input.charAt(parser_pos);
parser_pos++;
}
flags.in_html_comment = true;
return [c, 'TK_COMMENT'];
}
if (c === '-' && flags.in_html_comment && input.substring(parser_pos - 1, parser_pos + 2) === '-->') {
flags.in_html_comment = false;
parser_pos += 2;
return ['-->', 'TK_COMMENT'];
}
if (c === '.') {
return [c, 'TK_DOT'];
}
if (in_array(c, punct)) {
while (parser_pos < input_length && in_array(c + input.charAt(parser_pos), punct)) {
c += input.charAt(parser_pos);
parser_pos += 1;
if (parser_pos >= input_length) {
break;
}
}
if (c === ',') {
return [c, 'TK_COMMA'];
} else if (c === '=') {
return [c, 'TK_EQUALS'];
} else {
return [c, 'TK_OPERATOR'];
}
}
return [c, 'TK_UNKNOWN'];
}
function handle_start_expr() {
if (start_of_statement()) {
// The conditional starts the statement if appropriate.
}
var next_mode = MODE.Expression;
if (token_text === '[') {
if (last_type === 'TK_WORD' || flags.last_text === ')') {
// this is array index specifier, break immediately
// a[x], fn()[x]
if (last_type === 'TK_RESERVED' && in_array(flags.last_text, line_starters)) {
output_space_before_token = true;
}
set_mode(next_mode);
print_token();
indent();
if (opt.space_in_paren) {
output_space_before_token = true;
}
return;
}
next_mode = MODE.ArrayLiteral;
if (is_array(flags.mode)) {
if (flags.last_text === '[' ||
(flags.last_text === ',' && (last_last_text === ']' || last_last_text === '}'))) {
// ], [ goes to new line
// }, [ goes to new line
if (!opt.keep_array_indentation) {
print_newline();
}
}
}
} else {
if (last_type === 'TK_RESERVED' && flags.last_text === 'for') {
next_mode = MODE.ForInitializer;
} else if (last_type === 'TK_RESERVED' && in_array(flags.last_text, ['if', 'while'])) {
next_mode = MODE.Conditional;
} else {
// next_mode = MODE.Expression;
}
}
if (flags.last_text === ';' || last_type === 'TK_START_BLOCK') {
print_newline();
} else if (last_type === 'TK_END_EXPR' || last_type === 'TK_START_EXPR' || last_type === 'TK_END_BLOCK' || flags.last_text === '.') {
// TODO: Consider whether forcing this is required. Review failing tests when removed.
allow_wrap_or_preserved_newline(input_wanted_newline);
// do nothing on (( and )( and ][ and ]( and .(
} else if (!(last_type === 'TK_RESERVED' && token_text === '(') && last_type !== 'TK_WORD' && last_type !== 'TK_OPERATOR') {
output_space_before_token = true;
} else if ((last_type === 'TK_RESERVED' && (flags.last_word === 'function' || flags.last_word === 'typeof')) ||
(flags.last_text === '*' && last_last_text === 'function')) {
// function() vs function ()
if (opt.jslint_happy) {
output_space_before_token = true;
}
} else if (last_type === 'TK_RESERVED' && (in_array(flags.last_text, line_starters) || flags.last_text === 'catch')) {
if (opt.space_before_conditional) {
output_space_before_token = true;
}
}
// Support of this kind of newline preservation.
// a = (b &&
// (c || d));
if (token_text === '(') {
if (last_type === 'TK_EQUALS' || last_type === 'TK_OPERATOR') {
if (!start_of_object_property()) {
allow_wrap_or_preserved_newline();
}
}
}
set_mode(next_mode);
print_token();
if (opt.space_in_paren) {
output_space_before_token = true;
}
// In all cases, if we newline while inside an expression it should be indented.
indent();
}
function handle_end_expr() {
// statements inside expressions are not valid syntax, but...
// statements must all be closed when their container closes
while (flags.mode === MODE.Statement) {
restore_mode();
}
if (flags.multiline_frame) {
allow_wrap_or_preserved_newline(token_text === ']' && is_array(flags.mode) && !opt.keep_array_indentation);
}
if (opt.space_in_paren) {
if (last_type === 'TK_START_EXPR' && ! opt.space_in_empty_paren) {
// () [] no inner space in empty parens like these, ever, ref #320
trim_output();
output_space_before_token = false;
} else {
output_space_before_token = true;
}
}
if (token_text === ']' && opt.keep_array_indentation) {
print_token();
restore_mode();
} else {
restore_mode();
print_token();
}
remove_redundant_indentation(previous_flags);
// do {} while () // no statement required after
if (flags.do_while && previous_flags.mode === MODE.Conditional) {
previous_flags.mode = MODE.Expression;
flags.do_block = false;
flags.do_while = false;
}
}
function handle_start_block() {
set_mode(MODE.BlockStatement);
var empty_braces = is_next('}');
var empty_anonymous_function = empty_braces && flags.last_word === 'function' &&
last_type === 'TK_END_EXPR';
if (opt.brace_style === "expand") {
if (last_type !== 'TK_OPERATOR' &&
(empty_anonymous_function ||
last_type === 'TK_EQUALS' ||
(last_type === 'TK_RESERVED' && is_special_word(flags.last_text) && flags.last_text !== 'else'))) {
output_space_before_token = true;
} else {
print_newline(false, true);
}
} else { // collapse
if (last_type !== 'TK_OPERATOR' && last_type !== 'TK_START_EXPR') {
if (last_type === 'TK_START_BLOCK') {
print_newline();
} else {
output_space_before_token = true;
}
} else {
// if TK_OPERATOR or TK_START_EXPR
if (is_array(previous_flags.mode) && flags.last_text === ',') {
if (last_last_text === '}') {
// }, { in array context
output_space_before_token = true;
} else {
print_newline(); // [a, b, c, {
}
}
}
}
print_token();
indent();
}
function handle_end_block() {
// statements must all be closed when their container closes
while (flags.mode === MODE.Statement) {
restore_mode();
}
var empty_braces = last_type === 'TK_START_BLOCK';
if (opt.brace_style === "expand") {
if (!empty_braces) {
print_newline();
}
} else {
// skip {}
if (!empty_braces) {
if (is_array(flags.mode) && opt.keep_array_indentation) {
// we REALLY need a newline here, but newliner would skip that
opt.keep_array_indentation = false;
print_newline();
opt.keep_array_indentation = true;
} else {
print_newline();
}
}
}
restore_mode();
print_token();
}
function handle_word() {
if (start_of_statement()) {
// The conditional starts the statement if appropriate.
} else if (input_wanted_newline && !is_expression(flags.mode) &&
(last_type !== 'TK_OPERATOR' || (flags.last_text === '--' || flags.last_text === '++')) &&
last_type !== 'TK_EQUALS' &&
(opt.preserve_newlines || !(last_type === 'TK_RESERVED' && in_array(flags.last_text, ['var', 'let', 'const', 'set', 'get'])))) {
print_newline();
}
if (flags.do_block && !flags.do_while) {
if (token_type === 'TK_RESERVED' && token_text === 'while') {
// do {} ## while ()
output_space_before_token = true;
print_token();
output_space_before_token = true;
flags.do_while = true;
return;
} else {
// do {} should always have while as the next word.
// if we don't see the expected while, recover
print_newline();
flags.do_block = false;
}
}
// if may be followed by else, or not
// Bare/inline ifs are tricky
// Need to unwind the modes correctly: if (a) if (b) c(); else d(); else e();
if (flags.if_block) {
if (!flags.else_block && (token_type === 'TK_RESERVED' && token_text === 'else')) {
flags.else_block = true;
} else {
while (flags.mode === MODE.Statement) {
restore_mode();
}
flags.if_block = false;
flags.else_block = false;
}
}
if (token_type === 'TK_RESERVED' && (token_text === 'case' || (token_text === 'default' && flags.in_case_statement))) {
print_newline();
if (flags.case_body || opt.jslint_happy) {
// switch cases following one another
deindent();
flags.case_body = false;
}
print_token();
flags.in_case = true;
flags.in_case_statement = true;
return;
}
if (token_type === 'TK_RESERVED' && token_text === 'function') {
if (in_array(flags.last_text, ['}', ';']) || (just_added_newline() && ! in_array(flags.last_text, ['{', ':', '=', ',']))) {
// make sure there is a nice clean space of at least one blank line
// before a new function definition
if ( ! just_added_blankline() && ! flags.had_comment) {
print_newline();
print_newline(true);
}
}
if (last_type === 'TK_RESERVED' || last_type === 'TK_WORD') {
if (last_type === 'TK_RESERVED' && in_array(flags.last_text, ['get', 'set', 'new', 'return'])) {
output_space_before_token = true;
} else {
print_newline();
}
} else if (last_type === 'TK_OPERATOR' || flags.last_text === '=') {
// foo = function
output_space_before_token = true;
} else if (is_expression(flags.mode)) {
// (function
} else {
print_newline();
}
}
if (last_type === 'TK_COMMA' || last_type === 'TK_START_EXPR' || last_type === 'TK_EQUALS' || last_type === 'TK_OPERATOR') {
if (!start_of_object_property()) {
allow_wrap_or_preserved_newline();
}
}
if (token_type === 'TK_RESERVED' && token_text === 'function') {
print_token();
flags.last_word = token_text;
return;
}
prefix = 'NONE';
if (last_type === 'TK_END_BLOCK') {
if (!(token_type === 'TK_RESERVED' && in_array(token_text, ['else', 'catch', 'finally']))) {
prefix = 'NEWLINE';
} else {
if (opt.brace_style === "expand" || opt.brace_style === "end-expand") {
prefix = 'NEWLINE';
} else {
prefix = 'SPACE';
output_space_before_token = true;
}
}
} else if (last_type === 'TK_SEMICOLON' && flags.mode === MODE.BlockStatement) {
// TODO: Should this be for STATEMENT as well?
prefix = 'NEWLINE';
} else if (last_type === 'TK_SEMICOLON' && is_expression(flags.mode)) {
prefix = 'SPACE';
} else if (last_type === 'TK_STRING') {
prefix = 'NEWLINE';
} else if (last_type === 'TK_RESERVED' || last_type === 'TK_WORD' ||
(flags.last_text === '*' && last_last_text === 'function')) {
prefix = 'SPACE';
} else if (last_type === 'TK_START_BLOCK') {
prefix = 'NEWLINE';
} else if (last_type === 'TK_END_EXPR') {
output_space_before_token = true;
prefix = 'NEWLINE';
}
if (token_type === 'TK_RESERVED' && in_array(token_text, line_starters) && flags.last_text !== ')') {
if (flags.last_text === 'else') {
prefix = 'SPACE';
} else {
prefix = 'NEWLINE';
}
}
if (token_type === 'TK_RESERVED' && in_array(token_text, ['else', 'catch', 'finally'])) {
if (last_type !== 'TK_END_BLOCK' || opt.brace_style === "expand" || opt.brace_style === "end-expand") {
print_newline();
} else {
trim_output(true);
var line = output_lines[output_lines.length - 1];
// If we trimmed and there's something other than a close block before us
// put a newline back in. Handles '} // comment' scenario.
if (line.text[line.text.length - 1] !== '}') {
print_newline();
}
output_space_before_token = true;
}
} else if (prefix === 'NEWLINE') {
if (last_type === 'TK_RESERVED' && is_special_word(flags.last_text)) {
// no newline between 'return nnn'
output_space_before_token = true;
} else if (last_type !== 'TK_END_EXPR') {
if ((last_type !== 'TK_START_EXPR' || !(token_type === 'TK_RESERVED' && in_array(token_text, ['var', 'let', 'const']))) && flags.last_text !== ':') {
// no need to force newline on 'var': for (var x = 0...)
if (token_type === 'TK_RESERVED' && token_text === 'if' && flags.last_word === 'else' && flags.last_text !== '{') {
// no newline for } else if {
output_space_before_token = true;
} else {
print_newline();
}
}
} else if (token_type === 'TK_RESERVED' && in_array(token_text, line_starters) && flags.last_text !== ')') {
print_newline();
}
} else if (is_array(flags.mode) && flags.last_text === ',' && last_last_text === '}') {
print_newline(); // }, in lists get a newline treatment
} else if (prefix === 'SPACE') {
output_space_before_token = true;
}
print_token();
flags.last_word = token_text;
if (token_type === 'TK_RESERVED' && token_text === 'do') {
flags.do_block = true;
}
if (token_type === 'TK_RESERVED' && token_text === 'if') {
flags.if_block = true;
}
}
function handle_semicolon() {
if (start_of_statement()) {
// The conditional starts the statement if appropriate.
// Semicolon can be the start (and end) of a statement
output_space_before_token = false;
}
while (flags.mode === MODE.Statement && !flags.if_block && !flags.do_block) {
restore_mode();
}
print_token();
if (flags.mode === MODE.ObjectLiteral) {
// if we're in OBJECT mode and see a semicolon, its invalid syntax
// recover back to treating this as a BLOCK
flags.mode = MODE.BlockStatement;
}
}
function handle_string() {
if (start_of_statement()) {
// The conditional starts the statement if appropriate.
// One difference - strings want at least a space before
output_space_before_token = true;
} else if (last_type === 'TK_RESERVED' || last_type === 'TK_WORD') {
output_space_before_token = true;
} else if (last_type === 'TK_COMMA' || last_type === 'TK_START_EXPR' || last_type === 'TK_EQUALS' || last_type === 'TK_OPERATOR') {
if (!start_of_object_property()) {
allow_wrap_or_preserved_newline();
}
} else {
print_newline();
}
print_token();
}
function handle_equals() {
if (start_of_statement()) {
// The conditional starts the statement if appropriate.
}
if (flags.declaration_statement) {
// just got an '=' in a var-line, different formatting/line-breaking, etc will now be done
flags.declaration_assignment = true;
}
output_space_before_token = true;
print_token();
output_space_before_token = true;
}
function handle_comma() {
if (flags.declaration_statement) {
if (is_expression(flags.parent.mode)) {
// do not break on comma, for(var a = 1, b = 2)
flags.declaration_assignment = false;
}
print_token();
if (flags.declaration_assignment) {
flags.declaration_assignment = false;
print_newline(false, true);
} else {
output_space_before_token = true;
}
return;
}
print_token();
if (flags.mode === MODE.ObjectLiteral ||
(flags.mode === MODE.Statement && flags.parent.mode === MODE.ObjectLiteral)) {
if (flags.mode === MODE.Statement) {
restore_mode();
}
print_newline();
} else {
// EXPR or DO_BLOCK
output_space_before_token = true;
}
}
function handle_operator() {
// Check if this is a BlockStatement that should be treated as a ObjectLiteral
if (token_text === ':' && flags.mode === MODE.BlockStatement &&
last_last_text === '{' &&
(last_type === 'TK_WORD' || last_type === 'TK_RESERVED')){
flags.mode = MODE.ObjectLiteral;
}
if (start_of_statement()) {
// The conditional starts the statement if appropriate.
}
var space_before = true;
var space_after = true;
if (last_type === 'TK_RESERVED' && is_special_word(flags.last_text)) {
// "return" had a special handling in TK_WORD. Now we need to return the favor
output_space_before_token = true;
print_token();
return;
}
// hack for actionscript's import .*;
if (token_text === '*' && last_type === 'TK_DOT' && !last_last_text.match(/^\d+$/)) {
print_token();
return;
}
if (token_text === ':' && flags.in_case) {
flags.case_body = true;
indent();
print_token();
print_newline();
flags.in_case = false;
return;
}
if (token_text === '::') {
// no spaces around exotic namespacing syntax operator
print_token();
return;
}
// http://www.ecma-international.org/ecma-262/5.1/#sec-7.9.1
// if there is a newline between -- or ++ and anything else we should preserve it.
if (input_wanted_newline && (token_text === '--' || token_text === '++')) {
print_newline();
}
// Allow line wrapping between operators
if (last_type === 'TK_OPERATOR') {
allow_wrap_or_preserved_newline();
}
if (in_array(token_text, ['--', '++', '!', '~']) || (in_array(token_text, ['-', '+']) && (in_array(last_type, ['TK_START_BLOCK', 'TK_START_EXPR', 'TK_EQUALS', 'TK_OPERATOR']) || in_array(flags.last_text, line_starters) || flags.last_text === ','))) {
// unary operators (and binary +/- pretending to be unary) special cases
space_before = false;
space_after = false;
if (flags.last_text === ';' && is_expression(flags.mode)) {
// for (;; ++i)
// ^^^
space_before = true;
}
if (last_type === 'TK_RESERVED') {
space_before = true;
}
if ((flags.mode === MODE.BlockStatement || flags.mode === MODE.Statement) && (flags.last_text === '{' || flags.last_text === ';')) {
// { foo; --i }
// foo(); --bar;
print_newline();
}
} else if (token_text === ':') {
if (flags.ternary_depth === 0) {
if (flags.mode === MODE.BlockStatement) {
flags.mode = MODE.ObjectLiteral;
}
space_before = false;
} else {
flags.ternary_depth -= 1;
}
} else if (token_text === '?') {
flags.ternary_depth += 1;
} else if (token_text === '*' && last_type === 'TK_RESERVED' && flags.last_text === 'function') {
space_before = false;
space_after = false;
}
output_space_before_token = output_space_before_token || space_before;
print_token();
output_space_before_token = space_after;
}
function handle_block_comment() {
var lines = split_newlines(token_text);
var j; // iterator for this case
var javadoc = false;
var starless = false;
var lastIndent = whitespace_before_token.join('');
var lastIndentLength = lastIndent.length;
// block comment starts with a new line
print_newline(false, true);
if (lines.length > 1) {
if (all_lines_start_with(lines.slice(1), '*')) {
javadoc = true;
}
else if (each_line_matches_indent(lines.slice(1), lastIndent)) {
starless = true;
}
}
// first line always indented
print_token(lines[0]);
for (j = 1; j < lines.length; j++) {
print_newline(false, true);
if (javadoc) {
// javadoc: reformat and re-indent
print_token(' ' + trim(lines[j]));
} else if (starless && lines[j].length > lastIndentLength) {
// starless: re-indent non-empty content, avoiding trim
print_token(lines[j].substring(lastIndentLength));
} else {
// normal comments output raw
output_lines[output_lines.length - 1].text.push(lines[j]);
}
}
// for comments of more than one line, make sure there's a new line after
print_newline(false, true);
}
function handle_inline_comment() {
output_space_before_token = true;
print_token();
output_space_before_token = true;
}
function handle_comment() {
if (input_wanted_newline) {
print_newline(false, true);
} else {
trim_output(true);
}
output_space_before_token = true;
print_token();
print_newline(false, true);
}
function handle_dot() {
if (start_of_statement()) {
// The conditional starts the statement if appropriate.
}
if (last_type === 'TK_RESERVED' && is_special_word(flags.last_text)) {
output_space_before_token = true;
} else {
// allow preserved newlines before dots in general
// force newlines on dots after close paren when break_chained - for bar().baz()
allow_wrap_or_preserved_newline(flags.last_text === ')' && opt.break_chained_methods);
}
print_token();
}
function handle_unknown() {
print_token();
if (token_text[token_text.length - 1] === '\n') {
print_newline();
}
}
}
|
$.fn.smartSelect = function(settings) {
if( typeof $.fn.smartSelect.allSelects == 'undefined' ) {
$.fn.smartSelect.allSelects = []
}
this.filter(function(){
return ! $(this).hasClass('smart-select')
}).each(function() {
$(this).addClass('smart-select-done')
var $select = $(this);
var config = {
width : 230,
listHeight : 200,
showAnimation : 'show',
closeAnimation : 'hide',
animationDuration : 300,
closeAnimationCallback : $.noop,
showAnimationCallback : $.noop,
scroll : true,
onCreate : function($optionsList) {
},
onOpen : function($optionsList) {
// do nothing
},
onClose : function($optionsList) {
// do nothing
},
onSelect : function($optionsList, val, text) {
//do nothings
}
}
if(typeof settings != 'undefined') {
for( var s in settings) {
if( typeof config[s] != 'undefined' ) {
config[s] = settings[s]
}
}
}
var $options = $select.find('option');
var $selectedOption = $options.eq(0) //.filter('[selected=selected]')
$options.each(function() {
if( $(this).is('[selected=selected]') ) $selectedOption = $(this)
})
var scrollHtml = config.scroll ? '<div class="scroll-box" style="position:absolute;width:5px;right:5px;top:5px;bottom:5px;z-index:1000"><span class="scroll-bar" style="position:absolute;top:0;left:0;width:100%"></span></div>' : '';
$select.after('<div class="options-wrapper">\
<div class="click-handler">\
<span class="select-value">'+$selectedOption.text()+'</span><span class="click-arrow"></span>\
</div>\
<div class="options-holder" style="display:none">\
'+scrollHtml+'\
</div>\
</div>')
var $optionsList = $select.siblings('.options-wrapper').find('.options-holder');
var $value = $optionsList.siblings('.click-handler').find('.select-value');
var $scrollbox = $optionsList.children('.scroll-box');
var $scrollbar = $scrollbox.children('.scroll-bar');
var scrollbar_ratio = 0;
var is_opened = false;
var _actions = {
open : function(e) {
if( typeof e !='undefined') {
prevent(e);
if(e.stopPropagation) e.stopPropagation();
}
if(is_opened){
_actions.close(e);
return
}
_actions.setTo(0);
$.fn.smartSelect.allSelects.onEach('close');
$optionsList[config.showAnimation].call($optionsList, config.animationDuration , function() {
$(window).bind('click', _actions.closeOnOutsideClick )
config.showAnimationCallback($optionsList)
})
config.onOpen( $optionsList );
var $labels = $optionsList.children('label');
var last_label_position = $labels.last().position().top +
parseInt( $labels.last().css('padding-bottom') ) +
parseInt( $labels.last().css('padding-top') ) +
$labels.last().height()
scrollbar_ratio = ( config.listHeight - parseInt( $scrollbox.css('top') ) - parseInt( $scrollbox.css('bottom') ) ) /last_label_position
if( scrollbar_ratio < 1 ) {
$scrollbox.show();
$scrollbar.css({
height : (config.listHeight * scrollbar_ratio ) + 'px'
})
var $selected = $labels.filter('.selected');
if( $selected.length > 0) {
var selectedoffset = $selected.position().top +
parseInt( $selected.last().css('padding-bottom') ) +
parseInt( $selected.last().css('padding-top') ) +
$selected.last().height()
_actions.setTo( selectedoffset, true )
}
$scrollbar.bind('mousedown', function(e) {
prevent(e);
_actions.startMoving(e);
})
} else {
$scrollbox.hide()
}
is_opened = true;
}
,close : function(e) {
$optionsList[config.closeAnimation].call($optionsList, config.animationDuration, function() {
config.closeAnimationCallback($optionsList)
} )
$(window).unbind('click', _actions.closeOnOutsideClick)
config.onClose( $optionsList )
is_opened = false;
}
,closeOnOutsideClick : function(e) {
if( $(e.target).parents().is( $optionsList.parent() ) == false && $(e.target).is( $optionsList.parent() ) == false ) {
_actions.close()
}
},
setTo : function(scrolloffset, animate) {
scrolloffset = Math.max(0, Math.min( $scrollbox.height() - $scrollbar.height(),
scrolloffset ))
if( animate ) {
TweenLite.to( $scrollbar, .5, {css:{top:scrolloffset}} )
TweenLite.to( $optionsList.children('label').first(),
.5,
{css:{marginTop:Math.floor(-scrolloffset/scrollbar_ratio)}} )
} else {
$scrollbar.css({
top : scrolloffset + 'px'
});
$optionsList.children('label').first().css({
marginTop : Math.floor(-scrolloffset/scrollbar_ratio) + 'px'
})
}
}
,startMoving : function(e) {
var initial_mouse_position = ($.browser.msie && parseInt($.browser.version) < 9) ? {x : e.pageX , y : e.pageY } :
{x : e.clientX, y : e.clientY }
var scrollbar_start_position = parseInt( $scrollbar.css('top') )
var mousemoveHandler = function(e) {
prevent(e);
if( scrollbar_ratio == 0 ) return;
var new_mouse_position = ($.browser.msie && parseInt($.browser.version) < 9) ? {x : e.pageX , y : e.pageY } :
{x : e.clientX, y : e.clientY }
_actions.setTo(scrollbar_start_position + new_mouse_position.y - initial_mouse_position.y)
}
if( navigator.userAgent.match(/iP(ad|od|phone)|Android/) ) {
} else {
$(window).bind('mousemove', mousemoveHandler )
$(window).bind('mouseup', function() {
$(window).unbind('mousemove', mousemoveHandler )
})
}
}
,getOptions : function() {
return $selectedOptions
}
,mouseWheel : function(e) {
if( !is_opened ) return;
var e = window.event || e,
delta = -Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)))
_actions.setTo( $scrollbar.position().top + delta * 25 )
}
}
$.fn.smartSelect.allSelects.push(_actions);
$optionsList.css('height', config.listHeight + 'px')
$optionsList.siblings('.click-handler').click(_actions.open)
$options.each(function(ind) {
$optionsList.append('<label><span>'+$options.eq(ind).text()+'</span><input type="radio" name="'+$select.attr('name')+'" selected="'+( $selectedOption == $(this) ? 'selected' : 'false' )+'" value="'+$options.eq(ind).attr('value')+'" style="display:none"></label>')
})
$optionsList.find('label').unbind('click').bind('click', function(e) {
$(e.target).addClass('selected').siblings().removeClass('selected');
$value.text( $(this).find('span').text() );
config.onSelect( $optionsList, $(this).find('input').val(), $(this).find('span').text() )
_actions.close();
})
if( navigator.userAgent.match(/iP(ad|od|phone)|Android/) == null ) {
if( config.scroll == true ) {
if (window.addEventListener) {
/** DOMMouseScroll is for mozilla. */
window.addEventListener('mousewheel', _actions.mouseWheel, false);
window.addEventListener('DOMMouseScroll', _actions.mouseWheel, false);
} else {
/** IE/Opera. */
window.onmousewheel = document.onmousewheel = _actions.mouseWheel
}
}
} else {
$scrollbox.css({visibility:'hidden',opacity:0,zIndex:0});
$optionsList.css({overflow:'auto'})
/* $optionsList.get(0).addEventListener('touchstart',function(e) {
prevent(e)
}) */
}
config.onCreate( $optionsList )
// so lets not submit the select!
$select.removeAttr('name').hide();
}).addClass('smart-select')
return this;
}
|
var crypto = require('crypto');
// Bytesize
var len = 128;
// Current prefered algorithm
var currentAlgorithm = 'pbkdf2';
// Rounds of encryption
var currentIterations = 12000;
// root of hashing algorithm type hierarchy
var HashAlgorithm = function() {
};
HashAlgorithm.prototype = {
name : '',
adaptive : false,
doHash : function(hashArgs) {
throw "Algorithm not defined!";
}
};
// non-iterative hash functions supported by crypto
var SimpleHashAlgorithm = function(name) {
this.name = name;
};
SimpleHashAlgorithm.prototype = Object.create(HashAlgorithm.prototype, {
doHash : {
value : function(hashArgs, fn) {
var hash;
hash = crypto.createHash(this.name).update(
hashArgs.plaintext + hashArgs.salt).digest('base64');
fn(null, this.name + "$" + hash + '$' + hashArgs.salt);
}
}
});
// adaptive algorithm - need name + iterations
var AdaptiveHashAlgorithm = function(name, hashFunction) {
this.name = name;
this.doHash = hashFunction;
};
AdaptiveHashAlgorithm.prototype = Object.create(HashAlgorithm.prototype, {
adaptive : {
value : true
}
});
// This is an example of how to secure an obsolete hash with a wrapper adaptive
// algorithm. If both wrapper and wrapped algorithms are adaptive of course you
// will need to have a composite iteration field as well
var WrappedHashAlgorithm = function(name, wrappedAlgorithm, wrapperAlgorithm) {
this.name = name;
this.wrappedAlgorithm = wrappedAlgorithm;
this.wrapperAlgorithm = wrapperAlgorithm;
};
WrappedHashAlgorithm.prototype = Object
.create(AdaptiveHashAlgorithm.prototype,
{
wrappedAlgorithm : {
value : undefined
},
wrapperAlgorithm : {
value : undefined
},
doHash : {
value : function(hashArgs, fn) {
// 1st salt is for wrapped algorithm, 2nd for
// wrapper
var salts = hashArgs.salt.split('|');
var wrapperAlgorithm = this.wrapperAlgorithm;
var name = this.name;
var wrapHash = function(err, hash) {
if (err)
return fn(err);
fn(null, wrapperAlgorithm.name + '$'
+ hashArgs.iterations + '$'
+ hash.toString('base64') + '$'
+ hashArgs.salt);
};
// create wrapped hash with plaintext password
this.wrappedAlgorithm.doHash({
plaintext : hashArgs.plaintext,
salt : salts[0]
}, wrapHash);
}
}
});
// lookup table for the algorithms we support
var algorithms = {
sha1 : new SimpleHashAlgorithm('sha1'),
sha256 : new SimpleHashAlgorithm('sha256'),
pbkdf2 : new AdaptiveHashAlgorithm('pbkdf2', function(hashArgs, fn) {
// use crypto.pbkdf2 to generate hash
var onHash = function(err, hash) {
if (err)
return fn(err);
fn(null, 'pbkdf2$' + hashArgs.iterations + '$'
+ hash.toString('base64') + '$' + hashArgs.salt);
};
crypto.pbkdf2(hashArgs.plaintext, hashArgs.salt, hashArgs.iterations,
hashArgs.byteLen, onHash);
})
};
//here's how to wrap an obsolete hash
algorithms.sha1topbkdf2 = new WrappedHashAlgorithm('sha1topbkdf2',
algorithms.sha1, algorithms.pbkdf2);
// helper function to make secured credentials more readable
exports.splitCredentialFields = function(hash) {
// 3 fields for simple hash, 4 for adaptive
var fields = hash.split('$');
if (fields.length < 3 || fields.length > 4)
throw new Error('Hash should have 3 or 4 fields');
if (fields.length === 3) {
return {
algorithm : fields[0],
hash : fields[1],
salt : fields[2]
};
} else {
return {
algorithm : fields[0],
iterations : fields[1],
hash : fields[2],
salt : fields[3]
};
}
};
// Generate password hash with salt. If no salt provided, automatically
// generates it
exports.hash = function(password, salt, fn) {
if (salt !== undefined && arguments.length === 3) {
algorithms[currentAlgorithm].doHash({
plaintext : password,
salt : salt,
iterations : currentIterations,
byteLen : len
}, fn);
} else {
// no salt provided - generate and recursively call same function
if (typeof salt === 'function') {
fn = salt;
}
crypto.randomBytes(len, function(err, genSalt) {
if (err) {
return fn(err);
}
genSalt = genSalt.toString('base64');
exports.hash(password, genSalt, fn);
});
}
};
// verify password against secured credential using the algorithm, salt,
// iterations specified in the credential. If the credential is not using
// the current hash, re-hash and return the result
exports.verify = function(password, secureCredential, fn) {
var fields, hashArgs, algorithm;
// split and grab salt
fields = exports.splitCredentialFields(secureCredential);
algorithm = algorithms[fields.algorithm];
if (algorithm === undefined) {
return callback('Unsupported algorithm ' + fields[0]);
}
hashArgs = {
plaintext : password,
salt : fields.salt,
byteLen : new Buffer(fields.hash, 'base64').length
};
if (fields.iterations) {
hashArgs.iterations = parseInt(fields.iterations);
}
// delegate to algorithm implementation for actual hashing
algorithm.doHash(hashArgs, function(err, calcHash) {
if (err)
return fn(err);
if (calcHash !== secureCredential) {
console.log('\n\n\ncalcHash : ' + calcHash);
console.log('\nsecureCredential: ' + secureCredential);
fn(null, false);
} else {
if (fields.algorithm === currentAlgorithm
&& fields.iterations === currentIterations) {
fn(null, true);
} else {
// is obsolete algorithm
exports.hash(password, function(err, reash) {
fn(null, true, reash)
});
}
}
});
};
// wrap hash with pbkdf2 algorithm. because there is a wrapped and wrapper
// algorithm, we need to output both salts; using pipe ('|') as separator.
exports.wrapSha1 = function(hashToWrap, fn) {
var wrappedFields = exports.splitCredentialFields(hashToWrap);
crypto.randomBytes(len, function(err, genSalt) {
if (err)
return fn(err);
genSalt = genSalt.toString('base64');
algorithms.pbkdf2.doHash({
plaintext : hashToWrap,
salt : genSalt,
byteLen : len,
iterations : currentIterations
}, function(err, result) {
if (err)
return fn(err);
var wrapperFields = exports.splitCredentialFields(result);
// assemble final output
fn(null, algorithms.sha1topbkdf2.name + '$'
+ wrapperFields.iterations + '$' + wrapperFields.hash + '$'
+ wrappedFields.salt + '|' + wrapperFields.salt);
});
});
};
// can change these if not in production to allow various scenarios to be tested
if (process.env.NODE_ENV !== 'production') {
exports.setAlgorithm = function(newAlgorithm) {
currentAlgorithm = newAlgorithm;
}
exports.setIterations = function(newIterations) {
currentIterations = newIterations;
}
exports.setLen = function(newLen) {
len = newLen;
}
}
|
import _ from 'lodash'
import * as types from '../actions/types'
export default function reducer(state = {
availableFoundations: [],
selectedFoundations: [],
searchField: '',
selectedBuildpacks: [],
availableBuildpacks: [],
selectedAppStates: [],
availableAppStates: [],
sortBy: 'name-asc'
}, action) {
switch (action.type) {
case types.FETCH_FOUNDATIONS_FULFILLED: {
//when foundations are initially loaded, select them all
let foundations = [];
action.payload.forEach((foundation) => {
foundations.push(foundation.api)
})
return {
...state,
availableFoundations: foundations,
selectedFoundations: foundations
}
}
case types.FETCH_APP_FULFILLED: {
let buildpacks = [...state.availableBuildpacks]
buildpacks.push(action.payload.buildpack);
buildpacks = _.uniq(buildpacks);
let appStates = [...state.availableAppStates]
appStates.push(action.payload.state)
appStates = _.uniq(appStates);
return {
...state,
selectedBuildpacks: buildpacks,
availableBuildpacks: buildpacks,
selectedAppStates: appStates,
availableAppStates: appStates
}
}
case types.TOGGLE_FOUNDATION: {
let foundations = [...state.selectedFoundations]
if (foundations.indexOf(action.payload) !== -1) {
foundations.splice(foundations.indexOf(action.payload), 1)
} else {
foundations.push(action.payload);
}
return {
...state,
selectedFoundations: foundations
}
}
case types.SEARCH_FIELD_UPDATED: {
return {
...state,
searchField: action.payload
}
}
case types.TOGGLE_BUILDPACK: {
let buildpacks = [...state.selectedBuildpacks]
if (buildpacks.indexOf(action.payload) !== -1) {
buildpacks.splice(buildpacks.indexOf(action.payload), 1)
} else {
buildpacks.push(action.payload);
}
return {
...state,
selectedBuildpacks: buildpacks
}
}
case types.TOGGLE_APP_STATE: {
let appStates = [...state.selectedAppStates]
if (appStates.indexOf(action.payload) !== -1) {
appStates.splice(appStates.indexOf(action.payload), 1)
} else {
appStates.push(action.payload);
}
return {
...state,
selectedAppStates: appStates
}
}
case types.SORT_UPDATED: {
return {
...state,
sortBy: action.payload
}
}
default:
return state;
}
}
|
import Ember from 'ember';
export default Ember.Component.extend({
actions: {
addTurkart: function (navn) {
navn = navn || {};
let turkart = this.get('model.turkart') || [];
turkart.addObject(navn);
this.set('model.turkart', turkart);
},
removeTurkart: function (object) {
let turkart = this.get('model.turkart') || [];
turkart.removeObject(object);
this.set('model.turkart', turkart);
},
addOmrådeById: function (id) {
const model = this.get('model');
if (typeof model.addOmrådeById === 'function') {
model.addOmrådeById(id);
}
},
removeOmråde: function (område) {
let områder = this.get('model.områder') || [];
områder.removeObject(område);
}
}
});
|
'use strict';
module.exports = {
app: {
title: 'mecenate-web',
description: 'battlehack',
keywords: 'MEAN'
},
port: process.env.PORT || 3000,
templateEngine: 'swig',
sessionSecret: 'MEAN',
sessionCollection: 'sessions',
assets: {
lib: {
css: [
'public/lib/bootstrap/dist/css/bootstrap.css',
'public/lib/bootstrap/dist/css/bootstrap-theme.css',
],
js: [
'public/lib/angular/angular.js',
'public/lib/angular-resource/angular-resource.js',
'public/lib/angular-ui-router/release/angular-ui-router.js',
'public/lib/angular-ui-utils/ui-utils.js',
'public/lib/angular-bootstrap/ui-bootstrap-tpls.js',
// added
'public/lib/lodash/lodash.min.js',
'public/lib/ng-lodash/build/ng-lodash.js',
'public/lib/angular-google-maps/dist/angular-google-maps.min.js'
]
},
css: [
'public/modules/**/css/*.css'
],
js: [
'public/config.js',
'public/application.js',
'public/modules/*/*.js',
'public/modules/*/*[!tests]*/*.js'
],
tests: [
'public/lib/angular-mocks/angular-mocks.js',
'public/modules/*/tests/*.js'
]
}
};
|
const _log = console.log.bind(console);
let hijacked = false;
let fullLog = '';
_log.clear = function () {
fullLog = '';
};
_log.get = function () {
return fullLog;
};
function hijackLog() {
if (hijacked) return _log;
console.warn("The console.log has been hijacked by react-repl. This is not a security alert, it's a notice to developers.");
console.log = function(...args) {
fullLog += (fullLog ? "\n":'') +
args.map(v =>
(typeof v === 'string') ?
`${v} ` : JSON.stringify(v, null, 2) + "\n").join('');
_log.apply(console, args);
}
hijacked = true;
return _log;
}
module.exports = hijackLog;
|
// @flow
import type { ApiBooking } from '../../../../common/apiTypes';
import { getDateString } from '../../../../common/utils';
import { Room, Booking } from '../models';
import findTimeslots from '../../utils/findTimeslots';
import checkBooking from '../../utils/checkBooking';
// GET /booking/{bookingId}
export function getBooking(req: express$Request, res: express$Response) {
Booking.findById(req.params.bookingId)
.then(bookings => res.json(bookings))
.catch(err => res.send(err));
}
// GET /bookings
// returns a map (bookingId: {day, start, duration, roomId, bookingId})
export function getAllBookings(req: express$Request, res: express$Response) {
Booking.find()
.then(bookings => res.json(bookings))
.catch(err => res.send(err));
}
// GET /bookings/rooms/{roomId}
export function getBookingsForRoom(req: express$Request, res: express$Response) {
Booking.find({ roomId: req.params.roomId })
.then(bookings => res.json(bookings))
.catch(err => res.send(err));
}
// GET /timeslots/{roomId}/ for today or
// GET /timeslots/{roomId}/?date=YYYY-MM-DD for any future date
// returns an array of time strings
export function getTimeslots(req: express$Request, res: express$Response) {
let date = new Date();
if (req.query.date) {
const newDate = req.query.date;
if (typeof newDate === 'string') {
date = new Date(newDate);
} else {
date = new Date(newDate[0]);
}
}
Booking.find({ roomId: req.params.roomId, day: getDateString(date) })
.then(bookings => {
const timeslots = findTimeslots(bookings, date);
res.json(timeslots);
})
.catch(err => res.send(err));
}
// POST /bookings
// Request body contains start and duration, day is optional (default today)
// returns a booking id (UUID)
export function createBooking(req: any, res: express$Response) {
const bookingProposal: ApiBooking = req.body;
Room.count({ id: bookingProposal.roomId })
.then(count => {
if (count > 0) {
res.status(400);
res.send('Room does not exist');
}
if (!checkBooking(bookingProposal)) {
res.status(400);
res.send('Booking invalid');
}
const booking = new Booking(bookingProposal);
booking
.save()
.then(bookingResult => {
res.json(bookingResult);
})
.catch(err => {
res.send(err);
});
})
.catch(err => res.send(err));
}
// DELETE /bookings/{bookingId}/ to delete a specific booking
export function deleteBooking(req: express$Request, res: express$Response) {
Booking.find({ id: req.params.bookingId })
.then(() => res.json({ message: `Booking ${req.params.bookingId} successfully deleted` }))
.catch(err => res.send(err));
}
// DELETE /bookings/rooms/{roomId} to delete all bookings for that specific room
export function deleteBookingsForRoom(req: express$Request, res: express$Response) {
Booking.deleteMany({ roomId: req.params.roomId })
.then(() => res.json({ message: `Bookings for room ${req.params.roomId} successfully deleted` }))
.catch(err => res.send(err));
}
|
/**
* turn.js 4th release
* turnjs.com
* turnjs.com/license.txt
*
* Copyright (C) 2012 Emmanuel Garcia
* All rights reserved
**/
(function($) {
'use strict';
var has3d,
hasRot,
vendor = '',
version = '4.1.0',
PI = Math.PI,
A90 = PI/2,
isTouch = 'ontouchstart' in window,
mouseEvents = (isTouch) ?
{
down: 'touchstart',
move: 'touchmove',
up: 'touchend',
over: 'touchstart',
out: 'touchend'
}
:
{
down: 'mousedown',
move: 'mousemove',
up: 'mouseup',
over: 'mouseover',
out: 'mouseout'
},
// Contansts used for each corner
// | tl * tr |
// l | * * | r
// | bl * br |
corners = {
backward: ['bl', 'tl'],
forward: ['br', 'tr'],
all: ['tl', 'bl', 'tr', 'br', 'l', 'r']
},
// Display values
displays = ['single', 'double'],
// Direction values
directions = ['ltr', 'rtl'],
// Default options
turnOptions = {
// Enables hardware acceleration
acceleration: true,
// Display
display: 'double',
// Duration of transition in milliseconds
duration: 600,
// First page
page: 1,
// Enables gradients
gradients: true,
// Corners used when turning the page
turnCorners: 'bl,br',
// Events
when: null
},
flipOptions = {
// Size of the active zone of each corner
cornerSize: 100
},
// Number of pages in the DOM, minimum value: 6
pagesInDOM = 6,
turnMethods = {
// Singleton constructor
// $('#selector').turn([options]);
init: function(options) {
// Define constants
has3d = 'WebKitCSSMatrix' in window || 'MozPerspective' in document.body.style;
hasRot = rotationAvailable();
vendor = getPrefix();
var i, that = this, pageNum = 0, data = this.data(), ch = this.children();
// Set initial configuration
options = $.extend({
width: this.width(),
height: this.height(),
direction: this.attr('dir') || this.css('direction') || 'ltr'
}, turnOptions, options);
data.opts = options;
data.pageObjs = {};
data.pages = {};
data.pageWrap = {};
data.pageZoom = {};
data.pagePlace = {};
data.pageMv = [];
data.zoom = 1;
data.totalPages = options.pages || 0;
data.eventHandlers = {
touchStart: $.proxy(turnMethods._touchStart, this),
touchMove: $.proxy(turnMethods._touchMove, this),
touchEnd: $.proxy(turnMethods._touchEnd, this),
start: $.proxy(turnMethods._eventStart, this)
};
// Add event listeners
if (options.when)
for (i in options.when)
if (has(i, options.when))
this.bind(i, options.when[i]);
// Set the css
this.css({position: 'relative', width: options.width, height: options.height});
// Set the initial display
this.turn('display', options.display);
// Set the direction
if (options.direction!=='')
this.turn('direction', options.direction);
// Prevent blue screen problems of switching to hardware acceleration mode
// By forcing hardware acceleration for ever
if (has3d && !isTouch && options.acceleration)
this.transform(translate(0, 0, true));
// Add pages from the DOM
for (i = 0; i<ch.length; i++) {
if ($(ch[i]).attr('ignore')!='1') {
this.turn('addPage', ch[i], ++pageNum);
}
}
// Event listeners
$(this).bind(mouseEvents.down, data.eventHandlers.touchStart).
bind('end', turnMethods._eventEnd).
bind('pressed', turnMethods._eventPressed).
bind('released', turnMethods._eventReleased).
bind('flip', turnMethods._flip);
$(this).parent().bind('start', data.eventHandlers.start);
$(document).bind(mouseEvents.move, data.eventHandlers.touchMove).
bind(mouseEvents.up, data.eventHandlers.touchEnd);
// Set the initial page
this.turn('page', options.page);
// This flipbook is ready
data.done = true;
return this;
},
// Adds a page from external data
addPage: function(element, page) {
var currentPage,
className,
incPages = false,
data = this.data(),
lastPage = data.totalPages+1;
if (data.destroying)
return false;
// Read the page number from the className of `element` - format: p[0-9]+
if ((currentPage = /\bp([0-9]+)\b/.exec($(element).attr('class'))))
page = parseInt(currentPage[1], 10);
if (page) {
if (page==lastPage)
incPages = true;
else if (page>lastPage)
throw turnError('Page "'+page+'" cannot be inserted');
} else {
page = lastPage;
incPages = true;
}
if (page>=1 && page<=lastPage) {
if (data.display=='double')
className = (page%2) ? ' odd' : ' even';
else
className = '';
// Stop animations
if (data.done)
this.turn('stop');
// Move pages if it's necessary
if (page in data.pageObjs)
turnMethods._movePages.call(this, page, 1);
// Increase the number of pages
if (incPages)
data.totalPages = lastPage;
// Add element
data.pageObjs[page] = $(element).
css({'float': 'left'}).
addClass('page p' + page + className);
if (!hasHardPage() && data.pageObjs[page].hasClass('hard')) {
data.pageObjs[page].removeClass('hard');
}
// Add page
turnMethods._addPage.call(this, page);
// Remove pages out of range
turnMethods._removeFromDOM.call(this);
}
return this;
},
// Adds a page
_addPage: function(page) {
var data = this.data(),
element = data.pageObjs[page];
if (element)
if (turnMethods._necessPage.call(this, page)) {
if (!data.pageWrap[page]) {
// Wrapper
data.pageWrap[page] = $('<div/>',
{'class': 'page-wrapper',
page: page,
css: {position: 'absolute',
overflow: 'hidden'}});
// Append to this flipbook
this.append(data.pageWrap[page]);
if (!data.pagePlace[page]) {
data.pagePlace[page] = page;
// Move `pageObjs[page]` to wrapper
data.pageObjs[page].appendTo(data.pageWrap[page]);
}
// Set the size of the page
var prop = turnMethods._pageSize.call(this, page, true);
element.css({width: prop.width, height: prop.height});
data.pageWrap[page].css(prop);
}
if (data.pagePlace[page] == page) {
// If the page isn't in another place, create the flip effect
turnMethods._makeFlip.call(this, page);
}
} else {
// Place
data.pagePlace[page] = 0;
// Remove element from the DOM
if (data.pageObjs[page])
data.pageObjs[page].remove();
}
},
// Checks if a page is in memory
hasPage: function(page) {
return has(page, this.data().pageObjs);
},
// Centers the flipbook
center: function(page) {
var data = this.data(),
size = $(this).turn('size'),
left = 0;
if (!data.noCenter) {
if (data.display=='double') {
var view = this.turn('view', page || data.tpage || data.page);
if (data.direction=='ltr') {
if (!view[0])
left -= size.width/4;
else if (!view[1])
left += size.width/4;
} else {
if (!view[0])
left += size.width/4;
else if (!view[1])
left -= size.width/4;
}
}
$(this).css({marginLeft: left});
}
return this;
},
// Destroys the flipbook
destroy: function () {
var page,
flipbook = this,
data = this.data(),
events = [
'end', 'first', 'flip', 'last', 'pressed',
'released', 'start', 'turning', 'turned',
'zooming', 'missing'];
if (trigger('destroying', this)=='prevented')
return;
data.destroying = true;
$.each(events, function(index, eventName) {
flipbook.unbind(eventName);
});
this.parent().unbind('start', data.eventHandlers.start);
$(document).unbind(mouseEvents.move, data.eventHandlers.touchMove).
unbind(mouseEvents.up, data.eventHandlers.touchEnd);
while (data.totalPages!==0) {
this.turn('removePage', data.totalPages);
}
if (data.fparent)
data.fparent.remove();
if (data.shadow)
data.shadow.remove();
this.removeData();
data = null;
return this;
},
// Checks if this element is a flipbook
is: function() {
return typeof(this.data().pages)=='object';
},
// Sets and gets the zoom value
zoom: function(newZoom) {
var data = this.data();
if (typeof(newZoom)=='number') {
if (newZoom<0.001 || newZoom>100)
throw turnError(newZoom+ ' is not a value for zoom');
if (trigger('zooming', this, [newZoom, data.zoom])=='prevented')
return this;
var size = this.turn('size'),
currentView = this.turn('view'),
iz = 1/data.zoom,
newWidth = Math.round(size.width * iz * newZoom),
newHeight = Math.round(size.height * iz * newZoom);
data.zoom = newZoom;
$(this).turn('stop').
turn('size', newWidth, newHeight);
/*.
css({marginTop: size.height * iz / 2 - newHeight / 2});*/
if (data.opts.autoCenter)
this.turn('center');
/*else
$(this).css({marginLeft: size.width * iz / 2 - newWidth / 2});*/
turnMethods._updateShadow.call(this);
for (var i = 0; i<currentView.length; i++) {
if (currentView[i] && data.pageZoom[currentView[i]]!=data.zoom) {
this.trigger('zoomed',[
currentView[i],
currentView,
data.pageZoom[currentView[i]],
data.zoom]);
data.pageZoom[currentView[i]] = data.zoom;
}
}
return this;
} else
return data.zoom;
},
// Gets the size of a page
_pageSize: function(page, position) {
var data = this.data(),
prop = {};
if (data.display=='single') {
prop.width = this.width();
prop.height = this.height();
if (position) {
prop.top = 0;
prop.left = 0;
prop.right = 'auto';
}
} else {
var pageWidth = this.width()/2,
pageHeight = this.height();
if (data.pageObjs[page].hasClass('own-size')) {
prop.width = data.pageObjs[page].width();
prop.height = data.pageObjs[page].height();
} else {
prop.width = pageWidth;
prop.height = pageHeight;
}
if (position) {
var odd = page%2;
prop.top = (pageHeight-prop.height)/2;
if (data.direction=='ltr') {
prop[(odd) ? 'right' : 'left'] = pageWidth-prop.width;
prop[(odd) ? 'left' : 'right'] = 'auto';
} else {
prop[(odd) ? 'left' : 'right'] = pageWidth-prop.width;
prop[(odd) ? 'right' : 'left'] = 'auto';
}
}
}
return prop;
},
// Prepares the flip effect for a page
_makeFlip: function(page) {
var data = this.data();
if (!data.pages[page] && data.pagePlace[page]==page) {
var single = data.display=='single',
odd = page%2;
data.pages[page] = data.pageObjs[page].
css(turnMethods._pageSize.call(this, page)).
flip({
page: page,
next: (odd || single) ? page+1 : page-1,
turn: this
}).
flip('disable', data.disabled);
// Issue about z-index
turnMethods._setPageLoc.call(this, page);
data.pageZoom[page] = data.zoom;
}
return data.pages[page];
},
// Makes pages within a range
_makeRange: function() {
var page, range,
data = this.data();
if (data.totalPages<1)
return;
range = this.turn('range');
for (page = range[0]; page<=range[1]; page++)
turnMethods._addPage.call(this, page);
},
// Returns a range of pages that should be in the DOM
// Example:
// - page in the current view, return true
// * page is in the range, return true
// Otherwise, return false
//
// 1 2-3 4-5 6-7 8-9 10-11 12-13
// ** ** -- ** **
range: function(page) {
var remainingPages, left, right, view,
data = this.data();
page = page || data.tpage || data.page || 1;
view = turnMethods._view.call(this, page);
if (page<1 || page>data.totalPages)
throw turnError('"'+page+'" is not a valid page');
view[1] = view[1] || view[0];
if (view[0]>=1 && view[1]<=data.totalPages) {
remainingPages = Math.floor((pagesInDOM-2)/2);
if (data.totalPages-view[1] > view[0]) {
left = Math.min(view[0]-1, remainingPages);
right = 2*remainingPages-left;
} else {
right = Math.min(data.totalPages-view[1], remainingPages);
left = 2*remainingPages-right;
}
} else {
left = pagesInDOM-1;
right = pagesInDOM-1;
}
return [Math.max(1, view[0]-left),
Math.min(data.totalPages, view[1]+right)];
},
// Detects if a page is within the range of `pagesInDOM` from the current view
_necessPage: function(page) {
if (page===0)
return true;
var range = this.turn('range');
return this.data().pageObjs[page].hasClass('fixed') ||
(page>=range[0] && page<=range[1]);
},
// Releases memory by removing pages from the DOM
_removeFromDOM: function() {
var page, data = this.data();
for (page in data.pageWrap)
if (has(page, data.pageWrap) &&
!turnMethods._necessPage.call(this, page))
turnMethods._removePageFromDOM.call(this, page);
},
// Removes a page from DOM and its internal references
_removePageFromDOM: function(page) {
var data = this.data();
if (data.pages[page]) {
var dd = data.pages[page].data();
flipMethods._moveFoldingPage.call(data.pages[page], false);
if (dd.f && dd.f.fwrapper)
dd.f.fwrapper.remove();
data.pages[page].removeData();
data.pages[page].remove();
delete data.pages[page];
}
if (data.pageObjs[page])
data.pageObjs[page].remove();
if (data.pageWrap[page]) {
data.pageWrap[page].remove();
delete data.pageWrap[page];
}
turnMethods._removeMv.call(this, page);
delete data.pagePlace[page];
delete data.pageZoom[page];
},
// Removes a page
removePage: function(page) {
var data = this.data();
// Delete all the pages
if (page=='*') {
while (data.totalPages!==0) {
this.turn('removePage', data.totalPages);
}
} else {
if (page<1 || page>data.totalPages)
throw turnError('The page '+ page + ' doesn\'t exist');
if (data.pageObjs[page]) {
// Stop animations
this.turn('stop');
// Remove `page`
turnMethods._removePageFromDOM.call(this, page);
delete data.pageObjs[page];
}
// Move the pages
turnMethods._movePages.call(this, page, -1);
// Resize the size of this flipbook
data.totalPages = data.totalPages-1;
// Check the current view
if (data.page>data.totalPages) {
data.page = null;
turnMethods._fitPage.call(this, data.totalPages);
} else {
turnMethods._makeRange.call(this);
this.turn('update');
}
}
return this;
},
// Moves pages
_movePages: function(from, change) {
var page,
that = this,
data = this.data(),
single = data.display=='single',
move = function(page) {
var next = page + change,
odd = next%2,
className = (odd) ? ' odd ' : ' even ';
if (data.pageObjs[page])
data.pageObjs[next] = data.pageObjs[page].
removeClass('p' + page + ' odd even').
addClass('p' + next + className);
if (data.pagePlace[page] && data.pageWrap[page]) {
data.pagePlace[next] = next;
if (data.pageObjs[next].hasClass('fixed'))
data.pageWrap[next] = data.pageWrap[page].
attr('page', next);
else
data.pageWrap[next] = data.pageWrap[page].
css(turnMethods._pageSize.call(that, next, true)).
attr('page', next);
if (data.pages[page])
data.pages[next] = data.pages[page].
flip('options', {
page: next,
next: (single || odd) ? next+1 : next-1
});
if (change) {
delete data.pages[page];
delete data.pagePlace[page];
delete data.pageZoom[page];
delete data.pageObjs[page];
delete data.pageWrap[page];
}
}
};
if (change>0)
for (page=data.totalPages; page>=from; page--)
move(page);
else
for (page=from; page<=data.totalPages; page++)
move(page);
},
// Sets or Gets the display mode
display: function(display) {
var data = this.data(),
currentDisplay = data.display;
if (display===undefined) {
return currentDisplay;
} else {
if ($.inArray(display, displays)==-1)
throw turnError('"'+display + '" is not a value for display');
switch(display) {
case 'single':
// Create a temporal page to use as folded page
if (!data.pageObjs[0]) {
this.turn('stop').
css({'overflow': 'hidden'});
data.pageObjs[0] = $('<div />',
{'class': 'page p-temporal'}).
css({width: this.width(), height: this.height()}).
appendTo(this);
}
this.addClass('shadow');
break;
case 'double':
// Remove the temporal page
if (data.pageObjs[0]) {
this.turn('stop').css({'overflow': ''});
data.pageObjs[0].remove();
delete data.pageObjs[0];
}
this.removeClass('shadow');
break;
}
data.display = display;
if (currentDisplay) {
var size = this.turn('size');
turnMethods._movePages.call(this, 1, 0);
this.turn('size', size.width, size.height).
turn('update');
}
return this;
}
},
// Gets and sets the direction of the flipbook
direction: function(dir) {
var data = this.data();
if (dir===undefined) {
return data.direction;
} else {
dir = dir.toLowerCase();
if ($.inArray(dir, directions)==-1)
throw turnError('"' + dir + '" is not a value for direction');
if (dir=='rtl') {
$(this).attr('dir', 'ltr').
css({direction: 'ltr'});
}
data.direction = dir;
if (data.done)
this.turn('size', $(this).width(), $(this).height());
return this;
}
},
// Detects animation
animating: function() {
return this.data().pageMv.length>0;
},
// Gets the current activated corner
corner: function() {
var corner,
page,
data = this.data();
for (page in data.pages) {
if (has(page, data.pages))
if ((corner = data.pages[page].flip('corner'))) {
return corner;
}
}
return false;
},
// Gets the data stored in the flipbook
data: function() {
return this.data();
},
// Disables and enables the effect
disable: function(disable) {
var page,
data = this.data(),
view = this.turn('view');
data.disabled = disable===undefined || disable===true;
for (page in data.pages) {
if (has(page, data.pages))
data.pages[page].flip('disable',
(data.disabled) ? true : $.inArray(parseInt(page, 10), view)==-1);
}
return this;
},
// Disables and enables the effect
disabled: function(disable) {
if (disable===undefined) {
return this.data().disabled===true;
} else {
return this.turn('disable', disable);
}
},
// Gets and sets the size
size: function(width, height) {
if (width===undefined || height===undefined) {
return {width: this.width(), height: this.height()};
} else {
this.turn('stop');
var page, prop,
data = this.data(),
pageWidth = (data.display=='double') ? width/2 : width;
this.css({width: width, height: height});
if (data.pageObjs[0])
data.pageObjs[0].css({width: pageWidth, height: height});
for (page in data.pageWrap) {
if (!has(page, data.pageWrap)) continue;
prop = turnMethods._pageSize.call(this, page, true);
data.pageObjs[page].css({width: prop.width, height: prop.height});
data.pageWrap[page].css(prop);
if (data.pages[page])
data.pages[page].css({width: prop.width, height: prop.height});
}
this.turn('resize');
return this;
}
},
// Resizes each page
resize: function() {
var page, data = this.data();
if (data.pages[0]) {
data.pageWrap[0].css({left: -this.width()});
data.pages[0].flip('resize', true);
}
for (page = 1; page <= data.totalPages; page++)
if (data.pages[page])
data.pages[page].flip('resize', true);
turnMethods._updateShadow.call(this);
if (data.opts.autoCenter)
this.turn('center');
},
// Removes an animation from the cache
_removeMv: function(page) {
var i, data = this.data();
for (i=0; i<data.pageMv.length; i++)
if (data.pageMv[i]==page) {
data.pageMv.splice(i, 1);
return true;
}
return false;
},
// Adds an animation to the cache
_addMv: function(page) {
var data = this.data();
turnMethods._removeMv.call(this, page);
data.pageMv.push(page);
},
// Gets indexes for a view
_view: function(page) {
var data = this.data();
page = page || data.page;
if (data.display=='double')
return (page%2) ? [page-1, page] : [page, page+1];
else
return [page];
},
// Gets a view
view: function(page) {
var data = this.data(),
view = turnMethods._view.call(this, page);
if (data.display=='double')
return [(view[0]>0) ? view[0] : 0,
(view[1]<=data.totalPages) ? view[1] : 0];
else
return [(view[0]>0 && view[0]<=data.totalPages) ? view[0] : 0];
},
// Stops animations
stop: function(ignore, animate) {
if (this.turn('animating')) {
var i, opts, page,
data = this.data();
if (data.tpage) {
data.page = data.tpage;
delete data['tpage'];
}
for (i = 0; i<data.pageMv.length; i++) {
if (!data.pageMv[i] || data.pageMv[i]===ignore)
continue;
page = data.pages[data.pageMv[i]];
opts = page.data().f.opts;
page.flip('hideFoldedPage', animate);
if (!animate)
flipMethods._moveFoldingPage.call(page, false);
if (opts.force) {
opts.next = (opts.page%2===0) ? opts.page-1 : opts.page+1;
delete opts['force'];
}
}
}
this.turn('update');
return this;
},
// Gets and sets the number of pages
pages: function(pages) {
var data = this.data();
if (pages) {
if (pages<data.totalPages) {
for (var page = data.totalPages; page>pages; page--)
this.turn('removePage', page);
}
data.totalPages = pages;
turnMethods._fitPage.call(this, data.page);
return this;
} else
return data.totalPages;
},
// Checks missing pages
_missing : function(page) {
var data = this.data();
if (data.totalPages<1)
return;
var p,
range = this.turn('range', page),
missing = [];
for (p = range[0]; p<=range[1]; p++) {
if (!data.pageObjs[p])
missing.push(p);
}
if (missing.length>0)
this.trigger('missing', [missing]);
},
// Sets a page without effect
_fitPage: function(page) {
var data = this.data(),
newView = this.turn('view', page);
turnMethods._missing.call(this, page);
if (!data.pageObjs[page])
return;
data.page = page;
this.turn('stop');
for (var i = 0; i<newView.length; i++) {
if (newView[i] && data.pageZoom[newView[i]]!=data.zoom) {
this.trigger('zoomed',[
newView[i],
newView,
data.pageZoom[newView[i]],
data.zoom]);
data.pageZoom[newView[i]] = data.zoom;
}
}
turnMethods._removeFromDOM.call(this);
turnMethods._makeRange.call(this);
turnMethods._updateShadow.call(this);
this.trigger('turned', [page, newView]);
this.turn('update');
if (data.opts.autoCenter)
this.turn('center');
},
// Turns the page
_turnPage: function(page) {
var current,
next,
data = this.data(),
place = data.pagePlace[page],
view = this.turn('view'),
newView = this.turn('view', page);
if (data.page!=page) {
var currentPage = data.page;
if (trigger('turning', this, [page, newView])=='prevented') {
if (currentPage==data.page && $.inArray(place, data.pageMv)!=-1)
data.pages[place].flip('hideFoldedPage', true);
return;
}
if ($.inArray(1, newView)!=-1)
this.trigger('first');
if ($.inArray(data.totalPages, newView)!=-1)
this.trigger('last');
}
if (data.display=='single') {
current = view[0];
next = newView[0];
} else if (view[1] && page>view[1]) {
current = view[1];
next = newView[0];
} else if (view[0] && page<view[0]) {
current = view[0];
next = newView[1];
}
var optsCorners = data.opts.turnCorners.split(','),
flipData = data.pages[current].data().f,
opts = flipData.opts,
actualPoint = flipData.point;
turnMethods._missing.call(this, page);
if (!data.pageObjs[page])
return;
this.turn('stop');
data.page = page;
turnMethods._makeRange.call(this);
data.tpage = next;
if (opts.next!=next) {
opts.next = next;
opts.force = true;
}
this.turn('update');
flipData.point = actualPoint;
if (flipData.effect=='hard')
if (data.direction=='ltr')
data.pages[current].flip('turnPage',
(page>current) ? 'r' : 'l');
else
data.pages[current].flip('turnPage',
(page>current) ? 'l' : 'r');
else {
if (data.direction=='ltr')
data.pages[current].flip('turnPage',
optsCorners[(page>current) ? 1 : 0]);
else
data.pages[current].flip('turnPage',
optsCorners[(page>current) ? 0 : 1]);
}
},
// Gets and sets a page
page: function(page) {
var data = this.data();
if (page===undefined) {
return data.page;
} else {
if (!data.disabled && !data.destroying) {
page = parseInt(page, 10);
if (page>0 && page<=data.totalPages) {
if (page!=data.page) {
if (!data.done || $.inArray(page, this.turn('view'))!=-1)
turnMethods._fitPage.call(this, page);
else
turnMethods._turnPage.call(this, page);
}
return this;
} else {
throw turnError('The page ' + page + ' does not exist');
}
}
}
},
// Turns to the next view
next: function() {
return this.turn('page', Math.min(this.data().totalPages,
turnMethods._view.call(this, this.data().page).pop() + 1));
},
// Turns to the previous view
previous: function() {
return this.turn('page', Math.max(1,
turnMethods._view.call(this, this.data().page).shift() - 1));
},
// Shows a peeling corner
peel: function(corner, animate) {
var data = this.data(),
view = this.turn('view');
animate = (animate===undefined) ? true : animate===true;
if (corner===false) {
this.turn('stop', null, animate);
} else {
if (data.display=='single') {
data.pages[data.page].flip('peel', corner, animate);
} else {
var page;
if (data.direction=='ltr') {
page = (corner.indexOf('l')!=-1) ? view[0] : view[1];
} else {
page = (corner.indexOf('l')!=-1) ? view[1] : view[0];
}
if (data.pages[page])
data.pages[page].flip('peel', corner, animate);
}
}
return this;
},
// Adds a motion to the internal list
// This event is called in context of flip
_addMotionPage: function() {
var opts = $(this).data().f.opts,
turn = opts.turn,
dd = turn.data();
turnMethods._addMv.call(turn, opts.page);
},
// This event is called in context of flip
_eventStart: function(e, opts, corner) {
var data = opts.turn.data(),
actualZoom = data.pageZoom[opts.page];
if (e.isDefaultPrevented()) {
turnMethods._updateShadow.call(opts.turn);
return;
}
if (actualZoom && actualZoom!=data.zoom) {
opts.turn.trigger('zoomed',[
opts.page,
opts.turn.turn('view', opts.page),
actualZoom,
data.zoom]);
data.pageZoom[opts.page] = data.zoom;
}
if (data.display=='single' && corner) {
if ((corner.charAt(1)=='l' && data.direction=='ltr') ||
(corner.charAt(1)=='r' && data.direction=='rtl'))
{
opts.next = (opts.next<opts.page) ? opts.next : opts.page-1;
opts.force = true;
} else {
opts.next = (opts.next>opts.page) ? opts.next : opts.page+1;
}
}
turnMethods._addMotionPage.call(e.target);
turnMethods._updateShadow.call(opts.turn);
},
// This event is called in context of flip
_eventEnd: function(e, opts, turned) {
var that = $(e.target),
data = that.data().f,
turn = opts.turn,
dd = turn.data();
if (turned) {
var tpage = dd.tpage || dd.page;
if (tpage==opts.next || tpage==opts.page) {
delete dd.tpage;
turnMethods._fitPage.call(turn, tpage || opts.next, true);
}
} else {
turnMethods._removeMv.call(turn, opts.page);
turnMethods._updateShadow.call(turn);
turn.turn('update');
}
},
// This event is called in context of flip
_eventPressed: function(e) {
var page,
data = $(e.target).data().f,
turn = data.opts.turn,
turnData = turn.data(),
pages = turnData.pages;
turnData.mouseAction = true;
turn.turn('update');
return data.time = new Date().getTime();
},
// This event is called in context of flip
_eventReleased: function(e, point) {
var outArea,
page = $(e.target),
data = page.data().f,
turn = data.opts.turn,
turnData = turn.data();
if (turnData.display=='single') {
outArea = (point.corner=='br' || point.corner=='tr') ?
point.x<page.width()/2:
point.x>page.width()/2;
} else {
outArea = point.x<0 || point.x>page.width();
}
if ((new Date()).getTime()-data.time<200 || outArea) {
e.preventDefault();
turnMethods._turnPage.call(turn, data.opts.next);
}
turnData.mouseAction = false;
},
// This event is called in context of flip
_flip: function(e) {
e.stopPropagation();
var opts = $(e.target).data().f.opts;
opts.turn.trigger('turn', [opts.next]);
if (opts.turn.data().opts.autoCenter) {
opts.turn.turn('center', opts.next);
}
},
//
_touchStart: function() {
var data = this.data();
for (var page in data.pages) {
if (has(page, data.pages) &&
flipMethods._eventStart.apply(data.pages[page], arguments)===false) {
return false;
}
}
},
//
_touchMove: function() {
var data = this.data();
for (var page in data.pages) {
if (has(page, data.pages)) {
flipMethods._eventMove.apply(data.pages[page], arguments);
}
}
},
//
_touchEnd: function() {
var data = this.data();
for (var page in data.pages) {
if (has(page, data.pages)) {
flipMethods._eventEnd.apply(data.pages[page], arguments);
}
}
},
// Calculate the z-index value for pages during the animation
calculateZ: function(mv) {
var i, page, nextPage, placePage, dpage,
that = this,
data = this.data(),
view = this.turn('view'),
currentPage = view[0] || view[1],
total = mv.length-1,
r = {pageZ: {}, partZ: {}, pageV: {}},
addView = function(page) {
var view = that.turn('view', page);
if (view[0]) r.pageV[view[0]] = true;
if (view[1]) r.pageV[view[1]] = true;
};
for (i = 0; i<=total; i++) {
page = mv[i];
nextPage = data.pages[page].data().f.opts.next;
placePage = data.pagePlace[page];
addView(page);
addView(nextPage);
dpage = (data.pagePlace[nextPage]==nextPage) ? nextPage : page;
r.pageZ[dpage] = data.totalPages - Math.abs(currentPage-dpage);
r.partZ[placePage] = data.totalPages*2 - total + i;
}
return r;
},
// Updates the z-index and display property of every page
update: function() {
var page,
data = this.data();
if (this.turn('animating') && data.pageMv[0]!==0) {
// Update motion
var p, apage, fixed,
pos = this.turn('calculateZ', data.pageMv),
corner = this.turn('corner'),
actualView = this.turn('view'),
newView = this.turn('view', data.tpage);
for (page in data.pageWrap) {
if (!has(page, data.pageWrap))
continue;
fixed = data.pageObjs[page].hasClass('fixed');
data.pageWrap[page].css({
display: (pos.pageV[page] || fixed) ? '' : 'none',
zIndex:
(data.pageObjs[page].hasClass('hard') ?
pos.partZ[page]
:
pos.pageZ[page]
) || (fixed ? -1 : 0)
});
if ((p = data.pages[page])) {
p.flip('z', pos.partZ[page] || null);
if (pos.pageV[page])
p.flip('resize');
if (data.tpage) { // Is it turning the page to `tpage`?
p.flip('hover', false).
flip('disable',
$.inArray(parseInt(page, 10), data.pageMv)==-1 &&
page!=newView[0] &&
page!=newView[1]);
} else {
p.flip('hover', corner===false).
flip('disable', page!=actualView[0] && page!=actualView[1]);
}
}
}
} else {
// Update static pages
for (page in data.pageWrap) {
if (!has(page, data.pageWrap))
continue;
var pageLocation = turnMethods._setPageLoc.call(this, page);
if (data.pages[page]) {
data.pages[page].
flip('disable', data.disabled || pageLocation!=1).
flip('hover', true).
flip('z', null);
}
}
}
return this;
},
// Updates the position and size of the flipbook's shadow
_updateShadow: function() {
var view, view2, shadow,
data = this.data(),
width = this.width(),
height = this.height(),
pageWidth = (data.display=='single') ? width : width/2;
view = this.turn('view');
if (!data.shadow) {
data.shadow = $('<div />', {
'class': 'shadow',
'css': divAtt(0, 0, 0).css
}).
appendTo(this);
}
for (var i = 0; i<data.pageMv.length; i++) {
if (!view[0] || !view[1])
break;
view = this.turn('view', data.pages[data.pageMv[i]].data().f.opts.next);
view2 = this.turn('view', data.pageMv[i]);
view[0] = view[0] && view2[0];
view[1] = view[1] && view2[1];
}
if (!view[0]) shadow = (data.direction=='ltr') ? 1 : 2;
else if (!view[1]) shadow = (data.direction=='ltr') ? 2 : 1;
else shadow = 3;
switch (shadow) {
case 1:
data.shadow.css({
width: pageWidth,
height: height,
top: 0,
left: pageWidth
});
break;
case 2:
data.shadow.css({
width: pageWidth,
height: height,
top: 0,
left: 0
});
break;
case 3:
data.shadow.css({
width: width,
height: height,
top: 0,
left: 0
});
break;
}
},
// Sets the z-index and display property of a page
// It depends on the current view
_setPageLoc: function(page) {
var data = this.data(),
view = this.turn('view'),
loc = 0;
if (page==view[0] || page==view[1])
loc = 1;
else if (
(data.display=='single' && page==view[0]+1) ||
(data.display=='double' && page==view[0]-2 || page==view[1]+2)
)
loc = 2;
if (!this.turn('animating'))
switch (loc) {
case 1:
data.pageWrap[page].css(
{
zIndex: data.totalPages,
display: ''
});
break;
case 2:
data.pageWrap[page].css(
{
zIndex: data.totalPages-1,
display: ''
});
break;
case 0:
data.pageWrap[page].css(
{
zIndex: 0,
display: (data.pageObjs[page].hasClass('fixed')) ? '' : 'none'}
);
break;
}
return loc;
},
// Gets and sets the options
options: function(options) {
if (options===undefined) {
return this.data().opts;
} else {
var data = this.data();
// Set new values
$.extend(data.opts, options);
// Set pages
if (options.pages)
this.turn('pages', options.pages);
// Set page
if (options.page)
this.turn('page', options.page);
// Set display
if (options.display)
this.turn('display', options.display);
// Set direction
if (options.direction)
this.turn('direction', options.direction);
// Set size
if (options.width && options.height)
this.turn('size', options.width, options.height);
// Add event listeners
if (options.when)
for (var eventName in options.when)
if (has(eventName, options.when)) {
this.unbind(eventName).
bind(eventName, options.when[eventName]);
}
return this;
}
},
// Gets the current version
version: function() {
return version;
}
},
// Methods and properties for the flip page effect
flipMethods = {
// Constructor
init: function(opts) {
this.data({f: {
disabled: false,
hover: false,
effect: (this.hasClass('hard')) ? 'hard' : 'sheet'
}});
this.flip('options', opts);
flipMethods._addPageWrapper.call(this);
return this;
},
setData: function(d) {
var data = this.data();
data.f = $.extend(data.f, d);
return this;
},
options: function(opts) {
var data = this.data().f;
if (opts) {
flipMethods.setData.call(this,
{opts: $.extend({}, data.opts || flipOptions, opts)});
return this;
} else
return data.opts;
},
z: function(z) {
var data = this.data().f;
data.opts['z-index'] = z;
if (data.fwrapper)
data.fwrapper.css({
zIndex: z || parseInt(data.parent.css('z-index'), 10) || 0
});
return this;
},
_cAllowed: function() {
var data = this.data().f,
page = data.opts.page,
turnData = data.opts.turn.data(),
odd = page%2;
if (data.effect=='hard') {
return (turnData.direction=='ltr') ?
[(odd) ? 'r' : 'l'] :
[(odd) ? 'l' : 'r'];
} else {
if (turnData.display=='single') {
if (page==1)
return (turnData.direction=='ltr') ?
corners['forward'] : corners['backward'];
else if (page==turnData.totalPages)
return (turnData.direction=='ltr') ?
corners['backward'] : corners['forward'];
else
return corners['all'];
} else {
return (turnData.direction=='ltr') ?
corners[(odd) ? 'forward' : 'backward']
:
corners[(odd) ? 'backward' : 'forward'];
}
}
},
_cornerActivated: function(p) {
var data = this.data().f,
width = this.width(),
height = this.height(),
point = {x: p.x, y: p.y, corner: ''},
csz = data.opts.cornerSize;
if (point.x<=0 || point.y<=0 || point.x>=width || point.y>=height)
return false;
var allowedCorners = flipMethods._cAllowed.call(this);
switch (data.effect) {
case 'hard':
if (point.x>width-csz)
point.corner = 'r';
else if (point.x<csz)
point.corner = 'l';
else
return false;
break;
case 'sheet':
if (point.y<csz)
point.corner+= 't';
else if (point.y>=height-csz)
point.corner+= 'b';
else
return false;
if (point.x<=csz)
point.corner+= 'l';
else if (point.x>=width-csz)
point.corner+= 'r';
else
return false;
break;
}
return (!point.corner || $.inArray(point.corner, allowedCorners)==-1) ?
false : point;
},
_isIArea: function(e) {
var pos = this.data().f.parent.offset();
e = (isTouch && e.originalEvent) ? e.originalEvent.touches[0] : e;
return flipMethods._cornerActivated.call(this,
{
x: e.pageX-pos.left,
y: e.pageY-pos.top
});
},
_c: function(corner, opts) {
opts = opts || 0;
switch (corner) {
case 'tl':
return point2D(opts, opts);
case 'tr':
return point2D(this.width()-opts, opts);
case 'bl':
return point2D(opts, this.height()-opts);
case 'br':
return point2D(this.width()-opts, this.height()-opts);
case 'l':
return point2D(opts, 0);
case 'r':
return point2D(this.width()-opts, 0);
}
},
_c2: function(corner) {
switch (corner) {
case 'tl':
return point2D(this.width()*2, 0);
case 'tr':
return point2D(-this.width(), 0);
case 'bl':
return point2D(this.width()*2, this.height());
case 'br':
return point2D(-this.width(), this.height());
case 'l':
return point2D(this.width()*2, 0);
case 'r':
return point2D(-this.width(), 0);
}
},
_foldingPage: function() {
var data = this.data().f;
if (!data)
return;
var opts = data.opts;
if (opts.turn) {
data = opts.turn.data();
if (data.display == 'single')
return (opts.next>1 || opts.page>1) ? data.pageObjs[0] : null;
else
return data.pageObjs[opts.next];
}
},
_backGradient: function() {
var data = this.data().f,
turnData = data.opts.turn.data(),
gradient = turnData.opts.gradients && (turnData.display=='single' ||
(data.opts.page!=2 && data.opts.page!=turnData.totalPages-1));
if (gradient && !data.bshadow)
data.bshadow = $('<div/>', divAtt(0, 0, 1)).
css({'position': '', width: this.width(), height: this.height()}).
appendTo(data.parent);
return gradient;
},
type: function () {
return this.data().f.effect;
},
resize: function(full) {
var data = this.data().f,
turnData = data.opts.turn.data(),
width = this.width(),
height = this.height();
switch (data.effect) {
case 'hard':
if (full) {
data.wrapper.css({width: width, height: height});
data.fpage.css({width: width, height: height});
if (turnData.opts.gradients) {
data.ashadow.css({width: width, height: height});
data.bshadow.css({width: width, height: height});
}
}
break;
case 'sheet':
if (full) {
var size = Math.round(Math.sqrt(Math.pow(width, 2)+Math.pow(height, 2)));
data.wrapper.css({width: size, height: size});
data.fwrapper.css({width: size, height: size}).
children(':first-child').
css({width: width, height: height});
data.fpage.css({width: width, height: height});
if (turnData.opts.gradients)
data.ashadow.css({width: width, height: height});
if (flipMethods._backGradient.call(this))
data.bshadow.css({width: width, height: height});
}
if (data.parent.is(':visible')) {
var offset = findPos(data.parent[0]);
data.fwrapper.css({top: offset.top,
left: offset.left});
//if (data.opts.turn) {
offset = findPos(data.opts.turn[0]);
data.fparent.css({top: -offset.top, left: -offset.left});
//}
}
this.flip('z', data.opts['z-index']);
break;
}
},
// Prepares the page by adding a general wrapper and another objects
_addPageWrapper: function() {
var att,
data = this.data().f,
turnData = data.opts.turn.data(),
parent = this.parent();
data.parent = parent;
if (!data.wrapper)
switch (data.effect) {
case 'hard':
var cssProperties = {};
cssProperties[vendor + 'transform-style'] = 'preserve-3d';
cssProperties[vendor + 'backface-visibility'] = 'hidden';
data.wrapper = $('<div/>', divAtt(0, 0, 2)).
css(cssProperties).
appendTo(parent).
prepend(this);
data.fpage = $('<div/>', divAtt(0, 0, 1)).
css(cssProperties).
appendTo(parent);
if (turnData.opts.gradients) {
data.ashadow = $('<div/>', divAtt(0, 0, 0)).
hide().
appendTo(parent);
data.bshadow = $('<div/>', divAtt(0, 0, 0));
}
break;
case 'sheet':
var width = this.width(),
height = this.height(),
size = Math.round(Math.sqrt(Math.pow(width, 2)+Math.pow(height, 2)));
data.fparent = data.opts.turn.data().fparent;
if (!data.fparent) {
var fparent = $('<div/>', {css: {'pointer-events': 'none'}}).hide();
fparent.data().flips = 0;
fparent.css(divAtt(0, 0, 'auto', 'visible').css).
appendTo(data.opts.turn);
data.opts.turn.data().fparent = fparent;
data.fparent = fparent;
}
this.css({position: 'absolute', top: 0, left: 0, bottom: 'auto', right: 'auto'});
data.wrapper = $('<div/>', divAtt(0, 0, this.css('z-index'))).
appendTo(parent).
prepend(this);
data.fwrapper = $('<div/>', divAtt(parent.offset().top, parent.offset().left)).
hide().
appendTo(data.fparent);
data.fpage = $('<div/>', divAtt(0, 0, 0, 'visible')).
css({cursor: 'default'}).
appendTo(data.fwrapper);
if (turnData.opts.gradients)
data.ashadow = $('<div/>', divAtt(0, 0, 1)).
appendTo(data.fpage);
flipMethods.setData.call(this, data);
break;
}
// Set size
flipMethods.resize.call(this, true);
},
// Takes a 2P point from the screen and applies the transformation
_fold: function(point) {
var data = this.data().f,
turnData = data.opts.turn.data(),
o = flipMethods._c.call(this, point.corner),
width = this.width(),
height = this.height();
switch (data.effect) {
case 'hard':
if (point.corner=='l')
point.x = Math.min(Math.max(point.x, 0), width*2);
else
point.x = Math.max(Math.min(point.x, width), -width);
var leftPos,
shadow,
gradientX,
fpageOrigin,
parentOrigin,
totalPages = turnData.totalPages,
zIndex = data.opts['z-index'] || totalPages,
parentCss = {'overflow': 'visible'},
relX = (o.x) ? (o.x - point.x)/width : point.x/width,
angle = relX * 90,
half = angle<90;
switch (point.corner) {
case 'l':
fpageOrigin = '0% 50%';
parentOrigin = '100% 50%';
if (half) {
leftPos = 0;
shadow = data.opts.next-1>0;
gradientX = 1;
} else {
leftPos = '100%';
shadow = data.opts.page+1<totalPages;
gradientX = 0;
}
break;
case 'r':
fpageOrigin = '100% 50%';
parentOrigin = '0% 50%';
angle = -angle;
width = -width;
if (half) {
leftPos = 0;
shadow = data.opts.next+1<totalPages;
gradientX = 0;
} else {
leftPos = '-100%';
shadow = data.opts.page!=1;
gradientX = 1;
}
break;
}
parentCss[vendor+'perspective-origin'] = parentOrigin;
data.wrapper.transform('rotateY('+angle+'deg)' +
'translate3d(0px, 0px, '+(this.attr('depth')||0)+'px)', parentOrigin);
data.fpage.transform('translateX('+width+'px) rotateY('+(180+angle)+'deg)', fpageOrigin);
data.parent.css(parentCss);
if (half) {
relX = -relX+1;
data.wrapper.css({zIndex: zIndex+1});
data.fpage.css({zIndex: zIndex});
} else {
relX = relX-1;
data.wrapper.css({zIndex: zIndex});
data.fpage.css({zIndex: zIndex+1});
}
if (turnData.opts.gradients) {
if (shadow)
data.ashadow.css({
display: '',
left: leftPos,
backgroundColor: 'rgba(0,0,0,'+(0.5*relX)+')'
}).
transform('rotateY(0deg)');
else
data.ashadow.hide();
data.bshadow.css({opacity:-relX + 1});
if (half) {
if (data.bshadow.parent()[0]!=data.wrapper[0]) {
data.bshadow.appendTo(data.wrapper);
}
} else {
if (data.bshadow.parent()[0]!=data.fpage[0]) {
data.bshadow.appendTo(data.fpage);
}
}
/*data.bshadow.css({
backgroundColor: 'rgba(0,0,0,'+(0.1)+')'
})*/
gradient(data.bshadow, point2D(gradientX * 100, 0), point2D((-gradientX + 1)*100, 0),
[[0, 'rgba(0,0,0,0.3)'],[1, 'rgba(0,0,0,0)']],2);
}
break;
case 'sheet':
var that = this,
a = 0,
alpha = 0,
beta,
px,
gradientEndPointA,
gradientEndPointB,
gradientStartVal,
gradientSize,
gradientOpacity,
shadowVal,
mv = point2D(0, 0),
df = point2D(0, 0),
tr = point2D(0, 0),
folding = flipMethods._foldingPage.call(this),
tan = Math.tan(alpha),
ac = turnData.opts.acceleration,
h = data.wrapper.height(),
top = point.corner.substr(0, 1) == 't',
left = point.corner.substr(1, 1) == 'l',
compute = function() {
var rel = point2D(0, 0);
var middle = point2D(0, 0);
rel.x = (o.x) ? o.x - point.x : point.x;
if (!hasRot) {
rel.y = 0;
} else {
rel.y = (o.y) ? o.y - point.y : point.y;
}
middle.x = (left)? width - rel.x/2 : point.x + rel.x/2;
middle.y = rel.y/2;
var alpha = A90-Math.atan2(rel.y, rel.x),
gamma = alpha - Math.atan2(middle.y, middle.x),
distance = Math.max(0, Math.sin(gamma) * Math.sqrt(Math.pow(middle.x, 2) + Math.pow(middle.y, 2)));
a = deg(alpha);
tr = point2D(distance * Math.sin(alpha), distance * Math.cos(alpha));
if (alpha > A90) {
tr.x = tr.x + Math.abs(tr.y * rel.y/rel.x);
tr.y = 0;
if (Math.round(tr.x*Math.tan(PI-alpha)) < height) {
point.y = Math.sqrt(Math.pow(height, 2)+2 * middle.x * rel.x);
if (top) point.y = height - point.y;
return compute();
}
}
if (alpha>A90) {
var beta = PI-alpha, dd = h - height/Math.sin(beta);
mv = point2D(Math.round(dd*Math.cos(beta)), Math.round(dd*Math.sin(beta)));
if (left) mv.x = - mv.x;
if (top) mv.y = - mv.y;
}
px = Math.round(tr.y/Math.tan(alpha) + tr.x);
var side = width - px,
sideX = side*Math.cos(alpha*2),
sideY = side*Math.sin(alpha*2);
df = point2D(
Math.round((left ? side -sideX : px+sideX)),
Math.round((top) ? sideY : height - sideY));
// Gradients
if (turnData.opts.gradients) {
gradientSize = side*Math.sin(alpha);
var endingPoint = flipMethods._c2.call(that, point.corner),
far = Math.sqrt(Math.pow(endingPoint.x-point.x, 2)+Math.pow(endingPoint.y-point.y, 2))/width;
shadowVal = Math.sin(A90*((far>1) ? 2 - far : far));
gradientOpacity = Math.min(far, 1);
gradientStartVal = gradientSize>100 ? (gradientSize-100)/gradientSize : 0;
gradientEndPointA = point2D(
gradientSize*Math.sin(alpha)/width*100,
gradientSize*Math.cos(alpha)/height*100);
if (flipMethods._backGradient.call(that)) {
gradientEndPointB = point2D(
gradientSize*1.2*Math.sin(alpha)/width*100,
gradientSize*1.2*Math.cos(alpha)/height*100);
if (!left) gradientEndPointB.x = 100-gradientEndPointB.x;
if (!top) gradientEndPointB.y = 100-gradientEndPointB.y;
}
}
tr.x = Math.round(tr.x);
tr.y = Math.round(tr.y);
return true;
},
transform = function(tr, c, x, a) {
var f = ['0', 'auto'], mvW = (width-h)*x[0]/100, mvH = (height-h)*x[1]/100,
cssA = {left: f[c[0]], top: f[c[1]], right: f[c[2]], bottom: f[c[3]]},
cssB = {},
aliasingFk = (a!=90 && a!=-90) ? (left ? -1 : 1) : 0,
origin = x[0] + '% ' + x[1] + '%';
that.css(cssA).
transform(rotate(a) + translate(tr.x + aliasingFk, tr.y, ac), origin);
data.fpage.css(cssA).transform(
rotate(a) +
translate(tr.x + df.x - mv.x - width*x[0]/100, tr.y + df.y - mv.y - height*x[1]/100, ac) +
rotate((180/a - 2)*a),
origin);
data.wrapper.transform(translate(-tr.x + mvW-aliasingFk, -tr.y + mvH, ac) + rotate(-a), origin);
data.fwrapper.transform(translate(-tr.x + mv.x + mvW, -tr.y + mv.y + mvH, ac) + rotate(-a), origin);
if (turnData.opts.gradients) {
if (x[0])
gradientEndPointA.x = 100-gradientEndPointA.x;
if (x[1])
gradientEndPointA.y = (100-gradientEndPointA.y);
cssB['box-shadow'] = '0 0 20px rgba(0,0,0,'+(0.5*shadowVal)+')';
folding.css(cssB);
gradient(data.ashadow,
point2D(left?100:0, top?0:100),
point2D(gradientEndPointA.x, gradientEndPointA.y),
[[gradientStartVal, 'rgba(0,0,0,0)'],
[((1-gradientStartVal)*0.8)+gradientStartVal, 'rgba(0,0,0,'+(0.2*gradientOpacity)+')'],
[1, 'rgba(255,255,255,'+(0.2*gradientOpacity)+')']],
3,
alpha);
if (flipMethods._backGradient.call(that))
gradient(data.bshadow,
point2D(left?0:100, top?0:100),
point2D(gradientEndPointB.x, gradientEndPointB.y),
[[0.6, 'rgba(0,0,0,0)'],
[0.8, 'rgba(0,0,0,'+(0.3*gradientOpacity)+')'],
[1, 'rgba(0,0,0,0)']
],
3);
}
};
switch (point.corner) {
case 'l' :
break;
case 'r' :
break;
case 'tl' :
point.x = Math.max(point.x, 1);
compute();
transform(tr, [1,0,0,1], [100, 0], a);
break;
case 'tr' :
point.x = Math.min(point.x, width-1);
compute();
transform(point2D(-tr.x, tr.y), [0,0,0,1], [0, 0], -a);
break;
case 'bl' :
point.x = Math.max(point.x, 1);
compute();
transform(point2D(tr.x, -tr.y), [1,1,0,0], [100, 100], -a);
break;
case 'br' :
point.x = Math.min(point.x, width-1);
compute();
transform(point2D(-tr.x, -tr.y), [0,1,1,0], [0, 100], a);
break;
}
break;
}
data.point = point;
},
_moveFoldingPage: function(move) {
var data = this.data().f;
if (!data)
return;
var turn = data.opts.turn,
turnData = turn.data(),
place = turnData.pagePlace;
if (move) {
var nextPage = data.opts.next;
if (place[nextPage]!=data.opts.page) {
if (data.folding)
flipMethods._moveFoldingPage.call(this, false);
var folding = flipMethods._foldingPage.call(this);
folding.appendTo(data.fpage);
place[nextPage] = data.opts.page;
data.folding = nextPage;
}
turn.turn('update');
} else {
if (data.folding) {
if (turnData.pages[data.folding]) {
// If we have flip available
var flipData = turnData.pages[data.folding].data().f;
turnData.pageObjs[data.folding].
appendTo(flipData.wrapper);
} else if (turnData.pageWrap[data.folding]) {
// If we have the pageWrapper
turnData.pageObjs[data.folding].
appendTo(turnData.pageWrap[data.folding]);
}
if (data.folding in place) {
place[data.folding] = data.folding;
}
delete data.folding;
}
}
},
_showFoldedPage: function(c, animate) {
var folding = flipMethods._foldingPage.call(this),
dd = this.data(),
data = dd.f,
visible = data.visible;
if (folding) {
if (!visible || !data.point || data.point.corner!=c.corner) {
var corner = (
data.status=='hover' ||
data.status=='peel' ||
data.opts.turn.data().mouseAction) ?
c.corner : null;
visible = false;
if (trigger('start', this, [data.opts, corner])=='prevented')
return false;
}
if (animate) {
var that = this,
point = (data.point && data.point.corner==c.corner) ?
data.point : flipMethods._c.call(this, c.corner, 1);
this.animatef({
from: [point.x, point.y],
to: [c.x, c.y],
duration: 500,
frame: function(v) {
c.x = Math.round(v[0]);
c.y = Math.round(v[1]);
flipMethods._fold.call(that, c);
}
});
} else {
flipMethods._fold.call(this, c);
if (dd.effect && !dd.effect.turning)
this.animatef(false);
}
if (!visible) {
switch(data.effect) {
case 'hard':
data.visible = true;
flipMethods._moveFoldingPage.call(this, true);
data.fpage.show();
if (data.opts.shadows)
data.bshadow.show();
break;
case 'sheet':
data.visible = true;
data.fparent.show().data().flips++;
flipMethods._moveFoldingPage.call(this, true);
data.fwrapper.show();
if (data.bshadow)
data.bshadow.show();
break;
}
}
return true;
}
return false;
},
hide: function() {
var data = this.data().f,
turnData = data.opts.turn.data(),
folding = flipMethods._foldingPage.call(this);
switch (data.effect) {
case 'hard':
if (turnData.opts.gradients) {
data.bshadowLoc = 0;
data.bshadow.remove();
data.ashadow.hide();
}
data.wrapper.transform('');
data.fpage.hide();
break;
case 'sheet':
if ((--data.fparent.data().flips)===0)
data.fparent.hide();
this.css({left: 0, top: 0, right: 'auto', bottom: 'auto'}).
transform('');
data.wrapper.transform('');
data.fwrapper.hide();
if (data.bshadow)
data.bshadow.hide();
folding.transform('');
break;
}
data.visible = false;
return this;
},
hideFoldedPage: function(animate) {
var data = this.data().f;
if (!data.point) return;
var that = this,
p1 = data.point,
hide = function() {
data.point = null;
data.status = '';
that.flip('hide');
that.trigger('end', [data.opts, false]);
};
if (animate) {
var p4 = flipMethods._c.call(this, p1.corner),
top = (p1.corner.substr(0,1)=='t'),
delta = (top) ? Math.min(0, p1.y-p4.y)/2 : Math.max(0, p1.y-p4.y)/2,
p2 = point2D(p1.x, p1.y+delta),
p3 = point2D(p4.x, p4.y-delta);
this.animatef({
from: 0,
to: 1,
frame: function(v) {
var np = bezier(p1, p2, p3, p4, v);
p1.x = np.x;
p1.y = np.y;
flipMethods._fold.call(that, p1);
},
complete: hide,
duration: 800,
hiding: true
});
} else {
this.animatef(false);
hide();
}
},
turnPage: function(corner) {
var that = this,
data = this.data().f,
turnData = data.opts.turn.data();
corner = {corner: (data.corner) ?
data.corner.corner :
corner || flipMethods._cAllowed.call(this)[0]};
var p1 = data.point ||
flipMethods._c.call(this,
corner.corner,
(data.opts.turn) ? turnData.opts.elevation : 0),
p4 = flipMethods._c2.call(this, corner.corner);
this.trigger('flip').
animatef({
from: 0,
to: 1,
frame: function(v) {
var np = bezier(p1, p1, p4, p4, v);
corner.x = np.x;
corner.y = np.y;
flipMethods._showFoldedPage.call(that, corner);
},
complete: function() {
that.trigger('end', [data.opts, true]);
},
duration: turnData.opts.duration,
turning: true
});
data.corner = null;
},
moving: function() {
return 'effect' in this.data();
},
isTurning: function() {
return this.flip('moving') && this.data().effect.turning;
},
corner: function() {
return this.data().f.corner;
},
_eventStart: function(e) {
var data = this.data().f,
turn = data.opts.turn;
if (!data.corner && !data.disabled && !this.flip('isTurning') &&
data.opts.page==turn.data().pagePlace[data.opts.page])
{
data.corner = flipMethods._isIArea.call(this, e);
if (data.corner && flipMethods._foldingPage.call(this)) {
this.trigger('pressed', [data.point]);
flipMethods._showFoldedPage.call(this, data.corner);
return false;
} else
data.corner = null;
}
},
_eventMove: function(e) {
var data = this.data().f;
if (!data.disabled) {
e = (isTouch) ? e.originalEvent.touches : [e];
if (data.corner) {
var pos = data.parent.offset();
data.corner.x = e[0].pageX-pos.left;
data.corner.y = e[0].pageY-pos.top;
flipMethods._showFoldedPage.call(this, data.corner);
} else if (data.hover && !this.data().effect && this.is(':visible')) {
var point = flipMethods._isIArea.call(this, e[0]);
if (point) {
if ((data.effect=='sheet' && point.corner.length==2) || data.effect=='hard') {
data.status = 'hover';
var origin = flipMethods._c.call(this, point.corner, data.opts.cornerSize/2);
point.x = origin.x;
point.y = origin.y;
flipMethods._showFoldedPage.call(this, point, true);
}
} else {
if (data.status=='hover') {
data.status = '';
flipMethods.hideFoldedPage.call(this, true);
}
}
}
}
},
_eventEnd: function() {
var data = this.data().f,
corner = data.corner;
if (!data.disabled && corner) {
if (trigger('released', this, [data.point || corner])!='prevented') {
flipMethods.hideFoldedPage.call(this, true);
}
}
data.corner = null;
},
disable: function(disable) {
flipMethods.setData.call(this, {'disabled': disable});
return this;
},
hover: function(hover) {
flipMethods.setData.call(this, {'hover': hover});
return this;
},
peel: function (corner, animate) {
var data = this.data().f;
if (corner) {
if ($.inArray(corner, corners.all)==-1)
throw turnError('Corner '+corner+' is not permitted');
if ($.inArray(corner, flipMethods._cAllowed.call(this))!=-1) {
var point = flipMethods._c.call(this, corner, data.opts.cornerSize/2);
data.status = 'peel';
flipMethods._showFoldedPage.call(this,
{
corner: corner,
x: point.x,
y: point.y
}, animate);
}
} else {
data.status = '';
flipMethods.hideFoldedPage.call(this, animate);
}
return this;
}
};
// Processes classes
function dec(that, methods, args) {
if (!args[0] || typeof(args[0])=='object')
return methods.init.apply(that, args);
else if (methods[args[0]])
return methods[args[0]].apply(that, Array.prototype.slice.call(args, 1));
else
throw turnError(args[0] + ' is not a method or property');
}
// Attributes for a layer
function divAtt(top, left, zIndex, overf) {
return {'css': {
position: 'absolute',
top: top,
left: left,
'overflow': overf || 'hidden',
zIndex: zIndex || 'auto'
}
};
}
// Gets a 2D point from a bezier curve of four points
function bezier(p1, p2, p3, p4, t) {
var a = 1 - t,
b = a * a * a,
c = t * t * t;
return point2D(Math.round(b*p1.x + 3*t*a*a*p2.x + 3*t*t*a*p3.x + c*p4.x),
Math.round(b*p1.y + 3*t*a*a*p2.y + 3*t*t*a*p3.y + c*p4.y));
}
// Converts an angle from degrees to radians
function rad(degrees) {
return degrees/180*PI;
}
// Converts an angle from radians to degrees
function deg(radians) {
return radians/PI*180;
}
// Gets a 2D point
function point2D(x, y) {
return {x: x, y: y};
}
// Webkit 534.3 on Android wrongly repaints elements that use overflow:hidden + rotation
function rotationAvailable() {
var parts;
if ((parts = /AppleWebkit\/([0-9\.]+)/i.exec(navigator.userAgent))) {
var webkitVersion = parseFloat(parts[1]);
return (webkitVersion>534.3);
} else {
return true;
}
}
// Returns the traslate value
function translate(x, y, use3d) {
return (has3d && use3d) ? ' translate3d(' + x + 'px,' + y + 'px, 0px) '
: ' translate(' + x + 'px, ' + y + 'px) ';
}
// Returns the rotation value
function rotate(degrees) {
return ' rotate(' + degrees + 'deg) ';
}
// Checks if a property belongs to an object
function has(property, object) {
return Object.prototype.hasOwnProperty.call(object, property);
}
// Gets the CSS3 vendor prefix
function getPrefix() {
var vendorPrefixes = ['Moz','Webkit','Khtml','O','ms'],
len = vendorPrefixes.length,
vendor = '';
while (len--)
if ((vendorPrefixes[len] + 'Transform') in document.body.style)
vendor='-'+vendorPrefixes[len].toLowerCase()+'-';
return vendor;
}
// Detects the transitionEnd Event
function getTransitionEnd() {
var t,
el = document.createElement('fakeelement'),
transitions = {
'transition':'transitionend',
'OTransition':'oTransitionEnd',
'MSTransition':'transitionend',
'MozTransition':'transitionend',
'WebkitTransition':'webkitTransitionEnd'
};
for (t in transitions) {
if (el.style[t] !== undefined) {
return transitions[t];
}
}
}
// Gradients
function gradient(obj, p0, p1, colors, numColors) {
var j, cols = [];
if (vendor=='-webkit-') {
for (j = 0; j<numColors; j++)
cols.push('color-stop('+colors[j][0]+', '+colors[j][1]+')');
obj.css({'background-image':
'-webkit-gradient(linear, '+
p0.x+'% '+
p0.y+'%,'+
p1.x+'% '+
p1.y+'%, '+
cols.join(',') + ' )'});
} else {
p0 = {x:p0.x/100 * obj.width(), y:p0.y/100 * obj.height()};
p1 = {x:p1.x/100 * obj.width(), y:p1.y/100 * obj.height()};
var dx = p1.x-p0.x,
dy = p1.y-p0.y,
angle = Math.atan2(dy, dx),
angle2 = angle - Math.PI/2,
diagonal = Math.abs(obj.width()*Math.sin(angle2))+Math.abs(obj.height()*Math.cos(angle2)),
gradientDiagonal = Math.sqrt(dy*dy + dx*dx),
corner = point2D((p1.x<p0.x) ? obj.width() : 0, (p1.y<p0.y) ? obj.height() : 0),
slope = Math.tan(angle),
inverse = -1/slope,
x = (inverse*corner.x - corner.y - slope*p0.x + p0.y)/(inverse-slope),
c = {x: x, y: inverse*x - inverse*corner.x + corner.y},
segA = (Math.sqrt( Math.pow(c.x-p0.x,2) + Math.pow(c.y-p0.y,2)));
for (j = 0; j<numColors; j++)
cols.push(' '+colors[j][1]+' '+((segA + gradientDiagonal*colors[j][0])*100/diagonal)+'%');
obj.css({'background-image': vendor+'linear-gradient(' + (-angle) + 'rad,' + cols.join(',') + ')'});
}
}
// Triggers an event
function trigger(eventName, context, args) {
var event = $.Event(eventName);
context.trigger(event, args);
if (event.isDefaultPrevented())
return 'prevented';
else if (event.isPropagationStopped())
return 'stopped';
else
return '';
}
// JS Errors
function turnError(message) {
function TurnJsError(message) {
this.name = "TurnJsError";
this.message = message;
}
TurnJsError.prototype = new Error();
TurnJsError.prototype.constructor = TurnJsError;
return new TurnJsError(message);
}
// Find the offset of an element ignoring its transformation
function findPos(obj) {
var offset = {top: 0, left: 0};
do{
offset.left += obj.offsetLeft;
offset.top += obj.offsetTop;
} while ((obj = obj.offsetParent));
return offset;
}
// Checks if there's hard page compatibility
// IE9 is the only browser that does not support hard pages
function hasHardPage() {
return (navigator.userAgent.indexOf('MSIE 9.0')==-1);
}
// Request an animation
window.requestAnim = (function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
// Extend $.fn
$.extend($.fn, {
flip: function() {
return dec($(this[0]), flipMethods, arguments);
},
turn: function() {
return dec($(this[0]), turnMethods, arguments);
},
transform: function(transform, origin) {
var properties = {};
if (origin)
properties[vendor+'transform-origin'] = origin;
properties[vendor+'transform'] = transform;
return this.css(properties);
},
animatef: function(point) {
var data = this.data();
if (data.effect)
data.effect.stop();
if (point) {
if (!point.to.length) point.to = [point.to];
if (!point.from.length) point.from = [point.from];
var diff = [],
len = point.to.length,
animating = true,
that = this,
time = (new Date()).getTime(),
frame = function() {
if (!data.effect || !animating)
return;
var v = [],
timeDiff = Math.min(point.duration, (new Date()).getTime() - time);
for (var i = 0; i < len; i++)
v.push(data.effect.easing(1, timeDiff, point.from[i], diff[i], point.duration));
point.frame((len==1) ? v[0] : v);
if (timeDiff==point.duration) {
delete data['effect'];
that.data(data);
if (point.complete)
point.complete();
} else {
window.requestAnim(frame);
}
};
for (var i = 0; i < len; i++)
diff.push(point.to[i] - point.from[i]);
data.effect = $.extend({
stop: function() {
animating = false;
},
easing: function (x, t, b, c, data) {
return c * Math.sqrt(1 - (t=t/data-1)*t) + b;
}
}, point);
this.data(data);
frame();
} else {
delete data['effect'];
}
}
});
// Export some globals
$.isTouch = isTouch;
$.mouseEvents = mouseEvents;
$.cssPrefix = getPrefix;
$.cssTransitionEnd = getTransitionEnd;
$.findPos = findPos;
})(jQuery);
|
'use strict';
function Dataset($location, $http, $q, DatasetResource, DatasetModel, NpolarApiSecurity) {
'ngInject';
const schema = 'http://api.npolar.no/schema/dataset-1';
const license = 'http://creativecommons.org/licenses/by/4.0/';
DatasetResource.setRestrictedStatusForFiles = (files, restricted=true) => {
if (!files || files.length < 1) { return; }
console.log('Setting restricted =', restricted, 'for', files.map(f => f.filename||f.href));
files.forEach(f => {
$http.put(`${f.href}?restricted=${restricted}`).then(r => {
console.log(r);
});
});
};
DatasetResource.geoQuery = function(bounds) {
let deferred = $q.defer();
DatasetResource.feed(Object.assign({}, {
'filter-coverage.north': bounds.getSouth() + '..',
'filter-coverage.south': '..' + bounds.getNorth(),
'filter-coverage.west': '..' + bounds.getEast(),
'filter-coverage.east': bounds.getWest() + '..'
}, $location.search()), response => {
let points = [];
response.feed.entries.forEach(e => {
if (e.coverage) {
e.coverage.forEach(cov => {
points.push({
popup: `<a href="${DatasetResource.href(e.id)}">${e.title}</a>`,
point: [
cov.south + Math.abs(cov.north - cov.south) / 2,
cov.west + Math.abs(cov.east - cov.west) / 2
]
});
});
}
});
deferred.resolve(points);
}, error => {
deferred.reject([]);
});
return deferred.promise;
};
DatasetResource.schema = schema;
DatasetResource.license = license;
DatasetResource.create = function() {
let user = NpolarApiSecurity.getUser();
let id = user.email;
let email = user.email;
let homepage = `http://www.npolar.no/en/people/${email.split('@')[0]}`;
let [first_name,last_name] = user.name.split(' ');
let organisation = user.email.split('@')[1];
user = { id, roles: ['editor', 'pointOfContact'], first_name, last_name, email, homepage, organisation };
let collection = 'dataset';
let topics = [];
let released = new Date().toISOString();
let licences = [license];
let title = `Dataset created by ${user.email} ${released}`;
let people = [user];
let sets = [];
//let locations = [{ country: 'NO'}];
if (DatasetModel.isNyÅlesund()) {
sets.push('Ny-Ålesund');
}
return { title, released, licences, collection, schema, people, topics, draft:'no', sets };
};
// The hashi (v0) file object should be object with keys filename, url, [file_size, icon, extras].
DatasetResource.hashiObject = function(attachment) {
console.debug('hashiObject()', 'attachment:', attachment);
return {
url: attachment.href,
filename: attachment.filename,
content_type: attachment.type
};
};
DatasetResource.attachmentObject = function(hashi) {
let href = hashi.url;
//if ((/\/[0-9a-f]{32,}$/i).test(hashi.url)) {
// href = hashi.url.split('/');
// href.pop();
// href = encodeURI(`${ href.join('/') }/${ encodeURIComponent(hashi.filename) }`);
//}
let a = {
href,
filename: hashi.filename,
type: hashi.content_type,
};
console.debug('attachmentObject()', 'hashi:', hashi, '=>', a);
return a;
};
return DatasetResource;
}
module.exports = Dataset;
|
kgCO2PerMile*distance
|
var Button = require('react-bootstrap').Button;
var Glyphicon = require('react-bootstrap').Glyphicon;
var Input = require('react-bootstrap').Input;
var Modal = require('react-bootstrap').Modal;
var ModalTrigger = require('react-bootstrap').ModalTrigger;
var Nav = require('react-bootstrap').Nav;
var Navbar = require('react-bootstrap').Navbar;
var Navigation = require('react-router').Navigation;
var State = require('react-router').State;
var React = require('react');
var assign = require('object-assign');
var FluxMixin = require('fluxxor').FluxMixin(React);
var StoreWatchMixin = require('fluxxor').StoreWatchMixin;
var Markdown = require('../Markdown');
var CodeEditor = require('../CodeEditor');
var TrackDropdown = require('../TrackDropdown');
var WorldCanvas = require('../WorldCanvas');
import CodeRunner from '../CodeRunner'
require('./WorldDefinitionEditorPage.css');
var WorldDefinitionEditorPage = React.createClass({
mixins: [Navigation, State, FluxMixin, StoreWatchMixin("WorldStore")],
getDefaultProps: function() {
return {
world: null
};
},
getStateFromFlux: function() {
var store = this.getFlux().store("WorldStore");
var worldModel = store.getWorld(this.props.world.id);
return {
worldModel: worldModel,
worldSolution: worldModel.get('solution'),
saving: store.isLoading()
};
},
getInitialState: function() {
return {
currentStep: 0
};
},
handleChangeStep: function(index, event) {
var stepDefinitions = this.state.worldModel.getSteps();
stepDefinitions[index] = event.target.value;
this.state.worldModel.setSteps(stepDefinitions);
this.getFlux().actions.saveWorldLocal({}, this.state.worldModel);
},
handleSave: function() {
this.getFlux().actions.saveWorld({}, this.state.worldModel);
},
handleSaveAndRun: function(callback) {
this.getFlux().actions.saveWorld(
{solution: this.refs.codeRunner.state.programCode},
this.state.worldModel,
callback
);
},
handleAddStep: function() {
var worldStepDefinitions = this.state.worldModel.getSteps();
worldStepDefinitions.push(worldStepDefinitions[worldStepDefinitions.length-1]);
this.state.worldModel.setSteps(worldStepDefinitions);
this.getFlux().actions.saveWorldLocal({}, this.state.worldModel);
this.setState({currentStep: this.state.currentStep+1});
},
handleRemoveStep: function(index) {
if (index <= 0) {
return;
}
var worldStepDefinitions = this.state.worldModel.getSteps();
worldStepDefinitions.splice(index, 1);
this.state.worldModel.setSteps(worldStepDefinitions);
this.getFlux().actions.saveWorldLocal({}, this.state.worldModel);
this.setState({currentStep: this.state.currentStep - 1});
},
handleNextStep: function() {
if (this.state.currentStep < this.state.worldModel.getSteps().length) {
this.setState({
currentStep: this.state.currentStep + 1
});
}
},
handlePrevStep: function() {
if (this.state.currentStep > 0) {
this.setState({
currentStep: this.state.currentStep - 1
});
}
},
render: function() {
if (this.state.isLoading || !this.state.worldModel) {
return <div>loading...</div>;
}
var index = this.state.currentStep;
var definition = this.state.worldModel.getSteps()[this.state.currentStep];
return (
<div className="WorldDefinitionEditorPage">
<div className="row">
<div className="col-md-4">
<form>
<h6>
<Button className="pull-left" disabled={this.state.currentStep <= 0} onClick={this.handlePrevStep}>
<Glyphicon glyph="chevron-left" />
</Button>
Checkpoint {index}
<Button
className="pull-right"
disabled={this.state.currentStep >= this.state.worldModel.getSteps().length - 1}
onClick={this.handleNextStep}>
<Glyphicon glyph="chevron-right" />
</Button>
</h6>
<CodeEditor onChange={this.handleChangeStep.bind(this, index)} className="form-control" value={definition}/>
<div className="buttons text-right">
<Button onClick={this.handleRemoveStep.bind(this, index)}>Remove</Button>
{' '}
<Button onClick={this.handleAddStep}>Add</Button>
{' '}
<Button
onClick={this.handleSave}
disabled={!this.state.worldModel.needsSave}
bsStyle={this.state.worldModel.needsSave ? "primary" : "default"}>
{this.state.saving ? "Saving..." : "Save"}
</Button>
</div>
</form>
</div>
<div className="worldPane col-md-8">
<h3>Edit Demo Solution</h3>
<CodeRunner
ref="codeRunner"
world={this.state.worldModel}
initialCode={this.state.worldSolution}
showStep={this.state.currentStep}
onSaveAndRun={this.handleSaveAndRun}
isSaving={this.state.saving}/>
</div>
</div>
</div>
);
}
});
module.exports = WorldDefinitionEditorPage;
|
import { Factory } from 'miragejs';
export default Factory.extend({
title: (i) => `clerkship type ${i}`,
});
|
require('babel-register');
require("babel-polyfill");
require('./index');
|
var controller = module.exports;
var User = require('./users.model.js');
controller.getOne = function(req, res) {
User.where({id:req.params.id}).fetch()
.then(function (user) {
if(user){
res.json(user);
} else {
res.status(404).end();
}
});
};
controller.getAll = function(req, res) {
User.fetchAll({
}).then(function (collection) {
res.json(collection);
});
};
|
importScripts('/static/vendor/idb/lib/idb.js');
importScripts('/static/vendor/idb-keyval/idb-keyval.js');
importScripts('/static/javascripts/indexeddb.js');
const cacheName = 'cache-v1';
const urlsToCache = [
'/',
'/offline',
'/static/stylesheets/fonts.css',
'/static/stylesheets/components.css',
'/static/stylesheets/chatapp.css',
'/static/vendor/jquery/dist/jquery.min.js',
'/static/vendor/idb/lib/idb.js',
'/static/vendor/idb-keyval/idb-keyval.js',
'/static/javascripts/utils.js',
'/static/javascripts/indexeddb.js',
'/static/javascripts/chatapp.js',
'/static/javascripts/authentication.js',
'/static/javascripts/sw-register.js',
'/static/fonts/quicksand/regular.woff2',
'/static/fonts/quicksand/bold.woff2',
'/static/images/logout.png'
];
self.addEventListener('install', e => {
e.waitUntil(
caches.open(cacheName).then(cache => {
return cache.addAll(urlsToCache)
}).then(_ => {
console.log(`Caching complete for "${cacheName}"`);
})
);
});
self.addEventListener('activate', e => {
e.waitUntil(
caches.keys().then(cacheKeys => {
return Promise.all(cacheKeys.map(cacheKey => {
if (cacheKey !== cacheName) {
return caches.delete(cacheKey);
}
}));
})
);
});
self.addEventListener('fetch', e => {
e.respondWith(
caches.match(e.request).then(response => {
if (response) {
return response;
}
return fetch(e.request).catch(error => {
if (e.request.mode === 'navigate') {
return caches.match('/offline');
}
});
})
);
});
self.addEventListener('push', e => {
if (e.data) {
const data = e.data.json();
var notificationTitle = data.user.name;
var notificationOptions = {
body: data.message.content,
icon: data.user.avatar,
data: {
redirectUrl: '/messages'
}
};
} else {
var notificationTitle = 'You received a new message';
var notificationOptions = {
body: 'Tap to view in messages',
icon: '/static/images/chatapp.png'
};
}
e.waitUntil(
self.registration.showNotification(notificationTitle, notificationOptions)
);
});
self.addEventListener('notificationclick', e => {
e.notification.close();
e.waitUntil(
self.clients.matchAll({ type: 'window' }).then(clients => {
if (clients.length > 0) {
clients[0].navigate(e.notification.data.redirectUrl);
clients[0].focus();
} else {
self.clients.openWindow(e.notification.data.redirectUrl);
}
})
);
});
self.addEventListener('sync', e => {
if (e.tag === 'send-message') {
e.waitUntil(
retrieveObjectsFromIndexedDb('messages').then(messages => {
return idbKeyval.get('jwtoken').then(jwtoken => {
return Promise.all(messages.map(message => {
return fetch('/message', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${jwtoken}`
},
body: JSON.stringify({ message: message.message })
})
.then(response => response.json())
.then(response => deleteObjectFromIndexedDb('messages', message.id));
}));
});
})
);
}
});
|
import Vue from 'vue'
import App from './App'
import About from './About'
import Home from './components/Home'
import Router from 'vue-router'
/* eslint-disable no-new */
Vue.use(Router)
var app = Vue.extend({
components: { App }
})
var router = new Router({
linkActiveClass: 'is-active'
})
router.map({
'/': {
component: Home
},
'/about': {
component: About
}
})
router.start(app, 'body')
|
'use strict';
/**
* Module dependencies.
*/
var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
var expect = require('chai').expect;
var bmq = require('../');
describe('[Send]', function() {
var client;
var worker;
afterEach(function() {
client.removeAllListeners();
client.destroy();
worker.removeAllListeners();
worker.destroy();
});
describe('data frame', function() {
beforeEach(function() {
client = new bmq.Client();
client.use(bmq.MODULE.CONNECTION, {
approach: bmq.CONNECTION.REQ // connect dealer
});
client.initialize();
worker = new bmq.Worker();
worker.use(bmq.MODULE.CONNECTION, {
approach: bmq.CONNECTION.REP, // router
socket: bmq.SOCKET.BIND // bind
});
worker.initialize();
});
it('should recive string data', function(done) {
client.send('string data');
worker.on('message', function(messageId, data) {
expect(data).to.be.a('string');
expect(data).to.eq('string data');
expect(data.length).to.eq(11);
done();
});
});
it('should recive number data', function(done) {
client.send(123);
worker.on('message', function(messageId, data) {
expect(data).to.be.a('number');
expect(data).to.eq(123);
done();
});
});
it('should recive json data..', function(done) {
client.send({
foo: 'fooo',
bar: 123
});
worker.on('message', function(messageId, data) {
expect(data).to.be.a('object');
expect(data).to.have.property('foo').and.eq('fooo');
expect(data).to.have.property('bar').and.eq(123);
done();
});
});
});
});
|
System.config({
baseURL: "/",
defaultJSExtensions: true,
transpiler: "babel",
babelOptions: {
"optional": [
"runtime",
"optimisation.modules.system"
]
},
paths: {
"github:*": "jspm_packages/github/*",
"npm:*": "jspm_packages/npm/*"
},
map: {
"babel": "npm:babel-core@5.8.29",
"babel-runtime": "npm:babel-runtime@5.8.29",
"core-js": "npm:core-js@1.2.3",
"underscore": "npm:underscore@1.8.3",
"github:jspm/nodelibs-assert@0.1.0": {
"assert": "npm:assert@1.3.0"
},
"github:jspm/nodelibs-path@0.1.0": {
"path-browserify": "npm:path-browserify@0.0.0"
},
"github:jspm/nodelibs-process@0.1.2": {
"process": "npm:process@0.11.2"
},
"github:jspm/nodelibs-util@0.1.0": {
"util": "npm:util@0.10.3"
},
"npm:assert@1.3.0": {
"util": "npm:util@0.10.3"
},
"npm:babel-runtime@5.8.29": {
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:core-js@1.2.3": {
"fs": "github:jspm/nodelibs-fs@0.1.2",
"path": "github:jspm/nodelibs-path@0.1.0",
"process": "github:jspm/nodelibs-process@0.1.2",
"systemjs-json": "github:systemjs/plugin-json@0.1.0"
},
"npm:inherits@2.0.1": {
"util": "github:jspm/nodelibs-util@0.1.0"
},
"npm:path-browserify@0.0.0": {
"process": "github:jspm/nodelibs-process@0.1.2"
},
"npm:process@0.11.2": {
"assert": "github:jspm/nodelibs-assert@0.1.0"
},
"npm:util@0.10.3": {
"inherits": "npm:inherits@2.0.1",
"process": "github:jspm/nodelibs-process@0.1.2"
}
}
});
|
const Graphic = require('mongoose').model('Graphic')
const Comment = require('mongoose').model('Comment')
const multer = require('multer')
let fs = require('fs')
module.exports = {
graphicGet: (req, res) => {
"use strict";
res.render('graphics/create')
},
createGraphic: (req, res, err) => {
"use strict";
let errorMsg = ''
if (res.locals.errorMsg) {
errorMsg = res.locals.errorMsg
res.render('graphics/create', {globalError: errorMsg})
} else {
let image = req.files[0]
if (image.mimetype === 'image/jpeg' || image.mimetype === 'image/png') {
fs.rename('public/uploads/' + image.filename, 'public/uploads/' + image.filename + '.png', function (err) {
if (err) throw err
})
}
let graphicInput = req.body
if (!req.isAuthenticated()) {
errorMsg = 'Not Logged'
} else if (!graphicInput.name) {
errorMsg = 'Invalid Name'
}
if (!image) {
errorMsg = "Missing Image"
}
if (errorMsg) {
res.render('graphics/create', {globalError: errorMsg})
}
graphicInput.author = req.user.id
graphicInput.category = req.body.category.toString()
graphicInput.image = '/uploads/' + image.filename
graphicInput.views = 0
let today = new Date()
let dd = today.getDate()
let mm = today.getMonth()+1; //January is 0!
let yyyy = today.getFullYear();
let hh = today.getHours()
let m = today.getMinutes()
let ss = today.getSeconds()
if(dd<10) {
dd='0'+dd
}
if(mm<10) {
mm='0'+mm
}
today = mm+'-'+dd+'-'+yyyy+' / '+hh+':'+m+':'+ss;
graphicInput.date = today
Graphic.create(graphicInput)
.then(graphic => {
req.user.graphics.push(graphic.id)
req.user.save(err => {
if (err) {
res.redirect('/', {error: err.message})
} else {
res.redirect('/')
}
})
})
}
},
index: (req, res) => {
"use strict";
Graphic.count({}, function (err, grapCount) {
if (err) {
} else {
if (req.session.skip !== undefined) {
let limit = 6
let skip = 0
let pages = Math.ceil( grapCount / 6)
skip = parseInt(req.query.page) * limit
let currentPage = parseInt(req.query.page) || 0
Graphic.find({}).skip(skip).limit(limit).populate('author').then(graphics => {
graphics.page = 0
res.render('graphics/index', {graphics: graphics, pages, currentPage})
})
} else {
let limit = 6
let skip = 0
let pages = Math.ceil(grapCount / 6)
req.session.skip = 0
let currentPage = 0
Graphic.find({}).skip(skip).limit(limit).populate('author').then(graphics => {
graphics.page = 0
res.render('graphics/index', {graphics: graphics, pages, currentPage})
})
}
}
})
},
graphicDetails: (req, res) => {
"use strict";
let id = req.params.id;
Graphic.findById(id).populate('author').then(graphic => {
graphic.views++
graphic.save()
Comment.find({target: id}).populate('author').then(comments => {
graphic.comments = comments
res.render('graphics/details', graphic)
})
})
},
graphicDetailsReal: (req, res) => {
"use strict";
let id = req.params.id;
Graphic.findById(id).populate('author').then(graphic => {
let path = 'public/' + graphic.image + '.png'
graphic.views++
graphic.save()
Comment.find({target: id}).populate('author').then(comments => {
graphic.comments = comments
res.render('graphics/detailsReal', graphic)
//res.download(path)
})
})
},
downloadPost: (req, res) => {
"use strict";
let id = req.params.id;
Graphic.findById(id).then(graphic => {
let path = 'public/' + graphic.image + '.png'
res.download(path)
})
},
editGet: (req, res) => {
"use strict";
let id = req.params.id
let isUser = req.user.username
Graphic.findById(id).populate('author').then(graphic => {
console.log(graphic.author.username);
if (isUser === graphic.author.username || isUser === 'Admin') {
res.render('graphics/edit', graphic)
} else {
res.redirect('/users/login')
}
})
},
editPost: (req, res) => {
"use strict";
let id = req.params.id
let graphicArgs = req.body
let errorMsg = ''
if (!graphicArgs.name) {
errorMsg = 'Graphic name cannot be empty'
}
if (errorMsg) {
res.render('Graphics/details', {globalError: errorMsg})
} else {
Graphic.update({_id: id}, {
$set: {
name: graphicArgs.name,
category: graphicArgs.category,
description: graphicArgs.description
}
})
.then(updateStatus => {
res.redirect(`/graphics/details/${id}`)
})
}
},
deleteGet: (req, res) => {
"use strict";
let id = req.params.id
let isUser = req.user.username
Graphic.findById(id).populate('author').then(graphic => {
if (isUser === graphic.author.username || isUser === 'Admin') {
res.render('graphics/delete', graphic)
} else {
res.redirect('/users/login')
}
})
},
deletePost: (req, res) => {
"use strict";
let id = req.params.id
Graphic.findOneAndRemove({_id: id}).populate('author').then(graphic => {
let lifePath = 'public' + graphic.image + '.png'
fs.unlinkSync(lifePath)
graphic.prepareDelete()
res.redirect('/')
})
},
photographyGet: (req, res) => {
"use strict";
Graphic.count({category: "Photography"}, function (err, grapCount) {
if (err) {
} else {
if (req.session.skip !== undefined) {
let limit = 6
let skip = 0
let pages = Math.ceil( grapCount / 6)
skip = parseInt(req.query.page) * limit
let currentPage = parseInt(req.query.page) || 0
Graphic.find({category: "Photography"}).skip(skip).limit(limit).populate('author').then(graphics => {
graphics.page = 0
res.render('graphics/photography', {graphics: graphics, pages, currentPage})
})
} else {
let limit = 6
let skip = 0
let pages = Math.ceil(grapCount / 6)
req.session.skip = 0
let currentPage = 0
Graphic.find({category: "Photography"}).skip(skip).limit(limit).populate('author').then(graphics => {
graphics.page = 0
res.render('graphics/photography', {graphics: graphics, pages, currentPage})
})
}
}
})
},
drawingGet: (req, res) => {
"use strict";
Graphic.count({category: "Drawing"}, function (err, grapCount) {
if (err) {
} else {
if (req.session.skip !== undefined) {
let limit = 6
let skip = 0
let pages = Math.ceil( grapCount / 6)
skip = parseInt(req.query.page) * limit
let currentPage = parseInt(req.query.page) || 0
Graphic.find({category: "Drawing"}).skip(skip).limit(limit).populate('author').then(graphics => {
graphics.page = 0
res.render('graphics/Drawing', {graphics: graphics, pages, currentPage})
})
} else {
let limit = 6
let skip = 0
let pages = Math.ceil(grapCount / 6)
req.session.skip = 0
let currentPage = 0
Graphic.find({category: "Drawing"}).skip(skip).limit(limit).populate('author').then(graphics => {
graphics.page = 0
res.render('graphics/Drawing', {graphics: graphics, pages, currentPage})
})
}
}
})
},
threeDmodelsGet: (req, res) => {
"use strict";
Graphic.count({category: "3D Models"}, function (err, grapCount) {
if (err) {
} else {
if (req.session.skip !== undefined) {
let limit = 6
let skip = 0
let pages = Math.ceil( grapCount / 6)
skip = parseInt(req.query.page) * limit
let currentPage = parseInt(req.query.page) || 0
Graphic.find({category: "3D Models"}).skip(skip).limit(limit).populate('author').then(graphics => {
graphics.page = 0
res.render('graphics/threeDmodels', {graphics: graphics, pages, currentPage})
})
} else {
let limit = 6
let skip = 0
let pages = Math.ceil(grapCount / 6)
req.session.skip = 0
let currentPage = 0
Graphic.find({category: "3D Models"}).skip(skip).limit(limit).populate('author').then(graphics => {
graphics.page = 0
res.render('graphics/threeDmodels', {graphics: graphics, pages, currentPage})
})
}
}
})
},
otherGet: (req, res) => {
"use strict";
Graphic.count({category: "Other"}, function (err, grapCount) {
if (err) {
} else {
if (req.session.skip !== undefined) {
let limit = 6
let skip = 0
let pages = Math.ceil( grapCount / 6)
skip = parseInt(req.query.page) * limit
let currentPage = parseInt(req.query.page) || 0
Graphic.find({category: "Other"}).skip(skip).limit(limit).populate('author').then(graphics => {
graphics.page = 0
res.render('graphics/other', {graphics: graphics, pages, currentPage})
})
} else {
let limit = 6
let skip = 0
let pages = Math.ceil(grapCount / 6)
req.session.skip = 0
let currentPage = 0
Graphic.find({category: "Other"}).skip(skip).limit(limit).populate('author').then(graphics => {
graphics.page = 0
res.render('graphics/other', {graphics: graphics, pages, currentPage})
})
}
}
})
},
}
|
// Fichier config pour RequireJs
require.config({
paths: {
jquery: 'vendor/jquery/dist/jquery',
bootstrap: 'vendor/bootstrap-sass/assets/javascripts/bootstrap',
underscore: 'vendor/underscore/underscore',
backbone: 'vendor/backbone/backbone',
geoloc: 'tools/geoloc',
text: 'vendor/requirejs-text/text',
async: 'vendor/requirejs-plugins/src/async',
googleMap: 'vendor/googlemaps-amd/src/googlemaps'
},
shim: {
'jquery': {
export: '$'
},
'geoloc': {
export: 'geoloc'
},
'underscore': {
export: '_'
},
'bootstrap': {
deps: ['jquery']
},
'backbone': {
deps: ['underscore','jquery'],
export: 'Backbone'
}
}
});
require(['app'], function(App) {
App.initialize();
});
|
function Chunks(chunks) {
this.chunks = [];
this.length = 0;
if (chunks) {
this.setChunks(chunks);
}
}
Chunks.prototype.setChunks = function(chunks) {
if (!Array.isArray(chunks)) {
throw new Error("'chunks' must be an array in Chunks.setChunks");
}
this.chunks = chunks;
this.length = chunks.length;
}
Chunks.prototype.add = function(chars) {
this.chunks.push(chars);
this.length++;
}
Chunks.prototype.get = function(index) {
return this.chunks[index];
}
Chunks.prototype.range = function(start, stop) {
return new Chunks(this.chunks.slice(start, stop));
}
Chunks.prototype.indexOf = function(needle, begin) {
var index = -1;
for (var i = Math.max(begin, 0); i < this.chunks.length; i++) {
if (this.chunks[i].equals(needle)) {
return i;
}
}
return index;
}
module.exports = Chunks;
|
/*
Emglken port of TADS
====================
Copyright (c) 2020 Dannii Willis
MIT licenced
https://github.com/curiousdannii/emglken
*/
const EmglkenVM = require('./vm.js')
const TADSCore = require('../build/tads-core.js')
module.exports = class TADS extends EmglkenVM
{
default_options()
{
return {
vmcore: TADSCore,
}
}
}
|
"use strict";
$(function() {
console.log('Loading...');
var world = new World({containerId: 'canvas-container'});
world.render();
console.log('Loaded.');
});
|
/*
Copyright (c) 2004-2009, The Dojo Foundation All Rights Reserved.
Available via Academic Free License >= 2.1 OR the modified BSD license.
see: http://dojotoolkit.org/license for details
*/
if(!dojo._hasResource["dojo._base"]) {
dojo._hasResource["dojo._base"] = true;
dojo.provide("dojo._base");
dojo.require("dojo._base.lang");
dojo.require("dojo._base.declare");
dojo.require("dojo._base.connect");
dojo.require("dojo._base.Deferred");
dojo.require("dojo._base.json");
dojo.require("dojo._base.array");
dojo.require("dojo._base.Color");
dojo.requireIf(dojo.isBrowser,"dojo._base.browser");
}
|
import Phaser from 'phaser'
export default class extends Phaser.Stage {
}
|
// application/javascript;version=1.8
function testBasic1() {
var foo = 1+1;
assertEquals(2, foo);
}
gjstestRun();
|
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const glob = require('glob');
module.exports = {
mode: 'production',
entry: glob.sync('./dist/css/**/*.css'),
output: {
path: __dirname + '/dist',
filename: 'pivotal-ui.js'
},
module: {
rules: [
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, 'css-loader']
},
{
test: /\.(eot|ttf|woff)$/,
loader: 'url-loader'
},
{
test: /\.(jpe?g|png|gif|svg)$/i,
loaders: [
'file-loader?hash=sha512&digest=hex&name=[hash].[ext]',
'image-webpack-loader?bypassOnDebug&optimizationLevel=7&interlaced=false'
]
}
]
},
plugins: [
new MiniCssExtractPlugin({filename: 'components.css'})
],
node: {
fs: 'empty',
module: 'empty'
}
};
|
'use strict';
var path = require('path').posix;
var helpers = require('../helpers');
var runMochaJSON = helpers.runMochaJSON;
describe('--bail', function () {
var args = [];
before(function () {
args = ['--bail'];
});
it('should stop after the first error', function (done) {
var fixture = path.join('options', 'bail');
runMochaJSON(fixture, args, function (err, res) {
if (err) {
return done(err);
}
expect(res, 'to have failed')
.and('to have passed test', 'should display this spec')
.and('to have failed test', 'should only display this error')
.and('to have passed test count', 1)
.and('to have failed test count', 1);
done();
});
});
it('should stop after the first error - async', function (done) {
var fixture = path.join('options', 'bail-async');
runMochaJSON(fixture, args, function (err, res) {
if (err) {
return done(err);
}
expect(res, 'to have failed')
.and('to have passed test', 'should display this spec')
.and('to have failed test', 'should only display this error')
.and('to have passed test count', 1)
.and('to have failed test count', 1);
done();
});
});
it('should stop all tests after failing "before" hook', function (done) {
var fixture = path.join('options', 'bail-with-before');
runMochaJSON(fixture, args, function (err, res) {
if (err) {
return done(err);
}
expect(res, 'to have failed')
.and('to have failed test count', 1)
.and(
'to have failed test',
'"before all" hook: before suite1 for "test suite1"'
)
.and('to have passed test count', 0);
done();
});
});
it('should stop all tests after failing "beforeEach" hook', function (done) {
var fixture = path.join('options', 'bail-with-beforeEach');
runMochaJSON(fixture, args, function (err, res) {
if (err) {
return done(err);
}
expect(res, 'to have failed')
.and('to have failed test count', 1)
.and(
'to have failed test',
'"before each" hook: beforeEach suite1 for "test suite1"'
)
.and('to have passed test count', 0);
done();
});
});
it('should stop all tests after failing test', function (done) {
var fixture = path.join('options', 'bail-with-test');
runMochaJSON(fixture, args, function (err, res) {
if (err) {
return done(err);
}
expect(res, 'to have failed')
.and('to have failed test count', 1)
.and('to have failed test', 'test suite1')
.and('to have passed test count', 0);
done();
});
});
it('should stop all tests after failing "after" hook', function (done) {
var fixture = path.join('options', 'bail-with-after');
runMochaJSON(fixture, args, function (err, res) {
if (err) {
return done(err);
}
expect(res, 'to have failed')
.and('to have failed test count', 1)
.and(
'to have failed test',
'"after all" hook: after suite1A for "test suite1A"'
)
.and('to have passed test count', 2)
.and('to have passed test order', 'test suite1', 'test suite1A');
done();
});
});
it('should stop all tests after failing "afterEach" hook', function (done) {
var fixture = path.join('options', 'bail-with-afterEach');
runMochaJSON(fixture, args, function (err, res) {
if (err) {
return done(err);
}
expect(res, 'to have failed')
.and('to have failed test count', 1)
.and(
'to have failed test',
'"after each" hook: afterEach suite1A for "test suite1A"'
)
.and('to have passed test count', 2)
.and('to have passed test order', 'test suite1', 'test suite1A');
done();
});
});
});
|
"use strict";
define([
'./feature1/services/feature1Service'
],
function(feature1Service) {
return {
'meanSeed.feature1.services.feature1Service': feature1Service
};
});
|
jQuery(document).ready(function() {
Metronic.init(); // init metronic core components
Layout.init(); // init current layout
QuickSidebar.init(); // init quick sidebar
Demo.init(); // init demo features
TableManaged.init();
$("#category").addClass('active');
$("#category-table").on('click', ".btn-review-edit", function(){
$this_tr = $(this).closest('tr');
$("#other-input").html('<input type="hidden" id="category-id" name="category-id" value="'+$this_tr.data('number')+'" />');
$.post(base_url()+"admin/getcat",{cat_id:$this_tr.data('number')},function(data){
//data = jQuery.parseJSON(data);
$("#filtergroup-containner").html(data);
$("#filtergroup-containner").find("input[name=filters-value]").tagsinput({});
});
$("#category-name").val($this_tr.find('td:nth-child(2)').html().trim());
$('#category-modal').modal("show");
});
$("#category-table").on('click', ".btn-review-delete", function(){
$this_tr = $(this).closest('tr');
$.post(base_url()+"admin/delcat", {"category-id":$this_tr.data('number')}, function(data){
data = jQuery.parseJSON(data);
if(data.error == "no"){
$this_tr.fadeOut("normal", function() { $(this).remove(); });
Metronic.alert({type: 'success', message: data.msg, closeInSeconds: 5, icon: 'cjeck'});
}
});
});
$(".create-new").on('click', function(){
$("#other-input").html("");
$("#category-name").val("");
$('#category-form .alert').hide();
$('#category-modal').modal('show');
});
$("#category-save").on('click', function(){
if($("#category-name").val().trim() != ""){
var inps = document.getElementsByName('filters-value');
var filters_value = [];
for (var i = 0; i <inps.length - 1; i++) {
var inp=inps[i];
filters_value.push(inp.value);
// "filters-value["+i+"].value="+inp.value;
}
//console.log(filters_value);
$.post( base_url()+"admin/addcat", {form_data:$("#category-form").serialize(),filters_value:filters_value}, function(data){
data = jQuery.parseJSON(data);
if(data.error == "no"){
$('#category-modal').modal("hide");
Metronic.alert({type: 'success', message: data.msg, closeInSeconds: 5, icon: 'check'});
var catid = $("#category-form").find("#category-id");
if(catid.length > 0 && catid.val() != "" && catid.val() > 0){
var $update_row = $("#category-table tbody tr[data-number="+catid.val()+"]");
$update_row.find('td:nth-child(2)').html($("#category-name").val().trim());
}else{
$("#category-table tbody").append('<tr data-number="'+data.new+'"><td>'+(parseInt($("#category-table tr:last").find("td:first").html())+1)+'</td><td>'+$("#category-name").val()+'</td><td> <button type="button" class="btn btn-xs blue btn-review-edit">Edit</button><button type="button" class="btn btn-xs red btn-review-delete">delete</button></tr>');
}
}else if(data.error == "exist"){
$('#category-form .alert:first').show().html(data['msg']['category-name']);
}
else{
Metronic.alert({type: 'danger', message: data.msg, closeInSeconds: 5, icon: 'warning'});
$('#category-modal').modal("hide");
}
});
}else{
$('#category-form .alert:first').show().html('Please Enter Category Name.');
}
});
//for category filters
var filterGroupMaster = $("#filtergroupmaster").html();
var filterGroupContainer = $("#filtergroup-containner");
$("#add_filter_btn").on("click", function(){
filterGroupContainer.append(filterGroupMaster);
filterGroupContainer.find("input[name=filters-value]:last").tagsinput({});
});
filterGroupContainer.on('click', ".filtergroup-delete-btn" , function(){
var filter_id = $(this).closest(".filtergroups").find('.filters-name').attr('id');
var $btn = $(this);
if(typeof(filter_id) !== "undefined" && filter_id !== null){
$.post(base_url()+'admin/deleteFilter',{filter_id:filter_id},function(data){
data = jQuery.parseJSON(data);
if(data.error === "no"){
$($btn).closest(".filtergroups").fadeOut(300, function(){
$($btn).remove();
});
}
});
}else{
$(this).closest(".filtergroups").fadeOut(300, function(){ $(this).remove();});
}
});
});
var TableManaged = function () {
var initTable1 = function () {
var table = $('#category-table');
// begin first table
table.dataTable({
// Internationalisation. For more info refer to http://datatables.net/manual/i18n
"language": {
"aria": {
"sortAscending": ": activate to sort column ascending",
"sortDescending": ": activate to sort column descending"
},
"emptyTable": "No data available in table",
"info": "Showing _START_ to _END_ of _TOTAL_ records",
"infoEmpty": "No records found",
"infoFiltered": "(filtered1 from _MAX_ total records)",
"lengthMenu": "Show _MENU_ records",
"search": "Search:",
"zeroRecords": "No matching records found",
"paginate": {
"previous":"Prev",
"next": "Next",
"last": "Last",
"first": "First"
}
},
"lengthMenu": [
[10, 15, 20, 100, -1],
[10, 15, 20, 100, "All"] // change per page values here
],
// set the initial value
"pageLength": 10,
"pagingType": "bootstrap_full_number",
"columnDefs": [{ // set default column settings
'orderable': true,
'targets': [0]
}, {
"searchable": true,
"targets": [0]
}],
"order": [
[0, "asc"]
], // set first column as a default sort by asc
// "aoColumnDefs": [{ "bVisible": false, "aTargets": [2] }]
"fnDrawCallback": function ( oSettings ) {
/* Need to redo the counters if filtered or sorted */
if ( oSettings.bSorted || oSettings.bFiltered )
{
for ( var i=0, iLen=oSettings.aiDisplay.length ; i<iLen ; i++ )
{
$('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[i] ].nTr ).html( i+1 );
}
}
}
});
}
return {
init: function ()
{
if (!jQuery().dataTable)
{
return;
}
initTable1();
}
};
}();
|
'use strict';
//Setting up route
angular.module('vendorcontactnotes').config(['$stateProvider',
function ($stateProvider) {
// Vendorcontactnotes state routing
$stateProvider.
state('listVendorcontactnotes', {
url: '/notes/vendors',
templateUrl: 'modules/vendorcontactnotes/views/list-vendorcontactnotes.client.view.html'
}).
state('createVendorcontactnote', {
url: '/notes/vendors/:vendorId/create',
templateUrl: 'modules/vendorcontactnotes/views/create-vendorcontactnote.client.view.html'
}).
state('vendorNotesView', {
url: '/notes/vendors/:vendorId/view',
templateUrl: 'modules/vendorcontactnotes/views/view-vendorcontactnote.client.view.html'
})
}
]);
|
'use strict';
var fs = require('fs');
var path = require('path');
var _ = require('lodash');
var vinylFs = require('vinyl-fs');
var es = require('event-stream');
var gutil = require('gulp-util');
var concatCore = require('./athena_concat_core');
function getWidgetPath (modulePath, widget, config) {
return path.join(modulePath, config.dest, '_', 'widget', widget);
}
function resourcesConcat (opts) {
var config = _.assign({
cwd: undefined,
module: undefined,
dest: 'dist',
end: function () {}
}, opts);
if (!config.cwd || !config.module) {
gutil.log(gutil.colors.red('传入参数有误 at concat!'));
return;
}
var modulePath = path.join(config.cwd, config.module);
concactStatic(modulePath, config, function () {
if (_.isFunction(opts.end)) {
opts.end();
}
});
}
// 通过读取static-conf配置来进行资源合并
function concactStatic (modulePath, config, cb) {
var streamArr = [];
var staticPath = require(path.join(modulePath, 'static-conf')).staticPath;
if (_.isEmpty(staticPath)) {
cb();
return;
}
for (var key in staticPath) {
// css
if (path.extname(key).indexOf('css') >= 0) {
streamArr.push(vinylFs
.src(staticPath[key].map(function (item) {
return path.join(modulePath, config.dest, '_', item);
}))
.pipe(concatCore(key))
.pipe(vinylFs.dest(path.join(modulePath, config.dest, '_static', 'static', 'css'))));
}
// js
if (path.extname(key).indexOf('js') >= 0) {
streamArr.push(vinylFs
.src(staticPath[key].map(function (item) {
return path.join(modulePath, config.dest, '_', item);
}))
.pipe(concatCore(key))
.pipe(vinylFs.dest(path.join(modulePath, config.dest, '_static', 'static', 'js'))));
}
}
es.merge(streamArr).on('end', function () {
cb();
});
}
module.exports = resourcesConcat;
|
const h = require('react').createElement
const { mount, configure } = require('enzyme')
const ReactAdapter = require('enzyme-adapter-react-16')
const Uppy = require('@uppy/core')
beforeAll(() => {
configure({ adapter: new ReactAdapter() })
})
jest.mock('@uppy/progress-bar', () => require('./__mocks__/ProgressBarPlugin'))
const ProgressBar = require('./ProgressBar')
describe('react <ProgressBar />', () => {
it('can be mounted and unmounted', () => {
const oninstall = jest.fn()
const onuninstall = jest.fn()
const uppy = new Uppy()
const dash = mount((
<ProgressBar
uppy={uppy}
onInstall={oninstall}
onUninstall={onuninstall}
/>
))
expect(oninstall).toHaveBeenCalled()
expect(onuninstall).not.toHaveBeenCalled()
dash.unmount()
expect(oninstall).toHaveBeenCalled()
expect(onuninstall).toHaveBeenCalled()
})
it('react on HTMLDivElement props update', async () => {
const uppy = new Uppy()
const dash = mount((
<ProgressBar
uppy={uppy}
onInstall={Function.prototype}
onUninstall={Function.prototype}
hidden
/>
))
expect(dash.getDOMNode().hidden).toBeTruthy()
dash.setProps({ hidden: false })
expect(dash.getDOMNode().hidden).toBeFalsy()
dash.unmount()
})
})
|
/*global module:true */
module.exports = function (grunt) {
'use strict';
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-compass');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-jst');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-csslint');
grunt.loadNpmTasks('grunt-contrib-qunit');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-docco');
grunt.loadNpmTasks('grunt-jscs-checker');
grunt.loadNpmTasks('grunt-notify');
grunt.registerTask('template', 'A simple task to convert HTML templates', function () {
var template = grunt.file.read('src/qunit-image.hbs'),
process = function (template) {
var str = 'var template = function (data) {';
str += "var p = [];";
str += "p.push('" +
template.replace(/[\r\t\n]/g, ' ') // remove linebreaks etc.
.replace(/\{\{!--[^\}]*--\}\}/g, '') // remove comments
.replace(/\{\{#if ([^\}]*)\}\}/g, "');if(data.$1){p.push('") // opening if
.replace(/\{\{\/if\}\}/g, "');}p.push('") // closing if
.replace(/\{\{/g, "');p.push(data.")
.replace(/\}\}/g, ");p.push('") +
"');" +
'return p.join("");}';
return str;
};
grunt.file.write('src/template.js', process(template));
grunt.log.writeln('template.js created successfully');
});
var banner = '/*! qunit-image v<%= pkg.version %> MathLib.de | MathLib.de/en/license */';
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
concat: {
qunit_image: {
src: ['src/template.js', 'src/qunit-image.js'],
dest: 'build/qunit-image.js',
options: {
banner: '// qunit-image.js is an QUnit addon for comparing images.\n' +
'//\n' +
'// ## Version\n' +
'// v<%= pkg.version %> - <%= grunt.template.today("yyyy-mm-dd") %> \n' +
'//\n' +
'// ## License\n' +
'// Copyright © <%= grunt.template.today("yyyy") %> Alexander Zeilmann \n' +
'// qunit-image.js is [licensed under the MIT license](<http://MathLib.de/en/license>)\n' +
'//\n' +
'// ## Documentation\n' +
'// The source code is annotated using [Docco](https://github.com/jashkenas/docco "View Docco on GitHub")\n\n' +
'(function () {\n',
sepatator: '\n\n',
footer: '})()'
}
}
},
// Testing
qunit: {
index: ['test/test.html', 'test/test.min.html']
},
// JS Linting
jshint: {
all: ['Gruntfile.js', 'src/qunit-image.js'],
options: {
jshintrc: '.jshintrc'
}
},
jscs: {
qunitImage: {
options: {
config: '.jscs.json',
},
files: {
src: ['build/qunit-image.js']
}
},
Tests: {
options: {
config: '.jscs.json',
},
files: {
src: ['test/qunit-image.test.js']
}
},
Grunt: {
options: {
config: '.jscs.json',
},
files: {
src: ['Gruntfile.js']
}
}
},
// CSS Linting
csslint: {
qunit_image: {
options: {
csslintrc: '.csslintrc'
},
src: ['build/qunit-image.css']
}
},
// JS Minification
uglify: {
qunit_image: {
options: {
banner: banner + '\n'
},
files: {
'build/qunit-image.min.js': ['build/qunit-image.js']
}
}
},
// CSS Minification
cssmin: {
qunit_image: {
options: {
banner: banner
},
files: {
'build/qunit-image.min.css': ['build/qunit-image.css']
}
}
},
// SCSS
compass: {
qunit_image: {
options: {
sassDir: 'src/',
cssDir: 'build/',
outputStyle: 'expanded',
noLineComments: true
}
}
},
// Watch
watch: {
js: {
files: ['src/qunit-image.js'],
tasks: ['concat', 'uglify']
},
scss: {
files: ['src/qunit-image.scss'],
tasks: ['compass', 'cssmin', 'csslint']
},
hbs: {
files: ['src/qunit-image.hbs'],
tasks: ['template', 'concat', 'uglify']
}
},
// Documentation
docco: {
qunit_image: {
src: ['build/qunit-image.js'],
options: {
output: 'docs/'
}
},
qunit_image_css: {
src: ['src/qunit-image.scss'],
options: {
output: 'docs/'
}
}
}
});
grunt.registerTask('default', ['template', 'concat', 'uglify']);
grunt.registerTask('release', ['default', 'compass', 'cssmin', 'jshint', 'jscs', 'csslint', 'docco']);
};
|
#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
var pack = path.join(__dirname, '..', 'package.json');
var packageJSON = require(pack);
packageJSON.version = packageJSON.version.split('.');
packageJSON.version[2] = parseInt(packageJSON.version[2]);
packageJSON.version[2]++;
packageJSON.version = packageJSON.version.join('.');
packageJSON = JSON.stringify(packageJSON, null, '\t');
fs.writeFile(pack, packageJSON, function (err) {
if(err) console.error(err);
process.exit();
});
|
if (!window.JST) {
window.JST = {};
}
window.JST["tests/fixtures/advanced-example"] = function(__obj) {
if (!__obj) __obj = {};
var __out = [], __capture = function(callback) {
var out = __out, result;
__out = [];
callback.call(this);
result = __out.join('');
__out = out;
return __safe(result);
}, __sanitize = function(value) {
if (value && value.ecoSafe) {
return value;
} else if (typeof value !== 'undefined' && value != null) {
return __escape(value);
} else {
return '';
}
}, __safe, __objSafe = __obj.safe, __escape = __obj.escape;
__safe = __obj.safe = function(value) {
if (value && value.ecoSafe) {
return value;
} else {
if (!(typeof value !== 'undefined' && value != null)) value = '';
var result = new String(value);
result.ecoSafe = true;
return result;
}
};
if (!__escape) {
__escape = __obj.escape = function(value) {
return ('' + value)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"');
};
}
(function() {
(function() {
var i, len, project, ref;
if (this.projects.length) {
__out.push('\n ');
ref = this.projects;
for (i = 0, len = ref.length; i < len; i++) {
project = ref[i];
__out.push('\n <a href="');
__out.push(__sanitize(project.url));
__out.push('">');
__out.push(__sanitize(project.name));
__out.push('</a>\n <p>');
__out.push(__sanitize(project.description));
__out.push('</p>\n ');
}
__out.push('\n');
} else {
__out.push('\n No projects\n');
}
__out.push('\n');
}).call(this);
}).call(__obj);
__obj.safe = __objSafe, __obj.escape = __escape;
return __out.join('');
}
|
var http = require('http');
var ecstatic = require('ecstatic');
var ecstaticOpts = { root: __dirname };
http.createServer(
ecstatic(ecstaticOpts)
).listen(8080);
console.log('Listening on :8080');
console.log('%s', JSON.stringify(ecstaticOpts, null, 2));
|
Session.setDefault("showAddRegionPanel", false);
Session.setDefault("modifyRegionPanel", false);
Session.setDefault("modifyRegionCode", '');
Session.setDefault("modifyRegionTitle", '');
Session.setDefault("modifyRegionParent", '');
Session.setDefault("modifyRegionID", '');
Template.regionManagerTemplate.helpers({
//下面的辅助函数是为了控制界面显示
"showAddRegionPanel": function () {
return Session.get("showAddRegionPanel");
},
//下面的辅助函数是为了界面多语言
"langRegionManagement": function () {
return Session.get("langRegionManagement");
},
"langAdd": function () {
return Session.get("langAdd");
}
});
Template.regionListTemplate.helpers({
//下面的辅助函数是为了控制界面显示
"regions": function () {
return gRegions.find();
},
"getRegionParent": function (p) {
var o = gRegions.findOne({code: p});
if(o && o.title){
return o.title;
}else{
return "";
}
},
//下面的辅助函数是为了界面多语言
"langRegionCode": function () {
return Session.get("langRegionCode");
},
"langRegionTitle": function () {
return Session.get("langRegionTitle");
},
"langRegionParent": function () {
return Session.get("langRegionParent");
}
});
Template.addRegionTemplate.helpers({
"selected":function(v1,v2){
if(v1===v2){
return true;
}else{
return false;
}
},
//下面的辅助函数是为了控制界面显示
"modifyRegionPanel": function () {
return Session.get("modifyRegionPanel");
},
"regions": function () {
return gRegions.find();
},
"modifyRegionCode": function () {
return Session.get("modifyRegionCode");
},
"modifyRegionTitle": function () {
return Session.get("modifyRegionTitle");
},
"modifyRegionParent": function () {
return Session.get("modifyRegionParent");
},
"modifyRegionID": function () {
return Session.get("modifyRegionID");
},
//错误处理
"verifyRegionCodeError": function () {
return Session.get("verifyRegionCodeError");
},
"verifyRegionTitleError": function () {
return Session.get("verifyRegionTitleError");
},
//下面的辅助函数是为了界面多语言
"langAdd": function () {
return Session.get("langAdd");
},
"langSelect": function () {
return Session.get("langSelect");
},
"langModify": function () {
return Session.get("langModify");
},
"langRegionCode": function () {
return Session.get("langRegionCode");
},
"langRegionTitle": function () {
return Session.get("langRegionTitle");
},
"langRegionParent": function () {
return Session.get("langRegionParent");
}
});
function initInputField() {
Session.set('verifyRegionCodeError', '');
Session.set('verifyRegionTitleError', '');
Session.set('modifyRegionID', '');
Session.set('modifyRegionParent', '');
Session.set('modifyRegionTitle', '');
Session.set('modifyRegionCode', '');
}
function setInputField(region) {
Session.set('verifyRegionCodeError', '');
Session.set('verifyRegionTitleError', '');
Session.set('modifyRegionID', region._id);
Session.set('modifyRegionParent', region.parentCode);
Session.set('modifyRegionTitle', region.title);
Session.set('modifyRegionCode', region.code);
}
Template.regionManagerTemplate.events({
'click #btn_show_or_hide_addRegion_panel': function (e) {
var v1 = Session.get('showAddRegionPanel');
var v2 = Session.get('modifyRegionPanel');
if (v1 === true && v2 === true) {
//情况1:v1=true表示面板已经打开,v2=true表示现在是修改状态,所以这时候按这个按钮,应该切换为添加状态,保持面板打开
Session.set("modifyRegionPanel", false);
initInputField();
}
if (v1 === true && v2 === false) {
//情况2: v1=true表示面板已经打开,v2=true表示现在是添加状态,所以这时候按这个按钮,就应该把面板收起来
Session.set("showAddRegionPanel", false);
}
if (v1 === false && v2 === true) {
//情况3: v1=false表示面板未打开,v2=true表示现在是添加状态,所以这时候按这个按钮,就应该切换为添加状态,且把面板打开
Session.set("showAddRegionPanel", true);
Session.set("modifyRegionPanel", false);
initInputField();
}
if (v1 === false && v2 === false) {
//情况4: v1=false表示面板未打开,v2=false表示现在是新建状态,所以这时候按这个按钮,就应该把面板打开
Session.set("showAddRegionPanel", true);
initInputField();
}
}
});
Template.addRegionTemplate.events({
'click #btn_add_region': function (e) {
var region = {};
region.code = $('#input_region_code').val();
if (region.code === "") {
Session.set('verifyRegionCodeError', Session.get('langErrorCannotEmpty'));
return;
} else {
Session.set('verifyRegionCodeError', '');
}
region.title = $('#input_region_title').val();
if (region.title === "") {
Session.set('verifyRegionTitleError', Session.get('langErrorCannotEmpty'));
return;
} else {
Session.set('verifyRegionTitleError', '');
}
region.parentCode = $('#input_region_parent').val();
console.log(region);
if (Session.get('modifyRegionPanel') === false) {
//create
Meteor.call("addNewRegion", region, function (error, result) {
if (result.error !== "OK") {
alert(Session.get(result.error));
} else {
initInputField();
}
});
} else {
//modify
Meteor.call("updateRegion", Session.get("modifyRegionID"), region, function (error, result) {
if (!error) {
if (result && result.error && result.error !== "OK") {
alert(Session.get(result.error));
} else {
//initInputField();
}
}
});
}
}
});
Template.regionListTemplate.events({
'click .regionRemove': function (e) {
var id = e.currentTarget.value;
if (confirm(Session.get('langAreYouSure')) === true) {
Meteor.call('removeRegion', id, function (error, result) {
if (!error) {
if (result && result.error && result.error !== 'OK') {
alert(Session.get(result.error));
}
}
});
}
}
,
"click .regionEdit": function (e) {
var id = e.currentTarget.value;
var region = gRegions.findOne({_id: id});
console.log(region);
setInputField(region);
Session.set("modifyRegionPanel",true);
Session.set("showAddRegionPanel", true);
}
});
|
import { MDCIconToggle } from '@material/icon-toggle'
import { SMCAdapter } from '../base'
export default class IconToggleAdapter extends SMCAdapter {
constructor ({ sel, elm, data }) {
super(sel, new MDCIconToggle(elm), { toggled: 'on' })
this.updateDisabled_ = props => {
this.updateBool_(props, 'disabled')
}
this.updateOn_ = props => {
this.updateBool_(props, 'toggled')
}
this.update_ = props => {
this.updateDisabled_(props)
this.updateOn_(props)
// this.component.refreshToggleData()
}
this.update_(data.props)
}
}
|
var searchData=
[
['takeoff_3a',['takeOff:',['../interface_test_flight.html#aa91bbfe4dc0dd136d89d441406fef909',1,'TestFlight']]],
['tryandsenddata_3awitherrortofire_3aandwithpositiveresponse_3a',['tryAndSendData:withErrorToFire:andWithPositiveResponse:',['../interface_base_object.html#a2e718a69de78d1a650bb62c8a2bba427',1,'BaseObject']]]
];
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.